resolved conflict

This commit is contained in:
Daniel Maya 2022-10-14 09:10:25 +02:00
commit 3e9e04642d
155 changed files with 74699 additions and 115748 deletions

View File

@ -282,6 +282,8 @@ server_dependencies=" \
expect \
openssh-clients \
java \
bind-utils \
whois \
http://firefly.artica.es/centos7/xprobe2-0.3-12.2.x86_64.rpm \
http://firefly.artica.es/centos7/wmic-1.4-1.el7.x86_64.rpm \
https://firefly.artica.es/centos7/pandorawmic-1.0.0-1.x86_64.rpm"

View File

@ -338,6 +338,8 @@ server_dependencies=" \
expect \
openssh-clients \
java \
bind-utils \
whois \
http://firefly.artica.es/centos7/xprobe2-0.3-12.2.x86_64.rpm \
http://firefly.artica.es/centos7/wmic-1.4-1.el7.x86_64.rpm \
https://firefly.artica.es/centos8/pandorawmic-1.0.0-1.x86_64.rpm"

View File

@ -0,0 +1,743 @@
#!/bin/bash
##############################################################################################################
# PandoraFMS Community online installation script for Ubuntu 22.04
##############################################################################################################
## Tested versions ##
# Ubuntu 22.04.1
#avoid promps
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_SUSPEND=1
#Constants
PANDORA_CONSOLE=/var/www/html/pandora_console
PANDORA_SERVER_CONF=/etc/pandora/pandora_server.conf
PANDORA_AGENT_CONF=/etc/pandora/pandora_agent.conf
WORKDIR=/opt/pandora/deploy
S_VERSION='2022052501'
LOGFILE="/tmp/pandora-deploy-community-$(date +%F).log"
# define default variables
[ "$TZ" ] || TZ="Europe/Madrid"
[ "$PHPVER" ] || PHPVER=7.4
[ "$DBHOST" ] || DBHOST=127.0.0.1
[ "$DBNAME" ] || DBNAME=pandora
[ "$DBUSER" ] || DBUSER=pandora
[ "$DBPASS" ] || DBPASS=pandora
[ "$DBPORT" ] || DBPORT=3306
[ "$DBROOTPASS" ] || DBROOTPASS=pandora
[ "$SKIP_PRECHECK" ] || SKIP_PRECHECK=0
[ "$SKIP_DATABASE_INSTALL" ] || SKIP_DATABASE_INSTALL=0
[ "$SKIP_KERNEL_OPTIMIZATIONS" ] || SKIP_KERNEL_OPTIMIZATIONS=0
[ "$POOL_SIZE" ] || POOL_SIZE=$(grep -i total /proc/meminfo | head -1 | awk '{printf "%.2f \n", $(NF-1)*0.4/1024}' | sed "s/\\..*$/M/g")
[ "$PANDORA_BETA" ] || PANDORA_BETA=0
# Ansi color code variables
red="\e[0;91m"
green="\e[0;92m"
cyan="\e[0;36m"
reset="\e[0m"
# Functions
execute_cmd () {
local cmd="$1"
local msg="$2"
echo -e "${cyan}$msg...${reset}"
$cmd &>> "$LOGFILE"
if [ $? -ne 0 ]; then
echo -e "${red}Fail${reset}"
[ "$3" ] && echo "$3"
echo "Error installing Pandora FMS for detailed error please check log: $LOGFILE"
rm -rf "$WORKDIR" &>> "$LOGFILE"
exit 1
else
echo -e "\e[1A\e ${cyan}$msg...${reset} ${green}OK${reset}"
return 0
fi
}
check_cmd_status () {
if [ $? -ne 0 ]; then
echo -e "${red}Fail${reset}"
[ "$1" ] && echo "$1"
echo "Error installing Pandora FMS for detailed error please check log: $LOGFILE"
rm -rf "$WORKDIR" &>> "$LOGFILE"
exit 1
else
echo -e "${green}OK${reset}"
return 0
fi
}
check_pre_pandora () {
export MYSQL_PWD=$DBPASS
echo -en "${cyan}Checking environment ... ${reset}"
[ -d "$PANDORA_CONSOLE" ] && local fail=true
[ -f /usr/bin/pandora_server ] && local fail=true
echo "use $DBNAME" | mysql -u$DBUSER -P$DBPORT -h$DBHOST &>> /dev/null && local fail=true
[ ! $fail ]
check_cmd_status 'Error there is a current Pandora FMS installation on this node, please remove it to execute a clean install'
}
check_repo_connection () {
execute_cmd "ping -c 2 firefly.artica.es" "Checking Community repo"
execute_cmd "ping -c 2 support.pandorafms.com" "Checking Enterprise repo"
}
check_root_permissions () {
echo -en "${cyan}Checking root account... ${reset}"
if [ "$(whoami)" != "root" ]; then
echo -e "${red}Fail${reset}"
echo "Please use a root account or sudo for installing Pandora FMS"
echo "Error installing Pandora FMS for detailed error please check log: $LOGFILE"
exit 1
else
echo -e "${green}OK${reset}"
fi
}
## Main
echo "Starting PandoraFMS Community deployment Ubuntu 22.04 ver. $S_VERSION"
# Ubuntu Version
if [ ! "$(grep -Ei 'Ubuntu' /etc/lsb-release)" ]; then
printf "\n ${red}Error this is not a Ubuntu system, this installer is compatible with Ubuntu systems only${reset}\n"
exit 1
fi
echo -en "${cyan}Check Ubuntu Version...${reset}"
[ $(sed -nr 's/VERSION_ID+=\s*"([0-9][0-9].[0-9][0-9])"$/\1/p' /etc/os-release) == "22.04" ]
check_cmd_status 'Error OS version, Ubuntu 22.04 is expected'
#Detect OS
os_name=$(grep ^PRETTY_NAME= /etc/os-release | cut -d '=' -f2 | tr -d '"')
execute_cmd "echo $os_name" "OS detected: ${os_name}"
# initialice logfile
execute_cmd "echo 'Starting community deployment' > $LOGFILE" "All installer activity is logged on $LOGFILE"
echo "Community installer version: $S_VERSION" >> "$LOGFILE"
# Pre checks
# Root permisions
check_root_permissions
# Pre installed pandora
[ "$SKIP_PRECHECK" == 1 ] || check_pre_pandora
#advicing BETA PROGRAM
[ "$PANDORA_BETA" -ne '0' ] && echo -e "${red}BETA version enable using nightly PandoraFMS packages${reset}"
# Connectivity
check_repo_connection
# Systemd
execute_cmd "systemctl --version" "Checking SystemD" 'This is not a SystemD enable system, if tryng to use in a docker env please check: https://github.com/pandorafms/pandorafms/tree/develop/extras/docker/centos8'
# Check memomry greather or equal to 2G
execute_cmd "[ $(grep MemTotal /proc/meminfo | awk '{print $2}') -ge 1700000 ]" 'Checking memory (required: 2 GB)'
# Check disk size at least 10 Gb free space
execute_cmd "[ $(df -BM / | tail -1 | awk '{print $4}' | tr -d M) -gt 10000 ]" 'Checking Disk (required: 10 GB free min)'
# Setting timezone
rm -rf /etc/localtime &>> "$LOGFILE"
execute_cmd "timedatectl set-timezone $TZ" "Setting Timezone $TZ"
# Execute tools check
execute_cmd "awk --version" 'Checking needed tools: awk'
execute_cmd "grep --version" 'Checking needed tools: grep'
execute_cmd "sed --version" 'Checking needed tools: sed'
execute_cmd "apt --version" 'Checking needed tools: dnf'
# Creating working directory
rm -rf "$WORKDIR" &>> "$LOGFILE"
mkdir -p "$WORKDIR" &>> "$LOGFILE"
execute_cmd "cd $WORKDIR" "Moving to workdir: $WORKDIR"
## Install utils
execute_cmd "apt update" "Updating repos"
execute_cmd "apt install -y net-tools vim curl wget software-properties-common apt-transport-https" "Installing utils"
#Installing Apache and php-fpm
[ -e "/etc/apt/sources.list.d/ondrej-ubuntu-php-jammy.list" ] || execute_cmd "add-apt-repository ppa:ondrej/php -y" "Enable ppa:ondrej/php repo"
execute_cmd "apt update" "Updating repos"
execute_cmd "apt install -y php$PHPVER-fpm php$PHPVER-common libapache2-mod-fcgid php$PHPVER-cli apache2" "Installing apache and php-fpm"
#execute_cmd "a2enmod proxy_fcgi setenvif && a2enconf php$PHPVER-fpm" "Enabling php-fpm"
echo -en "${cyan}Enabling php$PHPVER-fpm...${reset}"
a2enmod proxy_fcgi setenvif &>> "$LOGFILE" && a2enconf php$PHPVER-fpm &>> "$LOGFILE"
check_cmd_status "Error enabling php$PHPVER-fpm "
systemctl restart php$PHPVER-fpm &>> "$LOGFILE"
# Console dependencies
console_dependencies=" \
ldap-utils \
postfix \
wget \
graphviz \
xfonts-75dpi \
xfonts-100dpi \
xfonts-ayu \
xfonts-intl-arabic \
xfonts-intl-asian \
xfonts-intl-phonetic \
xfonts-intl-japanese-big \
xfonts-intl-european \
xfonts-intl-chinese \
xfonts-intl-japanese \
xfonts-intl-chinese-big \
libzstd1 \
gir1.2-atk-1.0 \
libavahi-common-data \
cairo-perf-utils \
libfribidi-bin \
php$PHPVER-mcrypt \
php$PHPVER-gd \
php$PHPVER-curl \
php$PHPVER-mysql \
php$PHPVER-ldap \
php$PHPVER-fileinfo \
php$PHPVER-gettext \
php$PHPVER-snmp \
php$PHPVER-mbstring \
php$PHPVER-zip \
php$PHPVER-xmlrpc \
php$PHPVER-xml \
php$PHPVER-yaml \
libnet-telnet-perl \
whois"
execute_cmd "apt install -y $console_dependencies" "Installing Pandora FMS Console dependencies"
# Server dependencies
server_dependencies=" \
perl \
nmap \
fping \
sudo \
net-tools \
nfdump \
expect \
openssh-client \
postfix \
unzip \
xprobe \
coreutils \
libio-compress-perl \
libmoosex-role-timer-perl \
libdbd-mysql-perl \
libcrypt-mysql-perl \
libhttp-request-ascgi-perl \
liblwp-useragent-chicaching-perl \
liblwp-protocol-https-perl \
snmp \
libnetaddr-ip-perl \
libio-socket-ssl-perl \
libio-socket-socks-perl \
libio-socket-ip-perl \
libio-socket-inet6-perl \
libnet-telnet-perl \
libjson-perl \
libencode-perl \
libgeo-ip-perl \
openjdk-8-jdk "
execute_cmd "apt install -y $server_dependencies" "Installing Pandora FMS Server dependencies"
# wmic and pandorawmic
execute_cmd "curl -O https://firefly.artica.es/pandorafms/utils/bin/wmic" "Downloading wmic"
execute_cmd "curl -O https://firefly.artica.es/pandorafms/utils/bin/pandorawmic" "Downloading pandorawmic"
echo -en "${cyan}Installing wmic and pandorawmic...${reset}"
chmod +x pandorawmic wmic &>> "$LOGFILE" && \
cp -a wmic /usr/bin/ &>> "$LOGFILE" && \
cp -a pandorawmic /usr/bin/ &>> "$LOGFILE"
check_cmd_status "Error Installing phanromjs"
# phantomjs
echo -en "${cyan}Installing phantomjs...${reset}"
export PHANTOM_JS="phantomjs-2.1.1-linux-x86_64"
export OPENSSL_CONF=/etc/ssl
curl -LSs -O "https://firefly.artica.es/pandorafms/utils/$PHANTOM_JS.tar.bz2" &>> "$LOGFILE" && \
tar xvjf "$PHANTOM_JS.tar.bz2" &>> "$LOGFILE" && \
mv $PHANTOM_JS/bin/phantomjs /usr/bin &>> "$LOGFILE" && \
/usr/bin/phantomjs --version &>> "$LOGFILE"
check_cmd_status "Error Installing phanromjs"
# SDK VMware perl dependencies
vmware_dependencies=" \
lib32z1 \
lib32z1 \
build-essential \
uuid uuid-dev \
libssl-dev \
perl-doc \
libxml-libxml-perl \
libcrypt-ssleay-perl \
libsoap-lite-perl \
libmodule-build-perl"
execute_cmd "apt install -y $vmware_dependencies" "Installing VMware SDK dependencies"
execute_cmd "wget https://firefly.artica.es/pandorafms/utils/VMware-vSphere-Perl-SDK-7.0.0-16453907.x86_64.tar.gz" "Downloading VMware SDK"
echo -en "${cyan}Installing VMware SDK...${reset}"
tar xvzf VMware-vSphere-Perl-SDK-7.0.0-16453907.x86_64.tar.gz &>> "$LOGFILE"
cd vmware-vsphere-cli-distrib/ &>> "$LOGFILE"
sed --follow-symlinks -i -e "s/[^#].*show_EULA().*/ #show_EULA();/g" vmware-install.pl &>> "$LOGFILE"
./vmware-install.pl --default &>> "$LOGFILE"
check_cmd_status "Error Installing VMware SDK"
execute_cmd "cpan Crypt::OpenSSL::AES" "Installing extra vmware dependencie"
cd $WORKDIR &>> "$LOGFILE"
# Instant client Oracle
execute_cmd "mkdir -p /opt/oracle" "Creating Oracle instant client directory /opt/oracle"
execute_cmd "wget https://download.oracle.com/otn_software/linux/instantclient/19800/instantclient-basic-linux.x64-19.8.0.0.0dbru.zip" "Downloading Oracle instant client"
execute_cmd "wget https://download.oracle.com/otn_software/linux/instantclient/19800/instantclient-sqlplus-linux.x64-19.8.0.0.0dbru.zip" "Downloading Oracle sqlplus"
echo -en "${cyan}Installing Oracle instant client...${reset}"
rm -fr /opt/oracle/* &>> "$LOGFILE"
unzip instantclient-basic-linux.x64-19.8.0.0.0dbru.zip -d /opt/oracle/ &>> "$LOGFILE"
unzip instantclient-sqlplus-linux.x64-19.8.0.0.0dbru.zip -d /opt/oracle/ &>> "$LOGFILE"
check_cmd_status "Error Installing Oracle instant client"
#Configuring env variables
cat >> /root/.profile << 'EOF_ENV'
#!/bin/bash
VERSION=19.8
export PATH=$PATH:/opt/oracle/instantclient_19_8
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/oracle/instantclient_19_8
export ORACLE_HOME=/opt/oracle/instantclient_19_8
EOF_ENV
source '/root/.profile' &>> "$LOGFILE"
#ipam dependencies
ipam_dependencies=" \
xprobe \
libnetaddr-ip-perl \
coreutils \
libdbd-mysql-perl \
libxml-simple-perl \
libgeo-ip-perl \
libio-socket-inet6-perl \
libxml-twig-perl \
libnetaddr-ip-perl"
execute_cmd "apt install -y $ipam_dependencies" "Installing IPAM Dependencies"
# MSSQL dependencies el8
curl -sSL https://packages.microsoft.com/keys/microsoft.asc | tee /etc/apt/trusted.gpg.d/microsoft.asc &>> "$LOGFILE"
curl -sSL https://packages.microsoft.com/config/ubuntu/20.04/prod.list | tee /etc/apt/sources.list.d/microsoft-prod.list &>> "$LOGFILE"
apt update &>> "$LOGFILE"
execute_cmd "env ACCEPT_EULA=Y apt install -y msodbcsql17" "Installing ODBC Driver for Microsoft(R) SQL Server(R)"
MS_ID=$(head -1 /etc/odbcinst.ini | tr -d '[]') &>> "$LOGFILE"
# Disabling apparmor and ufw
systemctl stop ufw.service &>> "$LOGFILE"
systemctl disable ufw &>> "$LOGFILE"
systemctl stop apparmor &>> "$LOGFILE"
systemctl disable apparmor &>> "$LOGFILE"
#install mysql
debconf-set-selections <<< $(echo -n "mysql-server mysql-server/root_password password $DBROOTPASS") &>> "$LOGFILE"
debconf-set-selections <<< $(echo -n "mysql-server mysql-server/root_password_again password $DBROOTPASS") &>> "$LOGFILE"
echo -en "${cyan}Installing MySql Server...${reset}"
env DEBIAN_FRONTEND=noninteractive apt install -y mysql-server &>> "$LOGFILE"
check_cmd_status "Error Installing MySql Server"
#Configuring Database
if [ "$SKIP_DATABASE_INSTALL" -eq '0' ] ; then
execute_cmd "systemctl start mysql" "Starting database engine"
export MYSQL_PWD=$DBROOTPASS
echo -en "${cyan}Creating Pandora FMS database...${reset}"
echo "create database $DBNAME" | mysql -uroot -P$DBPORT -h$DBHOST
check_cmd_status "Error creating database $DBNAME, is this an empty node? if you have a previus installation please contact with support."
echo "CREATE USER \"$DBUSER\"@'%' IDENTIFIED BY \"$DBPASS\";" | mysql -uroot -P$DBPORT -h$DBHOST
echo "ALTER USER \"$DBUSER\"@'%' IDENTIFIED WITH mysql_native_password BY \"$DBPASS\"" | mysql -uroot -P$DBPORT -h$DBHOST
echo "GRANT ALL PRIVILEGES ON $DBNAME.* TO \"$DBUSER\"@'%'" | mysql -uroot -P$DBPORT -h$DBHOST
fi
export MYSQL_PWD=$DBPASS
#Generating my.cnf
cat > /etc/mysql/my.cnf << EOF_DB
[mysqld]
datadir=/var/lib/mysql
user=mysql
character-set-server=utf8
skip-character-set-client-handshake
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Mysql optimizations for Pandora FMS
# Please check the documentation in http://pandorafms.com for better results
max_allowed_packet = 64M
innodb_buffer_pool_size = $POOL_SIZE
innodb_lock_wait_timeout = 90
innodb_file_per_table
innodb_flush_log_at_trx_commit = 0
innodb_flush_method = O_DIRECT
innodb_log_file_size = 64M
innodb_log_buffer_size = 16M
innodb_io_capacity = 100
thread_cache_size = 8
thread_stack = 256K
max_connections = 100
key_buffer_size=4M
read_buffer_size=128K
read_rnd_buffer_size=128K
sort_buffer_size=128K
join_buffer_size=4M
sql_mode=""
log-error=/var/log/mysql/error.log
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
EOF_DB
execute_cmd "systemctl restart mysql" "Configuring and restarting database engine"
#Define packages
if [ "$PANDORA_BETA" -eq '0' ] ; then
[ "$PANDORA_SERVER_PACKAGE" ] || PANDORA_SERVER_PACKAGE="http://firefly.artica.es/pandorafms/latest/Tarball/pandorafms_server-7.0NG.tar.gz"
[ "$PANDORA_CONSOLE_PACKAGE" ] || PANDORA_CONSOLE_PACKAGE="http://firefly.artica.es/pandorafms/latest/Tarball/pandorafms_console-7.0NG.tar.gz"
[ "$PANDORA_AGENT_PACKAGE" ] || PANDORA_AGENT_PACKAGE="http://firefly.artica.es/pandorafms/latest/Tarball/pandorafms_agent_unix-7.0NG.tar.gz"
elif [ "$PANDORA_BETA" -ne '0' ] ; then
[ "$PANDORA_SERVER_PACKAGE" ] || PANDORA_SERVER_PACKAGE="http://firefly.artica.es/pandora_enterprise_nightlies/pandorafms_server-latest_x86_64.tar.gz"
[ "$PANDORA_CONSOLE_PACKAGE" ] || PANDORA_CONSOLE_PACKAGE="http://firefly.artica.es/pandora_enterprise_nightlies/pandorafms_console-latest.tar.gz"
[ "$PANDORA_AGENT_PACKAGE" ] || PANDORA_AGENT_PACKAGE="http://firefly.artica.es/pandorafms/latest/Tarball/pandorafms_agent_unix-7.0NG.tar.gz"
fi
# Downloading Pandora Packages
cd $WORKDIR &>> "$LOGFILE"
curl -LSs --output pandorafms_console-7.0NG.tar.gz "${PANDORA_CONSOLE_PACKAGE}" &>> "$LOGFILE"
curl -LSs --output pandorafms_server-7.0NG.tar.gz "${PANDORA_SERVER_PACKAGE}" &>> "$LOGFILE"
curl -LSs --output pandorafms_agent_unix-7.0NG.tar.gz "${PANDORA_AGENT_PACKAGE}" &>> "$LOGFILE"
# Install PandoraFMS Console
echo -en "${cyan}Installing PandoraFMS Console...${reset}"
tar xvzf pandorafms_console-7.0NG.tar.gz &>> "$LOGFILE" && cp -Ra pandora_console /var/www/html/ &>> "$LOGFILE"
check_cmd_status "Error installing PandoraFMS Console"
rm -f $PANDORA_CONSOLE/*.spec &>> "$LOGFILE"
# Install Pandora FMS Server
echo -en "${cyan}Installing PandoraFMS Server...${reset}"
useradd pandora &>> "$LOGFILE"
tar xvfz $WORKDIR/pandorafms_server-7.0NG.tar.gz &>> $LOGFILE && cd pandora_server && ./pandora_server_installer --install &>> $LOGFILE && cd $WORKDIR &>> $LOGFILE
check_cmd_status "Error installing PandoraFMS Server"
#Install agent:
execute_cmd "apt install -y libyaml-tiny-perl perl coreutils wget curl unzip procps python3 python3-pip" "Installing PandoraFMS Agent Dependencies"
echo -en "${cyan}Installing PandoraFMS Agent...${reset}"
tar xvzf $WORKDIR/pandorafms_agent_unix-7.0NG.tar.gz &>> "$LOGFILE" && cd unix && ./pandora_agent_installer --install &>> $LOGFILE && cp -a tentacle_client /usr/local/bin/ &>> $LOGFILE && cd $WORKDIR
check_cmd_status "Error installing PandoraFMS Agent"
# Copy gotty utility
cd $WORKDIR &>> "$LOGFILE"
execute_cmd "wget https://pandorafms.com/library/wp-content/uploads/2019/11/gotty_linux_amd64.tar.gz" 'Dowloading gotty util'
tar xvzf gotty_linux_amd64.tar.gz &>> $LOGFILE
execute_cmd "mv gotty /usr/bin/" 'Installing gotty util'
# Config servicesa
#Configure apache2
#Enable SSL connections
cat > /etc/apache2/conf-available/ssl-params.conf << EOF_PARAM
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
SSLHonorCipherOrder On
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
# Requires Apache >= 2.4
SSLCompression off
SSLUseStapling on
SSLStaplingCache "shmcb:logs/stapling-cache(150000)"
# Requires Apache >= 2.4.11
SSLSessionTickets Off
EOF_PARAM
a2enmod ssl &>> "$LOGFILE"
a2enmod headers &>> "$LOGFILE"
a2enconf ssl-params &>> "$LOGFILE"
a2ensite default-ssl &>> "$LOGFILE"
a2enconf ssl-params &>> "$LOGFILE"
apache2ctl configtest &>> "$LOGFILE"
execute_cmd "systemctl restart apache2" "Enable SSL mod and Restarting Apache2"
execute_cmd "systemctl enable mysql --now" "Enabling Database service"
execute_cmd "systemctl enable apache2 --now" "Enabling Apache2 service"
execute_cmd "systemctl enable php$PHPVER-fpm --now" "Enabling php$PHPVER-fpm service"
# Populate Database
echo -en "${cyan}Loading pandoradb.sql to $DBNAME database...${reset}"
mysql -u$DBUSER -P$DBPORT -h$DBHOST $DBNAME < $PANDORA_CONSOLE/pandoradb.sql &>> "$LOGFILE"
check_cmd_status 'Error Loading database schema'
echo -en "${cyan}Loading pandoradb_data.sql to $DBNAME database...${reset}"
mysql -u$DBUSER -P$DBPORT -h$DBHOST $DBNAME < $PANDORA_CONSOLE/pandoradb_data.sql &>> "$LOGFILE"
check_cmd_status 'Error Loading database schema data'
# Configure console
# Set console config file
cat > $PANDORA_CONSOLE/include/config.php << EO_CONFIG_F
<?php
\$config["dbtype"] = "mysql";
\$config["dbname"]="$DBNAME";
\$config["dbuser"]="$DBUSER";
\$config["dbpass"]="$DBPASS";
\$config["dbhost"]="$DBHOST";
\$config["homedir"]="$PANDORA_CONSOLE";
\$config["homeurl"]="/pandora_console";
error_reporting(0);
\$ownDir = dirname(__FILE__) . '/';
include (\$ownDir . "config_process.php");
EO_CONFIG_F
#Enable allow Override
cat > /etc/apache2/conf-enabled/pandora_security.conf << EO_CONFIG_F
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
EO_CONFIG_F
#Enable quickshell proxy
cat >> /etc/apache2/mods-enabled/00-proxy.conf << 'EO_HTTPD_WSTUNNEL'
ProxyRequests Off
<Proxy *>
Require all granted
</Proxy>
ProxyPass /ws ws://127.0.0.1:8080
ProxyPassReverse /ws ws://127.0.0.1:8080
EO_HTTPD_WSTUNNEL
# Fixing console permissions
chmod 600 $PANDORA_CONSOLE/include/config.php &>> "$LOGFILE"
chown -R www-data:www-data $PANDORA_CONSOLE &>> "$LOGFILE"
mv $PANDORA_CONSOLE/install.php $PANDORA_CONSOLE/install.done &>> "$LOGFILE"
# Prepare php.ini
## Prepare php config
ln -s /etc/php/$PHPVER/fpm/php.ini /etc/
sed --follow-symlinks -i -e "s/^max_input_time.*/max_input_time = -1/g" /etc/php.ini
sed --follow-symlinks -i -e "s/^max_execution_time.*/max_execution_time = 0/g" /etc/php.ini
sed --follow-symlinks -i -e "s/^upload_max_filesize.*/upload_max_filesize = 800M/g" /etc/php.ini
sed --follow-symlinks -i -e "s/^memory_limit.*/memory_limit = 800M/g" /etc/php.ini
sed --follow-symlinks -i -e "s/.*post_max_size =.*/post_max_size = 800M/" /etc/php.ini
sed --follow-symlinks -i -e "s/^disable_functions/;disable_functions/" /etc/php.ini
#adding 900s to httpd timeout
#echo 'TimeOut 900' > /etc/httpd/conf.d/timeout.conf
cat > /var/www/html/index.html << EOF_INDEX
<meta HTTP-EQUIV="REFRESH" content="0; url=/pandora_console/">
EOF_INDEX
execute_cmd "systemctl restart apache2" "Restarting apache2 after configuration"
execute_cmd "systemctl restart php$PHPVER-fpm" "Restarting php$PHPVER-fpm after configuration"
# prepare snmptrapd
cat > /etc/snmp/snmptrapd.conf << EOF
authCommunity log public
disableAuthorization yes
EOF
# Prepare Server conf
sed -i -e "s/^dbhost.*/dbhost $DBHOST/g" $PANDORA_SERVER_CONF
sed -i -e "s/^dbname.*/dbname $DBNAME/g" $PANDORA_SERVER_CONF
sed -i -e "s/^dbuser.*/dbuser $DBUSER/g" $PANDORA_SERVER_CONF
sed -i -e "s|^dbpass.*|dbpass $DBPASS|g" $PANDORA_SERVER_CONF
sed -i -e "s/^dbport.*/dbport $DBPORT/g" $PANDORA_SERVER_CONF
sed -i -e "s/^#.mssql_driver.*/mssql_driver $MS_ID/g" $PANDORA_SERVER_CONF
# Adding group www-data to pandora server conf.
grep -q "group www-data" $PANDORA_SERVER_CONF || \
cat >> $PANDORA_SERVER_CONF << EOF_G
#Adding group www-data to assing remote-config permission correctly for ubuntu 22.04
group www-data
EOF_G
# Enable agent remote config
sed -i "s/^remote_config.*$/remote_config 1/g" $PANDORA_AGENT_CONF
# Set Oracle environment for pandora_server
cat > /etc/pandora/pandora_server.env << 'EOF_ENV'
#!/bin/bash
VERSION=19.8
export PATH=$PATH:/opt/oracle/instantclient_19_8
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/oracle/instantclient_19_8
export ORACLE_HOME=/opt/oracle/instantclient_19_8
export OPENSSL_CONF=/etc/ssl
EOF_ENV
# Kernel optimization
if [ "$SKIP_KERNEL_OPTIMIZATIONS" -eq '0' ] ; then
cat >> /etc/sysctl.conf <<EO_KO
# Pandora FMS Optimization
# default=5
net.ipv4.tcp_syn_retries = 3
# default=5
net.ipv4.tcp_synack_retries = 3
# default=1024
net.ipv4.tcp_max_syn_backlog = 65536
# default=124928
net.core.wmem_max = 8388608
# default=131071
net.core.rmem_max = 8388608
# default = 128
net.core.somaxconn = 1024
# default = 20480
net.core.optmem_max = 81920
EO_KO
[ -d /dev/lxd/ ] || execute_cmd "sysctl --system" "Applying Kernel optimization"
fi
# Fix pandora_server.{log,error} permissions to allow Console check them
chown pandora:www-data /var/log/pandora
chmod g+s /var/log/pandora
cat > /etc/logrotate.d/pandora_server <<EO_LR
/var/log/pandora/pandora_server.log
/var/log/pandora/web_socket.log
/var/log/pandora/pandora_server.error {
su root apache
weekly
missingok
size 300000
rotate 3
maxage 90
compress
notifempty
copytruncate
create 660 pandora apache
}
/var/log/pandora/pandora_snmptrap.log {
su root apache
weekly
missingok
size 500000
rotate 1
maxage 30
notifempty
copytruncate
create 660 pandora apache
}
EO_LR
cat > /etc/logrotate.d/pandora_agent <<EO_LRA
/var/log/pandora/pandora_agent.log {
su root apache
weekly
missingok
size 300000
rotate 3
maxage 90
compress
notifempty
copytruncate
}
EO_LRA
chmod 0644 /etc/logrotate.d/pandora_server
chmod 0644 /etc/logrotate.d/pandora_agent
# Add websocket engine start script.
mv /var/www/html/pandora_console/pandora_websocket_engine /etc/init.d/ &>> "$LOGFILE"
chmod +x /etc/init.d/pandora_websocket_engine
# Start Websocket engine
/etc/init.d/pandora_websocket_engine start &>> "$LOGFILE"
# Configure websocket to be started at start.
systemctl enable pandora_websocket_engine &>> "$LOGFILE"
# Enable pandora ha service
execute_cmd "/etc/init.d/pandora_server start" "Starting Pandora FMS Server"
systemctl enable pandora_server &>> "$LOGFILE"
# starting tentacle server
execute_cmd "service tentacle_serverd start" "Starting Tentacle Server"
systemctl enable tentacle_serverd &>> "$LOGFILE"
# Enabling condole cron
execute_cmd "echo \"* * * * * root wget -q -O - --no-check-certificate http://127.0.0.1/pandora_console/enterprise/cron.php >> $PANDORA_CONSOLE/log/cron.log\" >> /etc/crontab" "Enabling Pandora FMS Console cron"
echo "* * * * * root wget -q -O - --no-check-certificate http://127.0.0.1/pandora_console/enterprise/cron.php >> $PANDORA_CONSOLE/log/cron.log" >> /etc/crontab
## Enabling agent adn configuring Agente
sed -i "s/^remote_config.*$/remote_config 1/g" $PANDORA_AGENT_CONF &>> "$LOGFILE"
execute_cmd "/etc/init.d/pandora_agent_daemon start" "Starting PandoraFSM Agent"
systemctl enable pandora_agent_daemon &>> "$LOGFILE"
#fix path phantomjs
sed --follow-symlinks -i -e "s/^openssl_conf = openssl_init/#openssl_conf = openssl_init/g" /etc/ssl/openssl.cnf &>> "$LOGFILE"
#SSH banner
[ "$(curl -s ifconfig.me)" ] && ipplublic=$(curl -s ifconfig.me)
cat > /etc/issue.net << EOF_banner
Welcome to Pandora FMS appliance on CentOS
------------------------------------------
Go to Public http://$ipplublic/pandora_console$to to login web console
$(ip addr | grep -w "inet" | grep -v "127.0.0.1" | grep -v "172.17.0.1" | awk '{print $2}' | awk -F '/' '{print "Go to Local http://"$1"/pandora_console to login web console"}')
You can find more information at http://pandorafms.com
EOF_banner
rm -f /etc/issue
ln -s /etc/issue.net /etc/issue
echo 'Banner /etc/issue.net' >> /etc/ssh/sshd_config
# Remove temporary files
execute_cmd "echo done" "Pandora FMS Community installed"
cd "$HOME"
execute_cmd "rm -rf $WORKDIR" "Removing temporary files"
# Print nice finish message
GREEN='\033[01;32m'
NONE='\033[0m'
printf " -> Go to Public ${green}http://"$ipplublic"/pandora_console${reset} to manage this server"
ip addr | grep -w "inet" | grep -v "127.0.0.1" | grep -v -e "172.1[0-9].0.1" | awk '{print $2}' | awk -v g=$GREEN -v n=$NONE -F '/' '{printf "\n -> Go to Local "g"http://"$1"/pandora_console"n" to manage this server \n -> Use these credentials to log in Pandora Console "g"[ User: admin / Password: pandora ]"n" \n"}'

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, AIX version
# Version 7.0NG.765, AIX version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, FreeBSD Version
# Version 7.0NG.765, FreeBSD Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, HP-UX Version
# Version 7.0NG.765, HP-UX Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, GNU/Linux
# Version 7.0NG.765, GNU/Linux
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, GNU/Linux
# Version 7.0NG.765, GNU/Linux
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, Solaris Version
# Version 7.0NG.765, Solaris Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,6 +1,6 @@
# Base config file for Pandora FMS Windows Agent
# (c) 2006-2021 Artica Soluciones Tecnologicas
# Version 7.0NG.764
# Version 7.0NG.765
# 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
# Foundation; either version 2 of the Licence or any later version

View File

@ -1,6 +1,6 @@
# Fichero de configuracion base de agentes de Pandora
# Base config file for Pandora agents
# Version 7.0NG.764, AIX version
# Version 7.0NG.765, AIX version
# General Parameters
# ==================

View File

@ -1,6 +1,6 @@
# Fichero de configuracion base de agentes de Pandora
# Base config file for Pandora agents
# Version 7.0NG.764
# Version 7.0NG.765
# FreeBSD/IPSO version
# Licenced under GPL licence, 2003-2007 Sancho Lerena

View File

@ -1,6 +1,6 @@
# Fichero de configuracion base de agentes de Pandora
# Base config file for Pandora agents
# Version 7.0NG.764, HPUX Version
# Version 7.0NG.765, HPUX Version
# General Parameters
# ==================

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764
# Version 7.0NG.765
# Licensed under GPL license v2,
# (c) 2003-2021 Artica Soluciones Tecnologicas
# please visit http://pandora.sourceforge.net

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764
# Version 7.0NG.765
# Licensed under GPL license v2,
# (c) 2003-2021 Artica Soluciones Tecnologicas
# please visit http://pandora.sourceforge.net

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764
# Version 7.0NG.765
# Licensed under GPL license v2,
# please visit http://pandora.sourceforge.net

View File

@ -1,6 +1,6 @@
# Fichero de configuracion base de agentes de Pandora
# Base config file for Pandora agents
# Version 7.0NG.764, Solaris version
# Version 7.0NG.765, Solaris version
# General Parameters
# ==================

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, AIX version
# Version 7.0NG.765, AIX version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
package: pandorafms-agent-unix
Version: 7.0NG.764-220920
Version: 7.0NG.765-221014
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.764-220920"
pandora_version="7.0NG.765-221014"
echo "Test if you has the tools for to make the packages."
whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null

View File

@ -31,7 +31,7 @@ fi
if [ "$#" -ge 2 ]; then
VERSION="$2"
else
VERSION="7.0NG.764"
VERSION="7.0NG.765"
fi
# Path for the generated DMG file

View File

@ -19,11 +19,11 @@
<choice id="com.pandorafms.pandorafms_src" visible="false">
<pkg-ref id="com.pandorafms.pandorafms_src"/>
</choice>
<pkg-ref id="com.pandorafms.pandorafms_src" version="7.0NG.764" onConclusion="none">pandorafms_src.pdk</pkg-ref>
<pkg-ref id="com.pandorafms.pandorafms_src" version="7.0NG.765" onConclusion="none">pandorafms_src.pdk</pkg-ref>
<choice id="com.pandorafms.pandorafms_uninstall" visible="true" customLocation="/Applications">
<pkg-ref id="com.pandorafms.pandorafms_uninstall"/>
</choice>
<pkg-ref id="com.pandorafms.pandorafms_uninstall" version="7.0NG.764" onConclusion="none">pandorafms_uninstall.pdk</pkg-ref>
<pkg-ref id="com.pandorafms.pandorafms_uninstall" version="7.0NG.765" onConclusion="none">pandorafms_uninstall.pdk</pkg-ref>
<!-- <installation-check script="check()" />
<script>
<![CDATA[

View File

@ -5,9 +5,9 @@
<key>CFBundleIconFile</key> <string>pandorafms.icns</string>
<key>CFBundleIdentifier</key> <string>com.pandorafms.pandorafms_uninstall</string>
<key>CFBundleVersion</key> <string>7.0NG.764</string>
<key>CFBundleGetInfoString</key> <string>7.0NG.764 Pandora FMS Agent uninstaller for MacOS by Artica ST on Aug 2020</string>
<key>CFBundleShortVersionString</key> <string>7.0NG.764</string>
<key>CFBundleVersion</key> <string>7.0NG.765</string>
<key>CFBundleGetInfoString</key> <string>7.0NG.765 Pandora FMS Agent uninstaller for MacOS by Artica ST on Aug 2020</string>
<key>CFBundleShortVersionString</key> <string>7.0NG.765</string>
<key>NSPrincipalClass</key><string>NSApplication</string>
<key>NSMainNibFile</key><string>MainMenu</string>

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, GNU/Linux
# Version 7.0NG.765, GNU/Linux
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, FreeBSD Version
# Version 7.0NG.765, FreeBSD Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, HP-UX Version
# Version 7.0NG.765, HP-UX Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, GNU/Linux
# Version 7.0NG.765, GNU/Linux
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com
@ -165,9 +165,15 @@ remote_config 0
# should consider changing the temporal directory, since /tmp is world writable.
xml_buffer 1
# Minimum available bytes in the temporal directory to enable the XML buffer
# Minimum available megabytes in the temporal directory to enable the XML buffer
temporal_min_size 1024
# Maximum size (in megabytes) allowed for the XML buffer.
temporal_max_size 1024
# Maximum number of files allowed for the XML buffer.
temporal_max_files 1024
# Agent mode: Learn (default), No-learn, Autodisable
# agent_mode autodisable

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, GNU/Linux
# Version 7.0NG.765, GNU/Linux
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, NetBSD Version
# Version 7.0NG.765, NetBSD Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1,5 +1,5 @@
# Base config file for Pandora FMS agents
# Version 7.0NG.764, Solaris Version
# Version 7.0NG.765, Solaris Version
# Licensed under GPL license v2,
# Copyright (c) 2003-2021 Artica Soluciones Tecnologicas
# http://www.pandorafms.com

View File

@ -1014,8 +1014,8 @@ my $Sem = undef;
# Semaphore used to control the number of threads
my $ThreadSem = undef;
use constant AGENT_VERSION => '7.0NG.764';
use constant AGENT_BUILD => '220920';
use constant AGENT_VERSION => '7.0NG.765';
use constant AGENT_BUILD => '221014';
# Agent log default file size maximum and instances
use constant DEFAULT_MAX_LOG_SIZE => 600000;
@ -1145,7 +1145,9 @@ my %DefaultConf = (
'secondary_server_opts' => '',
'secondary_temporal' => '/var/spool/pandora',
'autotime' => 0,
'temporal_min_size' => 1,
'temporal_min_size' => 1024,
'temporal_max_files' => 1024,
'temporal_max_size' => 1024,
'timezone_offset' => 0,
'pandora_exec' => 'pandora_agent_exec',
'agent_threads' => 1,
@ -2110,13 +2112,13 @@ sub send_xml_file ($) {
swap_servers();
# Secondary buffer.
if ($rc_sec != 0 && $Conf{'xml_buffer'} == 1 && temporal_freedisk () > $Conf{'temporal_min_size'}) {
if ($rc_sec != 0 && write_to_buffer($Conf{'secondary_temporal'}) == 1) {
copy($file, $Conf{'secondary_temporal'}) || die("Error copying file $file to " . $Conf{'secondary_temporal'} . ": $!");
}
}
# Primary buffer.
if ($rc == 0 || $Conf{'xml_buffer'} == 0 || temporal_freedisk () <= $Conf{'temporal_min_size'}) {
if ($rc == 0 || write_to_buffer($Conf{'temporal'}) == 0) {
if ($Conf{'debug'} eq '1') {
rename($file, $file . "sent");
} else {
@ -3761,20 +3763,45 @@ sub kill_signal_handler (){
}
################################################################################
# Get the free disk space in the temporal directory (in bytes).
# Get the free disk space in the temporal directory (in megabytes).
################################################################################
sub temporal_freedisk () {
sub temporal_freedisk {
my ($temporal) = @_;
# Call df
return 0 unless defined (DF_CMDS->{$OS});
my $cmd = DF_CMDS->{$OS} . ' ' . $Conf{'temporal'} . ' | awk \'NR > 1 {print $4}\'';
my $cmd = DF_CMDS->{$OS} . ' ' . $temporal . ' | awk \'NR > 1 {print $4}\'';
my $temporal_freedisk = `$cmd`;
# Check for errors
return 0 unless ($? eq 0);
# Convert to bytes
return 1024 * int ($temporal_freedisk);
# Convert from KB to MB.
return $temporal_freedisk / 1024;
}
################################################################################
# Return the number of data files in the temporal directory and their total
# size (in megabytes).
################################################################################
sub temporal_stats {
my ($temporal) = @_;
my $file_count = 0;
my $file_size = 0;
opendir(my $dir, $temporal) or die($!);
while (my $f = readdir($dir)) {
if ($f =~ m/.data$/ || $f =~ m/.datasent$/) {
$file_count += 1;
$file_size += (stat $temporal . '/' . $f)[7];
}
}
closedir($dir);
# Convert from B to MB.
$file_size /= 1048576;
return ($file_count, $file_size);
}
################################################################################
@ -3960,6 +3987,27 @@ sub get_ehkey {
return '';
}
################################################################################
# Return 1 if XML files should be written to the buffer. 0 otherwise.
################################################################################
sub write_to_buffer {
my ($temporal) = @_;
# The XML buffer is disabled.
return 0 if ($Conf{'xml_buffer'} == 0);
# Check available disk space.
return 0 if ($Conf{'temporal_min_size'} != 0 && temporal_freedisk($temporal) < $Conf{'temporal_min_size'});
# Check buffer file count and size limits.
my ($file_count, $file_size) = temporal_stats($temporal);
return 0 if ($Conf{'temporal_max_files'} != 0 && $file_count > $Conf{'temporal_max_files'});
return 0 if ($Conf{'temporal_max_size'} != 0 && $file_size > $Conf{'temporal_max_size'});
# It's OK to write to the buffer.
return 1;
}
################################################################################
# Main.
################################################################################

View File

@ -2,8 +2,8 @@
#Pandora FMS Linux Agent
#
%define name pandorafms_agent_unix
%define version 7.0NG.764
%define release 220920
%define version 7.0NG.765
%define release 221014
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -2,8 +2,8 @@
#Pandora FMS Linux Agent
#
%define name pandorafms_agent_unix
%define version 7.0NG.764
%define release 220920
%define version 7.0NG.765
%define release 221014
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -9,8 +9,8 @@
# Please see http://www.pandorafms.org. This code is licensed under GPL 2.0 license.
# **********************************************************************
PI_VERSION="7.0NG.764"
PI_BUILD="220920"
PI_VERSION="7.0NG.765"
PI_BUILD="221014"
OS_NAME=`uname -s`
FORCE=0

View File

@ -1,6 +1,6 @@
# Base config file for Pandora FMS Windows Agent
# (c) 2006-2021 Artica Soluciones Tecnologicas
# Version 7.0NG.764
# Version 7.0NG.765
# 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
# Foundation; either version 2 of the Licence or any later version
@ -55,9 +55,15 @@ address auto
# or setting a fixed IP address, like for example:
#address 192.168.36.73
# This limits operation if temporal dir has not enough free disk.
# This limits operation if temporal dir has not enough free disk (in megabytes).
#temporal_min_size 1024
# Maximum size (in megabytes) allowed for the XML buffer.
temporal_max_size 1024
# Maximum number of files allowed for the XML buffer.
temporal_max_files 1024
# Delay start execution X second before start to monitoring nothing
#startup_delay 30

View File

@ -3,7 +3,7 @@ AllowLanguageSelection
{Yes}
AppName
{Pandora FMS Windows Agent v7.0NG.764}
{Pandora FMS Windows Agent v7.0NG.765}
ApplicationID
{17E3D2CF-CA02-406B-8A80-9D31C17BD08F}
@ -186,7 +186,7 @@ UpgradeApplicationID
{}
Version
{220920}
{221014}
ViewReadme
{Yes}

View File

@ -30,7 +30,7 @@ using namespace Pandora;
using namespace Pandora_Strutils;
#define PATH_SIZE _MAX_PATH+1
#define PANDORA_VERSION ("7.0NG.764 Build 220920")
#define PANDORA_VERSION ("7.0NG.765 Build 221014")
string pandora_path;
string pandora_dir;

View File

@ -1696,7 +1696,7 @@ Pandora_Windows_Service::checkConfig (string file) {
int
Pandora_Windows_Service::sendXml (Pandora_Module_List *modules, string extra /* = ""*/) {
int rc = 0, rc_sec = 0, xml_buffer;
int rc = 0, rc_sec = 0, xml_buffer;
string data_xml;
string xml_filename, random_integer;
string tmp_filename, tmp_filepath;
@ -1705,12 +1705,10 @@ Pandora_Windows_Service::sendXml (Pandora_Module_List *modules, string extra /*
string ehorus_conf, eh_key;
static HANDLE mutex = 0;
ULARGE_INTEGER free_bytes;
double min_free_bytes = 0;
Pandora_Agent_Conf *conf = NULL;
FILE *conf_fh = NULL;
conf = this->getConf ();
min_free_bytes = 1024 * atoi (conf->getValue ("temporal_min_size").c_str ());
xml_buffer = atoi (conf->getValue ("xml_buffer").c_str ());
if (mutex == 0) {
@ -1814,14 +1812,14 @@ Pandora_Windows_Service::sendXml (Pandora_Module_List *modules, string extra /*
rc_sec = this->copyToSecondary (tmp_filename, false);
/* Secondary buffer. */
if (rc_sec != 0 && xml_buffer == 1 && (GetDiskFreeSpaceEx (conf->getValue ("secondary_temporal").c_str (), &free_bytes, NULL, NULL) != 0 && free_bytes.QuadPart >= min_free_bytes)) {
if (rc_sec != 0 && this->writeToBuffer(conf->getValue ("secondary_temporal").c_str ())) {
secondary_filepath = conf->getValue ("secondary_temporal") + "\\" + tmp_filename;
CopyFile (tmp_filepath.c_str(), secondary_filepath.c_str(), false);
}
}
/* Primary buffer. Delete the file if successfully copied, buffer disabled or not enough space available. */
if (rc == 0 || xml_buffer == 0 || (GetDiskFreeSpaceEx (tmp_filepath.c_str (), &free_bytes, NULL, NULL) != 0 && free_bytes.QuadPart < min_free_bytes)) {
if (rc == 0 || !writeToBuffer(conf->getValue ("temporal").c_str ())) {
/* Rename the file if debug mode is enabled*/
if (getPandoraDebug ()) {
string tmp_filepath_sent = tmp_filepath;
@ -2218,3 +2216,60 @@ Pandora_Windows_Service::generateAgentName () {
sha256(data.str().c_str(), digest);
return std::string(digest);
}
bool
Pandora_Windows_Service::writeToBuffer (string temporal) {
int xml_buffer;
long int temporal_max_files;
double temporal_min_size, temporal_max_size;
string dir, file_name;
ULARGE_INTEGER free_bytes;
Pandora_Agent_Conf *conf = NULL;
conf = this->getConf ();
dir = temporal;
if (dir[dir.length () - 1] != '\\') {
dir += "\\";
}
file_name = dir + "*.data";
// Is the XML buffer disabled?
xml_buffer = atoi (conf->getValue ("xml_buffer").c_str ());
if (xml_buffer == 0) {
return false;
}
// Check available disk space.
temporal_min_size = atoi (conf->getValue ("temporal_min_size").c_str ());
if (GetDiskFreeSpaceEx (dir.c_str (), &free_bytes, NULL, NULL) && (free_bytes.QuadPart / 1048576) < temporal_min_size) { // Convert free_bytes.QuadPart from B to MB.
pandoraLog ("[writeToBuffer] Disk full.");
return false;
}
// Check buffer file count and size limits.
temporal_max_size = atoi (conf->getValue ("temporal_max_size").c_str ());
temporal_max_files = atol (conf->getValue ("temporal_max_files").c_str ());
if (temporal_max_size != 0 || temporal_max_files != 0) {
long int file_count = 0;
ULONGLONG file_size = 0;
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
if ((hFind = FindFirstFile(file_name.c_str(), &FindFileData)) != INVALID_HANDLE_VALUE) {
do {
file_count += 1;
file_size += (FindFileData.nFileSizeHigh * (MAXDWORD + 1)) + FindFileData.nFileSizeLow;
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
file_size /= 1048576; // Convert from B to MB.
if ((temporal_max_size != 0 && file_size > temporal_max_size) ||
(temporal_max_files != 0 && file_count > temporal_max_files)) {
pandoraLog ("[writeToBuffer] Too many files or buffer full.");
return false;
}
}
return true;
}

View File

@ -124,6 +124,7 @@ namespace Pandora {
long getInterval ();
long getIntensiveInterval ();
string generateAgentName ();
bool writeToBuffer (string temporal);
};
}

View File

@ -11,7 +11,7 @@ BEGIN
VALUE "LegalCopyright", "Artica ST"
VALUE "OriginalFilename", "PandoraAgent.exe"
VALUE "ProductName", "Pandora FMS Windows Agent"
VALUE "ProductVersion", "(7.0NG.764(Build 220920))"
VALUE "ProductVersion", "(7.0NG.765(Build 221014))"
VALUE "FileVersion", "1.0.0.0"
END
END

View File

@ -1,5 +1,5 @@
package: pandorafms-console
Version: 7.0NG.764-220920
Version: 7.0NG.765-221014
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.764-220920"
pandora_version="7.0NG.765-221014"
package_pear=0
package_pandora=1

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,6 @@
START TRANSACTION;
ALTER TABLE `tmodule_inventory` ADD COLUMN `script_mode` INT NOT NULL DEFAULT 2;
ALTER TABLE `tmodule_inventory` ADD COLUMN `script_path` VARCHAR(1000) DEFAULT '';
COMMIT;

View File

@ -1052,9 +1052,10 @@ if ($update_agent) {
$exists_ip = db_get_row_sql($sql);
}
$old_group = agents_get_agent_group($id_agente);
if ($grupo <= 0) {
ui_print_error_message(__('The group id %d is incorrect.', $grupo));
} else if (group_allow_more_agents($grupo, true, 'update') === false) {
} else if ($old_group !== $grupo && group_allow_more_agents($grupo, true, 'update') === false) {
ui_print_error_message(__('Agent cannot be updated due to the maximum agent limit for this group'));
} else if ($exists_ip) {
ui_print_error_message(__('Duplicate main IP address'));

View File

@ -15,6 +15,7 @@
global $config;
require_once $config['homedir'].'/include/functions_alerts.php';
require_once $config['homedir'].'/include/functions_reports.php';
enterprise_include_once('meta/include/functions_alerts_meta.php');
check_login();
@ -349,9 +350,94 @@ if (is_ajax()) {
);
} else {
$fields_value_select = [];
$fv = explode(';', $field_value);
$force_print_select = false;
if (count($fv) > 1) {
// Exception for dynamically filled select boxes.
if (preg_match('/^_reports_$/i', $field_value)) {
// Filter normal and metaconsole reports.
if (is_metaconsole() === true) {
$filter['metaconsole'] = 1;
} else {
$filter['metaconsole'] = 0;
}
$own_info = get_user_info($config['id_user']);
if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'RM') || check_acl($config['id_user'], 0, 'RR')) {
$return_all_group = true;
} else {
$return_all_group = false;
}
if (is_user_admin($config['id_user']) === false) {
$filter[] = sprintf(
'private = 0 OR (private = 1 AND id_user = "%s")',
$config['id_user']
);
}
$reports = reports_get_reports(
$filter,
[
'name',
'id_report',
],
$return_all_group,
'RR'
);
$fv = array_map(
function ($report) {
return $report['id_report'].','.$report['name'];
},
$reports
);
$force_print_select = true;
} else if (preg_match('/^_report_templates_$/i', $field_value)) {
// Filter normal and metaconsole reports.
if (is_metaconsole() === true) {
$filter['metaconsole'] = 1;
} else {
$filter['metaconsole'] = 0;
}
$own_info = get_user_info($config['id_user']);
if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'RM') || check_acl($config['id_user'], 0, 'RR')) {
$return_all_group = true;
} else {
$return_all_group = false;
}
if (is_user_admin($config['id_user']) === false) {
$filter[] = sprintf(
'private = 0 OR (private = 1 AND id_user = "%s")',
$config['id_user']
);
}
$templates = reports_get_report_templates(
$filter,
[
'name',
'id_report',
],
$return_all_group,
'RR'
);
$fv = array_map(
function ($template) {
return $template['id_report'].','.$template['name'];
},
$templates
);
$force_print_select = true;
} else {
$fv = explode(';', $field_value);
}
if (count($fv) > 1 || $force_print_select === true) {
if (!empty($fv)) {
foreach ($fv as $fv_option) {
$fv_option = explode(',', $fv_option);

View File

@ -358,7 +358,7 @@ if (!is_user_admin($config['id_user'])) {
$filter['id_group'] = array_keys(users_get_groups(false, 'LM'));
}
$total_templates = alerts_get_alert_templates($filter, ['COUNT(*) AS total']);
$total_templates = alerts_get_alert_templates($filter, ['COUNT(*) AS total'], true);
$total_templates = $total_templates[0]['total'];
$templates = alerts_get_alert_templates(

View File

@ -2335,7 +2335,7 @@ $class = 'databox filters';
<td class="bolder">
<?php
echo __('SQL query').ui_print_help_tip(
__('The entities of the fields that contain them must be included.'),
__('The entities of the fields that contain them must be included. Also is possible use macros like `_start_date_` or `_end_date_`.'),
true
);
?>

View File

@ -881,14 +881,16 @@ if (($create != '') || ($view != '')) {
'class' => 'invert_filter',
]
).'</a>&nbsp;&nbsp;';
echo "<a href='index.php?sec=$sec&sec2=godmode/servers/plugin&tab=$tab&kill_plugin=".$row['id'].'&tab=plugins&pure='.$config['pure']."' onclick='javascript: if (!confirm(\"".__('All the modules that are using this plugin will be deleted').'. '.__('Are you sure?')."\")) return false;'>".html_print_image(
'images/cross.png',
true,
[
'border' => '0',
'class' => 'invert_filter',
]
).'</a>';
if ((bool) $row['no_delete'] === false) {
echo "<a href='index.php?sec=$sec&sec2=godmode/servers/plugin&tab=$tab&kill_plugin=".$row['id'].'&tab=plugins&pure='.$config['pure']."' onclick='javascript: if (!confirm(\"".__('All the modules that are using this plugin will be deleted').'. '.__('Are you sure?')."\")) return false;'>".html_print_image(
'images/cross.png',
true,
[
'border' => '0',
'class' => 'invert_filter',
]
).'</a>';
}
echo '</td>';
}

View File

@ -238,6 +238,17 @@ foreach ($servers as $server) {
$data[8] .= '</a>';
if (($names_servers[$safe_server_name] === true) && ($server['type'] === 'data' || $server['type'] === 'enterprise satellite')) {
$data[8] .= '<a href="'.ui_get_full_url('index.php?sec=gservers&sec2=godmode/servers/modificar_server&server_remote='.$server['id_server'].'&ext='.$ext.'&tab=agent_editor').'">';
$data[8] .= html_print_image(
'images/agent.png',
true,
[
'title' => __('Manage satellite hosts'),
'class' => 'invert_filter',
]
);
$data[8] .= '</a>';
$data[8] .= '<a href="'.ui_get_full_url('index.php?sec=gservers&sec2=godmode/servers/modificar_server&server_remote='.$server['id_server'].'&ext='.$ext).'">';
$data[8] .= html_print_image(
'images/remote_configuration.png',

View File

@ -59,6 +59,8 @@ if (is_metaconsole()) {
enterprise_include_once('include/functions_license.php');
}
enterprise_include_once('include/functions_crypto.php');
if ($renew_license_result !== null) {
echo $renew_license_result;
}
@ -74,8 +76,32 @@ if ($update_settings) {
);
}
$customer_key = $_POST['keys']['customer_key'];
$license_encryption_key = get_parameter('license_encryption_key', '');
$check = db_get_value_sql('SELECT `key` FROM tupdate_settings WHERE `key` LIKE "license_encryption_key"');
if ($check === false) {
db_process_sql_insert(
'tupdate_settings',
[
db_escape_key_identifier('value') => $license_encryption_key,
db_escape_key_identifier('key') => 'license_encryption_key',
]
);
} else {
db_process_sql_update(
'tupdate_settings',
[db_escape_key_identifier('value') => $license_encryption_key],
[db_escape_key_identifier('key') => 'license_encryption_key']
);
}
if (empty($license_encryption_key) === false) {
$customer_key = openssl_blowfish_encrypt_hex($customer_key, io_safe_output($license_encryption_key));
}
// Update the license file.
$result = file_put_contents($config['remote_config'].'/'.LICENSE_FILE, $_POST['keys']['customer_key']);
$result = file_put_contents($config['remote_config'].'/'.LICENSE_FILE, $customer_key);
if ($result === false) {
ui_print_error_message(__('Failed to Update license file'));
}
@ -153,8 +179,24 @@ $table->data[7][1] = html_print_input_text('expires', ($license['nms'] == 1 ? __
$table->data[8][0] = '<strong>'.__('Satellite').'</strong>';
$table->data[8][1] = html_print_input_text('expires', ($license['dhpm'] == 1 ? __('enabled') : __('disabled')), '', 10, 255, true, true);
$table->data[9][0] = '<strong>'.__('Licensed to').'</strong>';
$table->data[9][1] = html_print_input_text('licensed_to', $license['licensed_to'], '', 64, 255, true, true);
if ($license['dhpm'] == 1) {
$table->data[9][0] = '<strong>'.__('License encryption key').'</strong>'.ui_print_help_tip(
__('This key is used to encrypt your Pandora FMS license when it is shared with other Pandora FMS components'),
true
);
$table->data[9][1] = html_print_input_password(
'license_encryption_key',
io_safe_output($settings->license_encryption_key),
'',
10,
255,
true,
false
);
}
$table->data[10][0] = '<strong>'.__('Licensed to').'</strong>';
$table->data[10][1] = html_print_input_text('licensed_to', $license['licensed_to'], '', 64, 255, true, true);
html_print_table($table);

View File

@ -34,7 +34,7 @@ check_login();
if (is_ajax()) {
$test_address = get_parameter('test_address', '');
$params = get_parameter('params', '');
$params = io_safe_output(get_parameter('params', ''));
$res = send_test_email(
$test_address,

View File

@ -1,17 +1,32 @@
<?php
/**
* User creation / update.
*
* @category Users
* @package Pandora FMS
* @subpackage Community
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2022 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.
* 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.
* ============================================================================
*/
// Pandora FMS - http://pandorafms.com
// ==================================================
// Copyright (c) 2005-2021 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.
// 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
// Load global vars.
global $config;
check_login();
@ -343,6 +358,8 @@ if ($create_user) {
$values['email'] = (string) get_parameter('email');
$values['phone'] = (string) get_parameter('phone');
$values['comments'] = io_safe_input(strip_tags(io_safe_output((string) get_parameter('comments'))));
$values['allowed_ip_active'] = ((int) get_parameter_switch('allowed_ip_active', -1) === 0);
$values['allowed_ip_list'] = io_safe_input(strip_tags(io_safe_output((string) get_parameter('allowed_ip_list'))));
$values['is_admin'] = $user_is_admin;
$values['language'] = get_parameter('language', 'default');
$values['timezone'] = (string) get_parameter('timezone');
@ -358,20 +375,20 @@ if ($create_user) {
$values['block_size'] = (int) get_parameter('block_size', $config['block_size']);
$values['section'] = get_parameter('section');
if (($values['section'] == 'Event list') || ($values['section'] == 'Group view') || ($values['section'] == 'Alert detail') || ($values['section'] == 'Tactical view') || ($values['section'] == 'Default')) {
if (($values['section'] === 'Event list') || ($values['section'] === 'Group view') || ($values['section'] === 'Alert detail') || ($values['section'] === 'Tactical view') || ($values['section'] === 'Default')) {
$values['data_section'] = '';
} else if ($values['section'] == 'Dashboard') {
} else if ($values['section'] === 'Dashboard') {
$values['data_section'] = $dashboard;
} else if (io_safe_output($values['section']) == 'Visual console') {
} else if (io_safe_output($values['section']) === 'Visual console') {
$values['data_section'] = $visual_console;
} else if ($values['section'] == 'Other' || io_safe_output($values['section']) == 'External link') {
} else if ($values['section'] === 'Other' || io_safe_output($values['section']) === 'External link') {
$values['data_section'] = get_parameter('data_section');
}
if (enterprise_installed()) {
if (enterprise_installed() === true) {
$values['force_change_pass'] = 1;
$values['last_pass_change'] = date('Y/m/d H:i:s', get_system_time());
if (defined('METACONSOLE')) {
if (is_metaconsole() === true) {
$values['metaconsole_access'] = get_parameter('metaconsole_access', 'basic');
$values['metaconsole_agents_manager'] = ($user_is_admin == 1 ? 1 : get_parameter('metaconsole_agents_manager', '0'));
$values['metaconsole_access_node'] = ($user_is_admin == 1 ? 1 : get_parameter('metaconsole_access_node', '0'));
@ -384,8 +401,8 @@ if ($create_user) {
$values['strict_acl'] = (bool) get_parameter('strict_acl', false);
$values['session_time'] = (int) get_parameter('session_time', 0);
// eHorus user level conf
if ($config['ehorus_user_level_conf']) {
// eHorus user level conf.
if ((bool) $config['ehorus_user_level_conf'] === true) {
$values['ehorus_user_level_enabled'] = (bool) get_parameter('ehorus_user_level_enabled', false);
if ($values['ehorus_user_level_enabled'] === true) {
$values['ehorus_user_level_user'] = (string) get_parameter('ehorus_user_level_user');
@ -397,7 +414,7 @@ if ($create_user) {
}
if ($id == '') {
if (empty($id) === true) {
ui_print_error_message(__('User ID cannot be empty'));
$is_err = true;
$user_info = $values;
@ -411,7 +428,7 @@ if ($create_user) {
$password_new = '';
$password_confirm = '';
$new_user = true;
} else if ($password_new == '') {
} else if (empty($password_new) === true) {
$is_err = true;
ui_print_error_message(__('Passwords cannot be empty'));
$user_info = $values;
@ -438,6 +455,9 @@ if ($create_user) {
}
$info = '{"Id_user":"'.$values['id_user'].'","FullName":"'.$values['fullname'].'","Firstname":"'.$values['firstname'].'","Lastname":"'.$values['lastname'].'","Email":"'.$values['email'].'","Phone":"'.$values['phone'].'","Comments":"'.$values['comments'].'","Is_admin":"'.$values['is_admin'].'","Language":"'.$values['language'].'","Timezone":"'.$values['timezone'].'","Block size":"'.$values['block_size'].'"';
if ($values['allowed_ip_active'] === true) {
$info .= ',"IPS Allowed":"'.$values['allowed_ip_list'].'"';
}
if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) {
$info .= ',"Skin":"'.$values['id_skin'].'"}';
@ -540,6 +560,8 @@ if ($update_user) {
$values['email'] = (string) get_parameter('email');
$values['phone'] = (string) get_parameter('phone');
$values['comments'] = io_safe_input(strip_tags(io_safe_output((string) get_parameter('comments'))));
$values['allowed_ip_active'] = ((int) get_parameter('allowed_ip_active', -1) === 0);
$values['allowed_ip_list'] = io_safe_input(strip_tags(io_safe_output((string) get_parameter('allowed_ip_list'))));
$values['is_admin'] = (get_parameter('is_admin', 0) === 0) ? 0 : 1;
$values['language'] = (string) get_parameter('language');
$values['timezone'] = (string) get_parameter('timezone');
@ -573,17 +595,17 @@ if ($update_user) {
$values['block_size'] = get_parameter('block_size', $config['block_size']);
$values['section'] = get_parameter('section');
if (($values['section'] == 'Event list') || ($values['section'] == 'Group view') || ($values['section'] == 'Alert detail') || ($values['section'] == 'Tactical view') || ($values['section'] == 'Default')) {
if (($values['section'] === 'Event list') || ($values['section'] === 'Group view') || ($values['section'] === 'Alert detail') || ($values['section'] === 'Tactical view') || ($values['section'] === 'Default')) {
$values['data_section'] = '';
} else if ($values['section'] == 'Dashboard') {
} else if ($values['section'] === 'Dashboard') {
$values['data_section'] = $dashboard;
} else if (io_safe_output($values['section']) == 'Visual console') {
} else if (io_safe_output($values['section']) === 'Visual console') {
$values['data_section'] = $visual_console;
} else if ($values['section'] == 'Other' || io_safe_output($values['section']) == 'External link') {
} else if ($values['section'] === 'Other' || io_safe_output($values['section']) === 'External link') {
$values['data_section'] = get_parameter('data_section');
}
if (enterprise_installed() && defined('METACONSOLE')) {
if (enterprise_installed() === true && is_metaconsole() === true) {
$values['metaconsole_access'] = get_parameter('metaconsole_access');
$values['metaconsole_agents_manager'] = get_parameter('metaconsole_agents_manager', '0');
$values['metaconsole_access_node'] = get_parameter('metaconsole_access_node', '0');
@ -611,9 +633,9 @@ if ($update_user) {
$correct_password = true;
}
if ($password_confirm == $password_new) {
if ((string) $password_confirm === (string) $password_new) {
if ($correct_password === true || is_user_admin($config['id_user'])) {
if ((!is_user_admin($config['id_user']) || $config['enable_pass_policy_admin']) && $config['enable_pass_policy']) {
if ((is_user_admin($config['id_user']) === false || $config['enable_pass_policy_admin']) && $config['enable_pass_policy']) {
$pass_ok = login_validate_pass($password_new, $id, true);
if ($pass_ok != 1) {
ui_print_error_message($pass_ok);
@ -704,19 +726,23 @@ if ($update_user) {
"Block size":"'.$values['block_size'].'",
"Section":"'.$values['section'].'"';
if ($values['allowed_ip_active'] === true) {
$info .= ',"IPS Allowed":"'.$values['allowed_ip_list'].'"';
}
if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) {
$info .= ',"Skin":"'.$values['id_skin'].'"';
$has_skin = true;
}
if (enterprise_installed() && defined('METACONSOLE')) {
if (enterprise_installed() === true && is_metaconsole() === true) {
$info .= ',"Wizard access":"'.$values['metaconsole_access'].'"}';
$has_wizard = true;
} else if ($has_skin) {
} else if ($has_skin === true) {
$info .= '}';
}
if (!$has_skin && !$has_wizard) {
if ($has_skin === false && $has_wizard === false) {
$info .= '}';
}
@ -744,7 +770,7 @@ if ($update_user) {
}
if ($values['strict_acl']) {
if ((bool) $values['strict_acl'] === true) {
$count_groups = 0;
$count_tags = 0;
@ -754,7 +780,7 @@ if ($update_user) {
}
foreach ($profiles as $profile) {
$count_groups = ($count_groups + 1);
$count_groups++;
$arr_tags = explode(',', $profile['tags']);
$count_tags = ($count_tags + count($arr_tags));
}
@ -783,7 +809,7 @@ if ($add_profile && empty($json_profile)) {
$no_hierarchy = (int) get_parameter('no_hierarchy', 0);
foreach ($tags as $k => $tag) {
if (empty($tag)) {
if (empty($tag) === true) {
unset($tags[$k]);
}
}
@ -826,7 +852,7 @@ if (!users_is_admin() && $config['id_user'] != $id && !$new_user) {
);
$result = db_get_all_rows_sql($sql);
if ($result == false && $user_info['is_admin'] == false) {
if ((bool) $result === false && (bool) $user_info['is_admin'] === false) {
db_pandora_audit(
AUDIT_LOG_ACL_VIOLATION,
'Trying to access User Management'
@ -837,12 +863,13 @@ if (!users_is_admin() && $config['id_user'] != $id && !$new_user) {
}
}
if (defined('METACONSOLE')) {
if ($id) {
echo '<div class="user_form_title">'.__('Update User').'</div>';
} else {
echo '<div class="user_form_title">'.__('Create User').'</div>';
}
if (is_metaconsole() === true) {
html_print_div(
[
'class' => 'user_form_title',
'content' => ((bool) $id === true) ? __('Update User') : __('Create User'),
]
);
}
if (!$new_user) {
@ -1030,6 +1057,26 @@ $comments .= html_print_textarea(
true
);
$allowedIP = '<p class="edit_user_labels">';
$allowedIP .= __('Login allowed IP list').'&nbsp;';
$allowedIP .= ui_print_help_tip(__('Add the source IPs that will allow console access. Each IP must be separated only by comma. * allows all.'), true).'&nbsp;';
$allowedIP .= html_print_checkbox_switch(
'allowed_ip_active',
0,
$user_info['allowed_ip_active'],
true
);
$allowedIP .= '</p>';
$allowedIP .= html_print_textarea(
'allowed_ip_list',
2,
65,
$user_info['allowed_ip_list'],
(((bool) $view_mode === true) ? 'readonly="readonly"' : ''),
true
);
// If we want to create a new user, skins displayed are the skins of the creator's group. If we want to update, skins displayed are the skins of the modified user.
$own_info = get_user_info($config['id_user']);
if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) {
@ -1046,8 +1093,8 @@ if ($new_user) {
$id_usr = $id;
}
if (!$meta) {
// User only can change skins if has more than one group
if ((bool) $meta === false) {
// User only can change skins if has more than one group.
if (count($usr_groups) > 1) {
if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) {
$skin = '<div class="label_select"><p class="edit_user_labels">'.__('Skin').'</p>';
@ -1056,7 +1103,7 @@ if (!$meta) {
}
}
if ($meta) {
if ((bool) $meta === true) {
$array_filters = get_filters_custom_fields_view(0, true);
$search_custom_fields_view = '<div class="label_select"><p class="edit_user_labels">'.__('Search custom field view').' '.ui_print_help_tip(__('Load by default the selected view in custom field view'), true).'</p>';
@ -1413,6 +1460,20 @@ echo '</div>
<div class="user_edit_third_row white_box">
<div class="edit_user_comments">'.$comments.'</div>
</div>';
html_print_div(
[
'class' => 'user_edit_third_row white_box',
'content' => html_print_div(
[
'class' => 'edit_user_allowed_ip',
'content' => $allowedIP,
],
true
),
]
);
if (!empty($ehorus)) {
echo '<div class="user_edit_third_row white_box">'.$ehorus.'</div>';
}

View File

@ -941,6 +941,7 @@ class HostDevices extends Wizard
'return' => true,
'class' => 'discovery_list_input',
'simple_multiple_options' => true,
'required' => true,
]
);
@ -1001,6 +1002,7 @@ class HostDevices extends Wizard
$("#text-interval_text").val(10);
$("#hidden-interval").val('.$interval.');
$("#interval_units").val('.$unit.');
$("#interval_units").trigger("change");
}
}).change();

View File

@ -647,7 +647,12 @@ if ($get_agent_alerts_datatable === true) {
$order = get_datatable_order(true);
$url = get_parameter('url', '#');
$free_search_alert = $filter_alert['free_search_alert'];
if (empty($filter_alert['free_search']) === false) {
$free_search_alert = $filter_alert['free_search'];
} else {
$free_search_alert = $filter_alert['free_search_alert'];
}
$idGroup = $filter_alert['ag_group'];
$tag_filter = $filter_alert['tag_filter'];
$action_filter = $filter_alert['action'];
@ -676,7 +681,7 @@ if ($get_agent_alerts_datatable === true) {
$selectLastFiredDown = false;
switch ($sortField) {
case 'module':
case 'agent_module_name':
switch ($sort) {
case 'asc':
$selectModuleasc = $selected;
@ -696,7 +701,7 @@ if ($get_agent_alerts_datatable === true) {
}
break;
case 'template':
case 'template_name':
switch ($sort) {
case 'asc':
$selectTemplateasc = $selected;
@ -736,7 +741,7 @@ if ($get_agent_alerts_datatable === true) {
}
break;
case 'agent':
case 'agent_name':
switch ($sort) {
case 'asc':
$selectLastFiredasc = $selected;
@ -857,7 +862,7 @@ if ($get_agent_alerts_datatable === true) {
if (is_metaconsole() === true) {
include_once $config['homedir'].'/enterprise/meta/include/functions_alerts_meta.php';
if ($idAgent != 0) {
$alerts['alerts_simple'] = alerts_meta_get_alerts($agents, $filter_alert, $options_simple, $whereAlertSimple, false, false, $idGroup, false, $strict_user, $tag_filter, $action_filter);
$alerts['alerts_simple'] = alerts_meta_get_alerts($agents, $filter_alert, false, $whereAlertSimple, false, false, $idGroup, false, $strict_user, $tag_filter, $action_filter);
$countAlertsSimple = alerts_meta_get_alerts($agents, $filter_alert, false, $whereAlertSimple, false, false, $idGroup, true, $strict_user, $tag_filter, $action_filter);
} else {
@ -865,7 +870,7 @@ if ($get_agent_alerts_datatable === true) {
users_get_groups($config['id_user'], 'AR', false)
);
$alerts['alerts_simple'] = alerts_meta_get_group_alerts($id_groups, $filter_alert, $options_simple, $whereAlertSimple, false, false, $idGroup, false, $strict_user, $tag_filter, $action_filter);
$alerts['alerts_simple'] = alerts_meta_get_group_alerts($id_groups, $filter_alert, false, $whereAlertSimple, false, false, $idGroup, false, $strict_user, $tag_filter, $action_filter);
$countAlertsSimple = alerts_meta_get_group_alerts($id_groups, $filter_alert, false, $whereAlertSimple, false, false, $idGroup, true, $strict_user, $tag_filter, $action_filter);
}
@ -885,12 +890,32 @@ if ($get_agent_alerts_datatable === true) {
}
}
// Order and pagination metacosole.
if (is_metaconsole() === true) {
// Status order.
if ($sortField === 'status') {
foreach ($alerts['alerts_simple'] as $i => $alert) {
if ($alert['times_fired'] > 0) {
$alerts['alerts_simple'][$i]['status'] = '3';
} else if ($alert['disabled'] > 0) {
$alerts['alerts_simple'][$i]['status'] = '1';
} else {
$alerts['alerts_simple'][$i]['status'] = '2';
}
}
}
usort($alerts['alerts_simple'], arrayOutputSorting($sort, $sortField));
$alerts['alerts_simple'] = array_slice($alerts['alerts_simple'], $start, $length);
}
$data = [];
if ($alerts['alerts_simple']) {
foreach ($alerts['alerts_simple'] as $alert) {
$data[] = ui_format_alert_row($alert, true, $url, 'font-size: 7pt;');
}
$data = array_reduce(
$data,
function ($carry, $row) {
@ -902,11 +927,11 @@ if ($get_agent_alerts_datatable === true) {
$tmp->policy = $row[0];
$tmp->standby = $row[1];
$tmp->force = $row[2];
$tmp->agent = $row[3];
$tmp->module = $row[4];
$tmp->template = $row[5];
$tmp->agent_name = $row[3];
$tmp->agent_module_name = $row[4];
$tmp->template_name = $row[5];
$tmp->action = $row[6];
$tmp->lastFired = $row[7];
$tmp->last_fired = $row[7];
$tmp->status = $row[8];
$tmp->validate = $row[9];
@ -916,6 +941,7 @@ if ($get_agent_alerts_datatable === true) {
);
}
// Datatables format: RecordsTotal && recordsfiltered.
echo json_encode(
[

View File

@ -372,8 +372,8 @@ if ($save_event_filter) {
$values['custom_data'] = get_parameter('custom_data');
$values['custom_data_filter_type'] = get_parameter('custom_data_filter_type');
if (is_metaconsole()) {
$values['server_id'] = get_parameter('server_id');
if (is_metaconsole() === true) {
$values['server_id'] = implode(',', get_parameter('server_id'));
}
$exists = (bool) db_get_value_filter(
@ -430,7 +430,7 @@ if ($update_event_filter) {
$values['custom_data_filter_type'] = get_parameter('custom_data_filter_type');
if (is_metaconsole() === true) {
$values['server_id'] = get_parameter('server_id');
$values['server_id'] = implode(',', get_parameter('server_id'));
}
if (io_safe_output($values['tag_with']) == '["0"]') {

View File

@ -1916,12 +1916,21 @@ class AgentWizard extends HTML
$values['configuration_data'] = io_safe_input($cfData);
} else {
$values['id_module'] = MODULE_PLUGIN;
$fieldsPlugin = db_get_value_sql(
sprintf(
'SELECT macros FROM tplugin WHERE id=%d',
(int) $infoMacros['server_plugin']
)
);
if ((int) $infoMacros['server_plugin'] === 12) {
// Search plugin by execute.
$plugin_wmi = db_get_row_sql(
'SELECT id, macros FROM tplugin WHERE execute like "%wizard_wmi_module%"'
);
$fieldsPlugin = $plugin_wmi['macros'];
$infoMacros['server_plugin'] = $plugin_wmi['id'];
} else {
$fieldsPlugin = db_get_value_sql(
sprintf(
'SELECT macros FROM tplugin WHERE id=%d',
(int) $infoMacros['server_plugin']
)
);
}
if ($fieldsPlugin !== false) {
$fieldsPlugin = json_decode($fieldsPlugin, true);
@ -2360,12 +2369,21 @@ class AgentWizard extends HTML
);
} else {
$tmp->id_modulo(MODULE_PLUGIN);
$fieldsPlugin = db_get_value_sql(
sprintf(
'SELECT macros FROM tplugin WHERE id=%d',
(int) $infoMacros['server_plugin']
)
);
if ((int) $infoMacros['server_plugin'] === 12) {
// Search plugin by execute.
$plugin_wmi = db_get_row_sql(
'SELECT id, macros FROM tplugin WHERE execute like "%wizard_wmi_module%"'
);
$fieldsPlugin = $plugin_wmi['macros'];
$infoMacros['server_plugin'] = $plugin_wmi['id'];
} else {
$fieldsPlugin = db_get_value_sql(
sprintf(
'SELECT macros FROM tplugin WHERE id=%d',
(int) $infoMacros['server_plugin']
)
);
}
if ($fieldsPlugin !== false) {
$fieldsPlugin = json_decode($fieldsPlugin, true);

View File

@ -44,7 +44,7 @@ class AuditLog extends HTML
*
* @var array
*/
public $AJAXMethods = [ 'draw' ];
public $AJAXMethods = ['draw'];
/**
* Ajax page.
@ -78,7 +78,6 @@ class AuditLog extends HTML
// Set the ajax controller.
$this->ajaxController = $ajaxController;
}
@ -232,7 +231,6 @@ class AuditLog extends HTML
// Load own javascript file.
echo $this->loadJS();
}
@ -368,39 +366,38 @@ class AuditLog extends HTML
// Javascript content.
?>
<script type="text/javascript">
function format ( d ) {
var output = '';
<script type="text/javascript">
function format(d) {
var output = '';
if (d.extendedInfo === '') {
output = "<?php echo __('There is no additional information to display'); ?>";
} else {
output = d.extendedInfo;
}
return output;
if (d.extendedInfo === '') {
output = "<?php echo __('There is no additional information to display'); ?>";
} else {
output = d.extendedInfo;
}
$(document).ready(function() {
// Add event listener for opening and closing details
$('#audit_logs tbody').on('click', 'td.show_extended_info', function () {
var tr = $(this).closest('tr');
var table = <?php echo 'dt_'.$this->tableId; ?>;
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
</script>
return output;
}
$(document).ready(function() {
// Add event listener for opening and closing details
$('#audit_logs tbody').on('click', 'td.show_extended_info', function() {
var tr = $(this).closest('tr');
var table = $("#<?php echo $this->tableId; ?>").DataTable();
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
});
</script>
<?php
// EOF Javascript content.
return ob_get_clean();

View File

@ -1466,7 +1466,7 @@ class ConsoleSupervisor
[
'type' => 'NOTIF.PHP.INPUT_TIME',
'title' => sprintf(
__("'%s' value in PHP configuration is not recommended"),
__('%s value in PHP configuration is not recommended'),
'max_input_time'
),
'message' => sprintf(

View File

@ -594,6 +594,7 @@ class CustomNetScan extends Wizard
$("#text-interval_text").val(10);
$("#hidden-interval").val('.$interval.');
$("#interval_units").val('.$unit.');
$("#interval_units").trigger("change");
}
}).change();
';

View File

@ -651,6 +651,12 @@ class ExternalTools extends HTML
}
break;
case 'whois':
if (empty($snmpget_path) === false) {
return $snmpget_path;
}
break;
default:
return null;
}
@ -829,6 +835,7 @@ class ExternalTools extends HTML
if (empty($dig) === true) {
ui_print_error_message(__('Dig executable does not exist.'));
} else {
$dig .= ' '.$ip;
$this->performExecution($dig);
}
@ -837,6 +844,7 @@ class ExternalTools extends HTML
if (empty($whois) === true) {
ui_print_error_message(__('Whois executable does not exist.'));
} else {
$whois .= ' '.$ip;
$this->performExecution($whois);
}

View File

@ -2102,39 +2102,91 @@ class NetworkMap
$i++;
}
if (!$this->relations) {
// Search for relations.
foreach ($this->nodes as $k => $item) {
$target = $this->calculateRelations($k);
// Search for relations.
foreach ($this->nodes as $k => $item) {
$target = $this->calculateRelations($k);
// Adopt all orphan nodes but pandora one.
if (empty($target)) {
if (isset($this->noPandoraNode) === false
|| $this->noPandoraNode == false
) {
if ($item['id_node'] != 0) {
$rel = [];
$rel['id_parent'] = 0;
$rel['id_child'] = $item['id_node'];
$rel['parent_type'] = NODE_PANDORA;
$rel['child_type'] = $item['node_type'];
$rel['id_child_source_data'] = $item['id_source_data'];
// Adopt all orphan nodes but pandora one.
if (empty($target) === true) {
if (isset($this->noPandoraNode) === false
|| $this->noPandoraNode == false
) {
if ($item['id_node'] != 0) {
$rel = [];
$rel['id_parent'] = 0;
$rel['id_child'] = $item['id_node'];
$rel['parent_type'] = NODE_PANDORA;
$rel['child_type'] = $item['node_type'];
$rel['id_child_source_data'] = $item['id_source_data'];
$orphans[] = $rel;
}
}
} else {
// Flattern edges.
foreach ($target as $rel) {
$edges[] = $rel;
$orphans[] = $rel;
}
}
} else {
// Flattern edges.
foreach ($target as $rel) {
$edges[] = $rel;
}
}
} else {
$edges = $this->relations;
}
if (is_array($edges)) {
$array_aux = $edges;
$target_aux = $edges;
foreach ($edges as $key => $rel) {
foreach ($array_aux as $key2 => $rel2) {
if ($key2 <= $key) {
continue;
}
if ($rel['child_type'] == 1 && $rel['parent_type'] == 1
&& $rel2['child_type'] == 1 && $rel2['parent_type'] == 1
) {
if ($rel['id_parent'] == $rel2['id_parent'] && $rel['id_child'] == $rel2['id_child']) {
if ($rel['id_parent_source_data'] == $rel2['id_parent_source_data']) {
if (modules_get_agentmodule_type($rel['id_child_source_data']) === 6) {
unset($target_aux[$key]);
} else if (modules_get_agentmodule_type($rel2['id_child_source_data']) === 6) {
unset($target_aux[$key2]);
}
} else if ($rel['id_child_source_data'] == $rel2['id_child_source_data']) {
if (modules_get_agentmodule_type($rel['id_parent_source_data']) === 6) {
unset($target_aux[$key]);
} else if (modules_get_agentmodule_type($rel2['id_parent_source_data']) === 6) {
unset($target_aux[$key2]);
}
}
} else if ($rel['id_parent'] == $rel2['id_child'] && $rel['id_child'] == $rel2['id_parent']) {
if ($rel['id_parent_source_data'] == $rel2['id_child_source_data']
&& $rel['id_child_source_data'] == $rel2['id_parent_source_data']
) {
unset($target_aux[$key2]);
continue;
}
if ($rel['id_parent_source_data'] == $rel2['id_child_source_data']) {
if (modules_get_agentmodule_type($rel['id_child_source_data']) === 6) {
unset($target_aux[$key]);
} else if (modules_get_agentmodule_type($rel2['id_parent_source_data']) === 6) {
unset($target_aux[$key2]);
}
} else if ($rel['id_child_source_data'] == $rel2['id_parent_source_data']) {
if (modules_get_agentmodule_type($rel['id_parent_source_data']) === 6) {
unset($target_aux[$key]);
} else if (modules_get_agentmodule_type($rel2['id_child_source_data']) === 6) {
unset($target_aux[$key2]);
}
}
}
}
}
}
$edges = [];
foreach ($target_aux as $key => $value) {
$edges[] = $value;
}
foreach ($edges as $rel) {
$graph .= $this->createDotEdge(
[
@ -2628,6 +2680,79 @@ class NetworkMap
}
/**
* Regenerates a nodes - relationships array using graphviz dot
* schema and stores nodes&relations into $this->graph.
*
* @return object
*/
public function recalculateCoords()
{
global $config;
include_once 'include/functions_os.php';
$map_filter = $this->mapOptions['map_filter'];
/*
* Let graphviz place the nodes.
*/
if ($map_filter['empty_map']) {
$this->generateEmptyDotGraph();
} else if (!isset($this->dotGraph)) {
$this->generateDotGraph();
}
$graph = $this->calculateCoords();
if (is_array($graph) === true) {
$nodes = $graph['nodes'];
} else {
return [];
}
$nodes_aux = [];
// Prepare graph nodes.
foreach ($nodes as $id => $coords) {
$node_tmp['id'] = $id;
$source = $this->getNodeData($id);
$node_tmp['type'] = $source['node_type'];
$node_tmp['x'] = $coords['x'];
$node_tmp['y'] = $coords['y'];
switch ($node_tmp['type']) {
case NODE_AGENT:
$node_tmp['source_data'] = $source['id_agente'];
break;
case NODE_MODULE:
$node_tmp['source_data'] = $source['id_agente_modulo'];
break;
case NODE_PANDORA:
$node_tmp['source_data'] = 0;
$node_center['x'] = ($coords['x'] - MAP_X_CORRECTION);
$node_center['y'] = ($coords['y'] - MAP_Y_CORRECTION);
break;
case NODE_GENERIC:
default:
$node_tmp['source_data'] = $source['id_source'];
break;
}
$nodes_aux[$index] = $node_tmp;
$index++;
}
return $nodes_aux;
}
/**
* Transform node information into JS data.
*
@ -2799,7 +2924,6 @@ class NetworkMap
$output .= "var add_node_menu = '".__('Add node')."';\n";
$output .= "var set_center_menu = '".__('Set center')."';\n";
$output .= "var refresh_menu = '".__('Refresh')."';\n";
$output .= "var refresh_holding_area_menu = '".__('Refresh Holding area')."';\n";
$output .= "var ok_button = '".__('Proceed')."';\n";
$output .= "var message_to_confirm = '".__('Resetting the map will delete all customizations you have done, including manual relationships between elements, new items, etc.')."';\n";
$output .= "var warning_message = '".__('WARNING')."';\n";
@ -3066,8 +3190,8 @@ class NetworkMap
$table->data['template_row']['node_target'] = '';
$table->data['template_row']['edit'] = '';
$table->data['template_row']['edit'] .= '<span class="edit_icon_correct" style="display: none">'.html_print_image('images/dot_green.png', true).'</span><span class="edit_icon_fail" style="display: none" >'.html_print_image('images/dot_red.png', true).'</span><span class="edit_icon_progress" style="display: none">'.html_print_image('images/spinner.gif', true).'</span><span class="edit_icon"><a class="edit_icon_link" title="'.__('Update').'" href="#">'.html_print_image('images/config.png', true, ['class' => 'invert_filter']).'</a></span>';
$table->data['template_row']['edit'] .= '<span class="edit_icon_correct" style="display: none">'.html_print_image('images/dot_green.png', true).'</span><span class="edit_icon_fail" style="display: none" >'.html_print_image('images/dot_red.png', true).'</span><span class="edit_icon_progress" style="display: none">'.html_print_image('images/spinner.gif', true).'</span>';
// <span class="edit_icon"><a class="edit_icon_link" title="'.__('Update').'" href="#">'.html_print_image('images/config.png', true, ['class' => 'invert_filter']).'</a></span>';
$table->data['template_row']['edit'] .= '<a class="delete_icon" href="#">'.html_print_image('images/delete.png', true, ['class' => 'invert_filter']).'</a>';
$table->colspan['no_relations']['0'] = 5;
@ -3278,7 +3402,7 @@ class NetworkMap
$table->data[1][1] = html_print_select(
$list_networkmaps,
'networkmap_to_link',
'',
0,
'',
'',
0,
@ -3318,6 +3442,10 @@ class NetworkMap
*/
public function loadController(?bool $return=true)
{
if (isset($this->mapOptions['refresh_time']) === false) {
$this->mapOptions['refresh_time'] = 0;
}
$output = '';
if ($this->useTooltipster
@ -3359,13 +3487,34 @@ class NetworkMap
node_radius: node_radius,
holding_area_dimensions: networkmap_holding_area_dimensions,
url_background_grid: url_background_grid,
refresh_time: '.$this->mapOptions['refresh_time'].',
font_size: '.$this->mapOptions['font_size'].',
base_url_homedir: "'.ui_get_full_url(false).'"
});
init_drag_and_drop();
init_minimap();
function_open_minimap();
if ('.$this->mapOptions['refresh_time'].' > 0) {
var startCountDown = function (duration, cb) {
$("div.vc-countdown").countdown("destroy");
if (!duration) return;
var t = new Date();
t.setTime(t.getTime() + duration * 1000);
$("div.vc-countdown").countdown({
until: t,
format: "MS",
layout: "(%M%nn%M:%S%nn%S '.__('Until refresh').') ",
alwaysExpire: true,
onExpiry: function () {
refresh();
}
});
}
startCountDown('.($this->mapOptions['refresh_time']).', false);
}
$(document.body).on("mouseleave",
".context-menu-list",
function(e) {
@ -3504,6 +3653,10 @@ class NetworkMap
$output .= ' style="width: '.$this->mapOptions['width'].'px; height: '.$this->mapOptions['height'].'px;position: relative; overflow: hidden; background: #FAFAFA">';
}
$output .= '<div id="spinner_networkmap" style="position: absolute; width: 100%;height: 100%; z-index:1; justify-content: center; align-items: center; display:none; background-color:rgba(0, 0, 0, 0.2);">';
$output .= html_print_image('/images/spinner.gif', true, ['style' => 'width: 22px; height: 22px']);
$output .= '</div>';
$output .= '<div style="display: '.$minimap_display.';">';
$output .= '<canvas id="minimap_'.$networkmap['id'].'"';
$output .= ' class="minimap">';

View File

@ -56,6 +56,7 @@ class SatelliteAgent extends HTML
'draw',
'addAgent',
'deleteAgent',
'disableAgent',
'loadModal',
];
@ -97,7 +98,6 @@ class SatelliteAgent extends HTML
$this->satellite_name = servers_get_name($this->satellite_server);
$this->satellite_config = (array) config_satellite_get_config_file($this->satellite_name);
}
}
@ -108,27 +108,53 @@ class SatelliteAgent extends HTML
*/
public function run()
{
global $config;
// Javascript.
ui_require_jquery_file('pandora');
// CSS.
ui_require_css_file('wizard');
ui_require_css_file('discovery');
global $config;
$this->createBlock();
// Datatables list.
try {
$checkbox_all = html_print_checkbox(
'all_validate_box',
1,
false,
true
);
$columns = [
[
'text' => 'm',
'extra' => $checkbox_all,
'class' => 'mw60px',
],
'name',
'address',
'actions',
];
$column_names = [
[
'text' => 'm',
'extra' => $checkbox_all,
'class' => 'w20px no-text-imp',
],
__('Agent Name'),
__('IP Adrress'),
__('Actions'),
];
$show_agents = [
0 => __('Everyone'),
1 => __('Only disabled'),
2 => __('Only deleted'),
3 => __('Only added'),
];
$this->tableId = 'satellite_agents';
if (is_metaconsole() === true) {
@ -154,6 +180,7 @@ class SatelliteAgent extends HTML
0,
1,
2,
3,
],
'search_button_class' => 'sub filter float-right',
'form' => [
@ -167,7 +194,15 @@ class SatelliteAgent extends HTML
'name' => 'filter_search',
'size' => 12,
],
[
'label' => __('Show agents'),
'type' => 'select',
'id' => 'filter_agents',
'name' => 'filter_agents',
'fields' => $show_agents,
'return' => true,
'selected' => 0,
],
],
],
]
@ -186,7 +221,34 @@ class SatelliteAgent extends HTML
$msg = '<div id="msg" class="invisible"></div>';
$aux = '<div id="aux" class="invisible"></div>';
echo $modal.$msg.$aux;
echo $modal.$msg.$aux;
echo '<div id="satellite_actions" class="action-buttons" style="width: 100%">';
html_print_select(
[
'0' => 'Disable / Enable selected agents',
'1' => 'Delete / Create selected agents',
],
'satellite_action',
'',
'',
'',
0,
false,
false,
false
);
html_print_submit_button(
__('Execute action'),
'submit_satellite_action',
false,
'class="sub next"'
);
echo '</div>';
echo '</br></br>';
// Create button.
echo '<div class="w100p flex-content-right">';
@ -200,7 +262,6 @@ class SatelliteAgent extends HTML
echo '</div>';
// Load own javascript file.
echo $this->loadJS();
}
@ -212,8 +273,7 @@ class SatelliteAgent extends HTML
public function draw()
{
global $config;
// Initialice filter.
$filter = '1=1';
// Init data.
$data = [];
// Count of total records.
@ -228,8 +288,24 @@ class SatelliteAgent extends HTML
ob_start();
$data = [];
$agents_db = db_get_all_rows_sql(
sprintf(
'SELECT id_agente, alias AS name, direccion AS address,
IF(disabled = 0, INSERT("add_host", 0 , 0, ""),
IF(modo = 1, INSERT("ignore_host", 0 , 0, ""), INSERT("delete_host", 0, 0, ""))) AS type
FROM tagente WHERE `satellite_server` = %d',
$this->satellite_server
)
);
if (empty($agents_db) === false) {
$data = $agents_db;
}
foreach ($this->satellite_config as $line) {
$re = '/^#*add_host \b(\S+) (\S*)$/m';
$re = '/^#*add_host \b(\S+) (\S*)/m';
$re_disable = '/^ignore_host \b(\S+)/m';
$re_delete = '/^delete_host \b(\S+)/m';
if (preg_match($re, $line, $matches, PREG_OFFSET_CAPTURE, 0) > 0) {
$agent['address'] = $matches[1][0];
@ -239,17 +315,64 @@ class SatelliteAgent extends HTML
$agent['name'] = $matches[2][0];
}
if (empty($filters['filter_search']) === false) {
if (empty(preg_grep('/'.$filters['filter_search'].'?/mi', array_values($agent))) === true) {
continue;
}
}
$agent['type'] = 'add_host';
array_push($data, $agent);
}
if (preg_match($re_disable, $line, $matches, PREG_OFFSET_CAPTURE, 0) > 0) {
$agent['name'] = $matches[1][0];
$agent['type'] = 'ignore_host';
array_push($data, $agent);
}
if (preg_match($re_delete, $line, $matches, PREG_OFFSET_CAPTURE, 0) > 0) {
$agent['name'] = $matches[1][0];
$agent['type'] = 'delete_host';
array_push($data, $agent);
}
}
if (empty($data) === false) {
$data = $this->uniqueMultidimArray($data, ['name', 'address']);
if (empty($filters['filter_agents']) === false || empty($filters['filter_search']) === false) {
foreach ($data as $key => $value) {
switch ($filters['filter_agents']) {
case 1:
if ($value['type'] !== 'ignore_host') {
unset($data[$key]);
}
break;
case 2:
if ($value['type'] !== 'delete_host') {
unset($data[$key]);
}
break;
case 3:
if ($value['type'] !== 'add_host') {
unset($data[$key]);
}
break;
default:
// Everyone.
break;
}
if (empty($filters['filter_search']) === false) {
if (empty(preg_grep('/'.$filters['filter_search'].'?/mi', array_values($value))) === true) {
unset($data[$key]);
}
}
}
}
$data = array_reduce(
$data,
function ($carry, $item) {
@ -258,14 +381,50 @@ class SatelliteAgent extends HTML
// of objects, making a post-process of certain fields.
$tmp = (object) $item;
$tmp->actions .= html_print_image(
'images/cross.png',
true,
[
'border' => '0',
'class' => 'action_button_img invert_filter',
'onclick' => 'delete_agent(\''.$tmp->address.'\',\''.$tmp->name.'\')',
]
$disable = ($tmp->type === 'ignore_host');
$delete = ($tmp->type === 'delete_host');
if ($disable === true) {
$tmp->name = '<i class="italic_a">'.$tmp->name.'</i>';
}
if ($delete === true) {
$tmp->name = '<del>'.$tmp->name.'</del>';
}
$id_agente = (isset($tmp->id_agente) === true) ? $tmp->id_agente : 0;
$tmp->actions = '';
if ($delete === false) {
$tmp->actions .= html_print_image(
($disable === true) ? 'images/lightbulb_off.png' : 'images/lightbulb.png',
true,
[
'border' => '0',
'class' => 'action_button_img mrgn_lft_05em invert_filter',
'onclick' => 'disable_agent(\''.$tmp->address.'\',\''.strip_tags($tmp->name).'\',\''.(int) $disable.'\',\''.$id_agente.'\')',
]
);
}
if ($disable === false) {
$tmp->actions .= html_print_image(
($delete === true) ? 'images/add.png' : 'images/cross.png',
true,
[
'border' => '0',
'class' => 'action_button_img mrgn_lft_05em invert_filter',
'onclick' => 'delete_agent(\''.$tmp->address.'\',\''.strip_tags($tmp->name).'\',\''.(int) $delete.'\',\''.$id_agente.'\')',
]
);
}
$tmp->m = html_print_checkbox(
'check_'.strip_tags($tmp->name),
$tmp->address.','.strip_tags($tmp->name).','.(int) $delete.','.(int) $disable.','.$id_agente,
false,
true
);
$carry[] = $tmp;
@ -274,8 +433,13 @@ class SatelliteAgent extends HTML
);
}
$data = array_slice($data, $start, $length, true);
$total = count($data);
if (empty($data) === true) {
$total = 0;
$data = [];
} else {
$total = count($data);
$data = array_slice($data, $start, $length, false);
}
echo json_encode(
[
@ -333,12 +497,6 @@ class SatelliteAgent extends HTML
$values = [];
}
$return_all_group = false;
if (users_can_manage_group_all('AR') === true) {
$return_all_group = true;
}
$form = [
'action' => '#',
'id' => 'modal_form',
@ -392,6 +550,16 @@ class SatelliteAgent extends HTML
$values['address'] = get_parameter('address');
$values['name'] = get_parameter('name');
if ($this->checkAddressExists($values['address']) === true) {
$this->ajaxMsg('error', __('Error saving agent. The address already exists'));
exit;
}
if ($this->checkNameExists($values['name']) === true) {
$this->ajaxMsg('error', __('Error saving agent. The Name already exists'));
exit;
}
if ($this->parseSatelliteConf('save', $values) === false) {
$this->ajaxMsg('error', __('Error saving agent'));
} else {
@ -412,11 +580,82 @@ class SatelliteAgent extends HTML
{
$values['address'] = get_parameter('address', '');
$values['name'] = get_parameter('name', '');
$values['delete'] = get_parameter('delete', '');
$values['id'] = get_parameter('id', 0);
$no_msg = (bool) get_parameter('no_msg', 0);
if ((bool) $values['id'] === true) {
db_process_sql_update(
'tagente',
[
'disabled' => ($values['delete'] === '0') ? 1 : 0,
'modo' => ($values['delete'] === '0') ? 2 : 1,
],
['id_agente' => (int) $values['id']]
);
}
if ($this->parseSatelliteConf('delete', $values) === false) {
$this->ajaxMsg('error', __('Error saving agent'));
if ($no_msg === false) {
$this->ajaxMsg('error', ($values['delete'] === '0') ? __('Error delete agent') : __('Error add agent'));
}
} else {
$this->ajaxMsg('result', _('Host '.$values['addres'].' added.'));
if ($no_msg === false) {
$this->ajaxMsg(
'result',
($values['delete'] === '0')
? _('Host '.$values['address'].' deleted.')
: _('Host '.$values['address'].' added.'),
true
);
}
}
exit;
}
/**
* Disable agent from satellite conf.
*
* @return void
*/
public function disableAgent()
{
$values['address'] = get_parameter('address', '');
$values['name'] = get_parameter('name', '');
$values['disable'] = get_parameter('disable', '');
$values['id'] = get_parameter('id', 0);
$no_msg = (bool) get_parameter('no_msg', 0);
if ((bool) $values['id'] === true) {
db_process_sql_update(
'tagente',
['disabled' => ($values['disable'] === '0') ? 1 : 0],
['id_agente' => (int) $values['id']]
);
}
if ($this->parseSatelliteConf('disable', $values) === false) {
if ($no_msg === false) {
$this->ajaxMsg(
'error',
($values['disable'] === '0') ? __('Error disable agent') : __('Error enable agent')
);
}
} else {
if ($no_msg === false) {
$this->ajaxMsg(
'result',
($values['disable'] === '0')
? _('Host '.$values['address'].' disabled.')
: _('Host '.$values['address'].' enabled.'),
false,
true
);
}
}
exit;
@ -426,38 +665,173 @@ class SatelliteAgent extends HTML
/**
* Parse satellite configuration .
*
* @param string $action Action to perform (save, delete).
* @param array $values.
* @return void
* @param string $action Action to perform (save, delete).
* @param array $values Values.
*
* @return boolean
*/
private function parseSatelliteConf(string $action, array $values)
{
switch ($action) {
case 'save':
if (isset($values['address']) === true && empty($values['address']) === false) {
$string_hosts = 'add_host '.$values['address'].' '.$values['name']."\n";
$pos = preg_grep('/^\#INIT ignore_host/', $this->satellite_config);
if (empty($pos) === false) {
$string_hosts = 'add_host '.$values['address'].' '.$values['name']."\n";
// Add host to conf
array_push($this->satellite_config, $string_hosts);
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
// Check config.
if (empty($this->satellite_config)) {
return false;
$array1 = array_slice($this->satellite_config, 0, $key_pos);
$array2 = array_slice($this->satellite_config, $key_pos);
// Add host to conf.
$array_merge = array_merge($array1, [$string_hosts], $array2);
$this->satellite_config = $array_merge;
// Check config.
if (empty($this->satellite_config)) {
return false;
}
$conf = implode('', $this->satellite_config);
}
$conf = implode('', $this->satellite_config);
} else {
return false;
}
break;
case 'disable':
if ((bool) $values['disable'] === true) {
$pos = preg_grep('/^\#INIT ignore_host/', $this->satellite_config);
if (empty($pos) === false) {
$string_hosts = 'add_host '.$values['address'].' '.$values['name']."\n";
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
$array1 = array_slice($this->satellite_config, 0, $key_pos);
$array2 = array_slice($this->satellite_config, $key_pos);
// Add host to conf.
$array_merge = array_merge($array1, [$string_hosts], $array2);
$this->satellite_config = $array_merge;
// Remove ignore_host.
$pattern = io_safe_expreg('ignore_host '.$values['name']);
$pos = preg_grep('/'.$pattern.'/', $this->satellite_config);
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
if (empty($pos) === false) {
unset($this->satellite_config[$key_pos]);
}
$conf = implode('', $this->satellite_config);
}
} else {
$pos = preg_grep('/^\#INIT delete_host/', $this->satellite_config);
if (empty($pos) === false) {
$string_hosts = 'ignore_host '.$values['name']."\n";
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
$array1 = array_slice($this->satellite_config, 0, $key_pos);
$array2 = array_slice($this->satellite_config, $key_pos);
// Add host to conf.
$array_merge = array_merge($array1, [$string_hosts], $array2);
$this->satellite_config = $array_merge;
// Remove add_host.
$pattern = io_safe_expreg('add_host '.$values['address'].' '.$values['name']);
$pos = preg_grep('/'.$pattern.'/', $this->satellite_config);
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
if (empty($pos) === false) {
unset($this->satellite_config[$key_pos]);
}
$conf = implode('', $this->satellite_config);
}
}
break;
case 'delete':
$conf = implode('', $this->satellite_config);
// Find agent to mark for deletion.
$pattern = io_safe_expreg($values['address'].' '.$values['name']);
$re = "/add_host ($pattern)/m";
$subst = 'delete_host $1';
$conf = preg_replace($re, $subst, $conf);
if ((bool) $values['delete'] === true) {
$pos = preg_grep('/^\#INIT ignore_host/', $this->satellite_config);
if (empty($pos) === false) {
$string_hosts = 'add_host '.$values['address'].' '.$values['name']."\n";
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
$array1 = array_slice($this->satellite_config, 0, $key_pos);
$array2 = array_slice($this->satellite_config, $key_pos);
// Add host to conf.
$array_merge = array_merge($array1, [$string_hosts], $array2);
$this->satellite_config = $array_merge;
// Remove delete_host.
$pattern = io_safe_expreg('delete_host '.$values['name']);
$pos = preg_grep('/'.$pattern.'/', $this->satellite_config);
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
unset($this->satellite_config[$key_pos]);
$conf = implode('', $this->satellite_config);
}
} else {
// Find agent to mark for deletion.
$pattern = io_safe_expreg('add_host '.$values['address'].' '.$values['name']);
$pos = preg_grep('/'.$pattern.'/', $this->satellite_config);
if (empty($pos) === false) {
$key_pos = 0;
foreach ($pos as $key => $value) {
$key_pos = $key;
break;
}
unset($this->satellite_config[$key_pos]);
}
$string_hosts = 'delete_host '.$values['name']."\n";
$pos = preg_grep('/delete_host/', $this->satellite_config);
if (empty($pos) === false) {
$key_pos = array_keys($pos)[(count($pos) - 1)];
$array1 = array_slice($this->satellite_config, 0, ($key_pos + 1));
$array2 = array_slice($this->satellite_config, ($key_pos + 1));
$array_merge = array_merge($array1, [$string_hosts], $array2);
$this->satellite_config = $array_merge;
}
$conf = implode('', $this->satellite_config);
}
break;
default:
@ -469,11 +843,37 @@ class SatelliteAgent extends HTML
}
public function checkAddressExists($address)
{
$pos_address = preg_grep('/.*_host\s('.$address.')\s.*/', $this->satellite_config);
if (empty($pos_address) === false) {
return true;
}
return false;
}
public function checkNameExists($name)
{
$pos_name = preg_grep('/.*_host.*('.$name.')$/', $this->satellite_config);
if (empty($pos_name) === false) {
return true;
}
return false;
}
/**
* Saves agent to satellite cofiguration file.
*
* @param array $values
* @return void
* @param string $new_conf Config file.
*
* @return boolean|void
*/
private function saveAgent(string $new_conf)
{
@ -483,13 +883,13 @@ class SatelliteAgent extends HTML
return false;
}
db_pandora_audit(
AUDIT_LOG_SYSTEM,
'Update remote config for server '.$this->satellite_name
);
db_pandora_audit(
AUDIT_LOG_SYSTEM,
'Update remote config for server '.$this->satellite_name
);
// Convert to config file encoding.
$encoding = config_satellite_get_encoding($new_conf);
// Convert to config file encoding.
$encoding = config_satellite_get_encoding($new_conf);
if ($encoding !== false) {
$converted_server_config = mb_convert_encoding($new_conf, $encoding, 'UTF-8');
if ($converted_server_config !== false) {
@ -497,7 +897,7 @@ class SatelliteAgent extends HTML
}
}
// Get filenames.
// Get filenames.
if ($this->satellite_server !== false) {
$files = config_satellite_get_satellite_config_filenames($this->satellite_name);
} else {
@ -506,16 +906,40 @@ class SatelliteAgent extends HTML
$files['md5'] = $config['remote_config'].'/md5/'.md5($this->satellite_name).'.srv.md5';
}
// Save configuration
$result = file_put_contents($files['conf'], $new_conf);
// Save configuration.
$result = file_put_contents($files['conf'], $new_conf);
if ($result === false) {
return false;
}
// Save configuration md5
$result = file_put_contents($files['md5'], md5($new_conf));
// Save configuration md5.
$result = file_put_contents($files['md5'], md5($new_conf));
}
/**
* Creates add_host, ignore_host and delete_host blocks
*
* @return void
*/
public function createBlock()
{
$init = preg_grep('/^\#INIT/', $this->satellite_config);
if (empty($init) === true) {
$add_host = "#INIT add_host\n";
$ignore_host = "#INIT ignore_host\n";
$delete_host = "#INIT delete_host\n";
array_push($this->satellite_config, "\n");
array_push($this->satellite_config, $add_host);
array_push($this->satellite_config, $ignore_host);
array_push($this->satellite_config, $delete_host);
$conf = implode('', $this->satellite_config);
$this->saveAgent($conf);
}
}
@ -532,33 +956,36 @@ class SatelliteAgent extends HTML
}
/**
* Minor function to dump json message as ajax response.
*
* @param string $type Type: result || error.
* @param string $msg Message.
* @param boolean $delete Deletion messages.
*
* @return void
*/
private function ajaxMsg($type, $msg, $delete=false)
/**
* Minor function to dump json message as ajax response.
*
* @param string $type Type: result || error.
* @param string $msg Message.
* @param boolean $delete Deletion messages.
* @param boolean $disable Disable messages.
*
* @return void
*/
private function ajaxMsg($type, $msg, $delete=false, $disable=false)
{
$msg_err = 'Failed while saving: %s';
$msg_ok = 'Successfully saved agent ';
if ($delete) {
if ($delete === true) {
$msg_err = 'Failed while removing: %s';
$msg_ok = 'Successfully deleted ';
}
if ($disable === true) {
$msg_err = 'Failed while disabling: %s';
$msg_ok = 'Successfully disabled';
}
if ($type == 'error') {
echo json_encode(
[
$type => ui_print_error_message(
__(
$msg_err,
$msg
),
__($msg),
'',
true
),
@ -568,10 +995,7 @@ class SatelliteAgent extends HTML
echo json_encode(
[
$type => ui_print_success_message(
__(
$msg_ok,
$msg
),
__($msg),
'',
true
),
@ -583,6 +1007,35 @@ class SatelliteAgent extends HTML
}
/**
* Removes duplicate values from a multidimensional array
*
* @param array $array Input array.
* @param array $key Keys.
*
* @return array
*/
public function uniqueMultidimArray($array, $key)
{
$temp_array = [];
$i = 0;
$key_array_name = [];
$key_array_address = [];
foreach ($array as $val) {
if (!in_array($val[$key[0]], $key_array_name) && !in_array($val[$key[1]], $key_array_address)) {
$key_array_name[$i] = $val[$key[0]];
$key_array_address[$i] = $val[$key[1]];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
/**
* Load Javascript code.
*
@ -707,11 +1160,11 @@ class SatelliteAgent extends HTML
/**
* Delete selected agent
*/
function delete_agent(address, name) {
function delete_agent(address, name, deleted, id_agente) {
$('#aux').empty();
$('#aux').text('<?php echo __('Are you sure?'); ?>');
$('#aux').dialog({
title: '<?php echo __('Delete'); ?> ' + address,
title: (deleted == 0) ? '<?php echo __('Delete'); ?> '+address : '<?php echo __('Add'); ?>'+address,
buttons: [
{
class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel',
@ -723,7 +1176,7 @@ class SatelliteAgent extends HTML
}
},
{
text: 'Delete',
text: (deleted == 0) ? 'Delete' : 'Add',
class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next',
click: function(e) {
$.ajax({
@ -734,6 +1187,56 @@ class SatelliteAgent extends HTML
method: 'deleteAgent',
address: address,
name: name,
id: id_agente,
delete: deleted,
server_remote: <?php echo $this->satellite_server; ?>,
},
datatype: "json",
success: function (data) {
showMsg(data);
},
error: function(e) {
showMsg(e);
}
});
}
}
]
});
}
/**
* Disable selected agent
*/
function disable_agent(address, name, disabled, id_agente) {
$('#aux').empty();
$('#aux').text('<?php echo __('Are you sure?'); ?>');
$('#aux').dialog({
title: (disabled == 0) ? '<?php echo __('Disable'); ?>'+address : '<?php echo __('Enable'); ?>'+address,
buttons: [
{
class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel',
text: '<?php echo __('Cancel'); ?>',
click: function(e) {
$(this).dialog('close');
cleanupDOM();
}
},
{
text: (disabled == 0) ? 'Disable' : 'Enable',
class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next',
click: function(e) {
$.ajax({
method: 'post',
url: '<?php echo ui_get_full_url('ajax.php', false, false, false); ?>',
data: {
page: 'enterprise/godmode/servers/agents_satellite',
method: 'disableAgent',
address: address,
disable: disabled,
id: id_agente,
name: name,
server_remote: <?php echo $this->satellite_server; ?>,
},
datatype: "json",
@ -752,12 +1255,77 @@ class SatelliteAgent extends HTML
$(document).ready(function() {
$("#submit-create").on('click', function(){
$("#submit-create").on('click', function() {
show_form();
});
$("#checkbox-all_validate_box").click(function() {
const check = $("#checkbox-all_validate_box").is(":checked");
$('input[name*=check_]').prop('checked', check);
});
$('#submit-submit_satellite_action').click(function() {
const checks = $('input[name*=check_]:checked');
const action = $('#satellite_action').val();
$.each(checks, function(i, val) {
const params = val.value.split(",");
if (action === '0') {
if (params[2] === '0') {
$.ajax({
method: 'post',
async: false,
url: '<?php echo ui_get_full_url('ajax.php', false, false, false); ?>',
data: {
page: 'enterprise/godmode/servers/agents_satellite',
method: 'disableAgent',
address: params[0],
disable: params[3],
id: params[4],
name: params[1],
no_msg: 1,
server_remote: <?php echo $this->satellite_server; ?>,
},
datatype: "json",
success: function (data) {
},
error: function(e) {
console.error(e);
}
});
}
} else {
if (params[3] === '0') {
$.ajax({
method: 'post',
async: false,
url: '<?php echo ui_get_full_url('ajax.php', false, false, false); ?>',
data: {
page: 'enterprise/godmode/servers/agents_satellite',
method: 'deleteAgent',
address: params[0],
name: params[1],
id: params[4],
delete: params[2],
no_msg: 1,
server_remote: <?php echo $this->satellite_server; ?>,
},
datatype: "json",
success: function (data) {
},
error: function(e) {
console.error(e);
}
});
}
}
});
var dt_satellite_agents = $("#satellite_agents").DataTable();
dt_satellite_agents.draw();
});
});
</script>
<?php
// EOF Javascript content.

View File

@ -20,8 +20,8 @@
/**
* Pandora build version and version
*/
$build_version = 'PC220920';
$pandora_version = 'v7.0NG.764';
$build_version = 'PC221014';
$pandora_version = 'v7.0NG.765';
// Do not overwrite default timezone set if defined.
$script_tz = @date_default_timezone_get();

View File

@ -57,11 +57,17 @@ function mysql_connect_db(
$port = $config['dbport'];
}
if ($ssl === null && (bool) $config['dbssl'] === true) {
if ($ssl === null
&& isset($config['dbssl']) === true
&& (bool) $config['dbssl'] === true
) {
$ssl = $config['dbsslcafile'];
}
if ($verify === null && (bool) $config['sslverifyservercert'] === true) {
if ($verify === null
&& isset($config['sslverifyservercert']) === true
&& (bool) $config['sslverifyservercert'] === true
) {
$verify = 'verified';
}

View File

@ -1007,6 +1007,30 @@ function get_parameter_post($name, $default='')
}
/**
* Get header.
*
* @param string $key Key.
* @param string|null $default Default.
*
* @return string|null
*/
function get_header(string $key, ?string $default=null): ?string
{
static $headers;
if (!isset($headers)) {
$headers = getAllHeaders();
}
$adjust_key = ucwords(strtolower($key));
if (isset($headers[$adjust_key])) {
return $headers[$adjust_key];
}
return $default;
}
/**
* Get name of a priority value.
*
@ -6217,3 +6241,31 @@ function notify_reporting_console_node()
return $return;
}
/**
* Auxiliar Ordenation function
*
* @param string $sort Direction of sort.
* @param string $sortField Field for perform the sorting.
*
* @return mixed
*/
function arrayOutputSorting($sort, $sortField)
{
return function ($a, $b) use ($sort, $sortField) {
if ($sort === 'up' || $sort === 'asc') {
if (is_string($a[$sortField]) === true) {
return strnatcasecmp($a[$sortField], $b[$sortField]);
} else {
return ($a[$sortField] - $b[$sortField]);
}
} else {
if (is_string($a[$sortField]) === true) {
return strnatcasecmp($b[$sortField], $a[$sortField]);
} else {
return ($a[$sortField] + $b[$sortField]);
}
}
};
}

View File

@ -795,7 +795,7 @@ function alerts_delete_alert_template($id_alert_template)
*
* @return mixed Array with selected alert templates or false if something goes wrong.
*/
function alerts_get_alert_templates($filter=false, $fields=false)
function alerts_get_alert_templates($filter=false, $fields=false, $total=false)
{
global $config;
@ -811,32 +811,17 @@ function alerts_get_alert_templates($filter=false, $fields=false)
$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;
$limit_sql = '';
if (isset($offset) && isset($limit) && $total === false) {
$limit_sql = " LIMIT $offset, $limit ";
} else {
$limit_sql = '';
}
$sql = sprintf('%s %s', $templates_sql, $limit_sql);
$alert_templates = db_get_all_rows_sql($sql);
return $alert_templates;
}

View File

@ -46,12 +46,18 @@ require_once $config['homedir'].'/include/functions_planned_downtimes.php';
require_once $config['homedir'].'/include/functions_db.php';
require_once $config['homedir'].'/include/functions_event_responses.php';
require_once $config['homedir'].'/include/functions_tactical.php';
require_once $config['homedir'].'/include/functions_reporting.php';
require_once $config['homedir'].'/include/functions_reporting_xml.php';
require_once $config['homedir'].'/include/functions_reports.php';
enterprise_include_once('include/functions_local_components.php');
enterprise_include_once('include/functions_events.php');
enterprise_include_once('include/functions_agents.php');
enterprise_include_once('include/functions_modules.php');
enterprise_include_once('include/functions_clusters.php');
enterprise_include_once('include/functions_alerts.php');
enterprise_include_once('include/functions_reporting_pdf.php');
enterprise_include_once('include/functions_reporting_csv.php');
enterprise_include_once('include/functions_cron.php');
// Clases.
use PandoraFMS\Agent;
@ -1984,12 +1990,10 @@ function api_set_create_os($thrash1, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$values = [];
@ -2024,12 +2028,10 @@ function api_set_update_os($id_os, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$values = [];
@ -2203,8 +2205,8 @@ function api_set_delete_agent($id, $thrash1, $other, $returnType)
}
} else {
// Delete only if the centralised mode is disabled.
$headers = getallheaders();
if (isset($headers['idk']) === false && is_management_allowed($headers['idk']) === false) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
exit;
}
@ -5073,12 +5075,10 @@ function api_set_new_network_component($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -5175,12 +5175,10 @@ function api_set_new_plugin_component($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -5450,12 +5448,10 @@ function api_set_new_local_component($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -5622,12 +5618,10 @@ function api_set_create_alert_template($name, $thrash1, $other, $thrash3)
{
global $config;
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($name == '') {
@ -5765,12 +5759,10 @@ function api_set_update_alert_template($id_template, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id_template == '') {
@ -5917,12 +5909,10 @@ function api_set_delete_alert_template($id_template, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id_template == '') {
@ -7111,12 +7101,10 @@ function api_set_tag($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$values = [];
@ -7821,12 +7809,10 @@ function api_set_update_data_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -7941,12 +7927,10 @@ function api_set_add_network_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8064,12 +8048,10 @@ function api_set_update_network_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8171,12 +8153,10 @@ function api_set_add_plugin_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8305,12 +8285,10 @@ function api_set_update_plugin_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8601,12 +8579,10 @@ function api_set_add_snmp_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8768,12 +8744,10 @@ function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -8933,12 +8907,10 @@ function api_set_remove_agent_from_policy_by_id($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($other['data'][0] == '' || !$other['data'][0]) {
@ -8974,12 +8946,10 @@ function api_set_remove_agent_from_policy_by_name($id, $thrash1, $other, $thrash
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($other['data'][0] == '' || !$other['data'][0]) {
@ -9018,12 +8988,10 @@ function api_set_create_group($id, $thrash1, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$group_name = $id;
@ -9141,12 +9109,10 @@ function api_set_update_group($id_group, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if (db_get_value('id_grupo', 'tgrupo', 'id_grupo', $id_group) === false) {
@ -9218,12 +9184,10 @@ function api_set_delete_group($id_group, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$group = db_get_row_filter('tgrupo', ['id_grupo' => $id_group]);
@ -9545,12 +9509,10 @@ function api_set_new_user($id, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$values = [];
@ -9608,12 +9570,10 @@ function api_set_update_user($id, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$fields_user = [
@ -9708,12 +9668,10 @@ function api_set_enable_disable_user($id, $thrash2, $other, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($id == '') {
@ -9987,12 +9945,10 @@ function api_set_new_alert_template($id, $id2, $other, $trash1)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($other['type'] == 'string') {
@ -10213,7 +10169,7 @@ function api_set_module_data($id, $thrash2, $other, $trash1)
$xmlTemplate,
io_safe_output(get_os_name($agent['id_os'])),
io_safe_output($agent['os_version']),
$agent['intervalo'],
$agentModule['module_interval'],
io_safe_output($agent['agent_version']),
date('Y/m/d H:i:s', $time),
io_safe_output($agent['nombre']),
@ -10410,12 +10366,10 @@ function api_set_alert_actions($id, $id2, $other, $trash1)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($other['type'] == 'string') {
@ -10566,12 +10520,10 @@ function api_set_new_module_group($id, $thrash2, $other, $trash1)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if (!check_acl($config['id_user'], 0, 'PM')) {
@ -10640,12 +10592,10 @@ function api_set_alert_commands($id, $thrash2, $other, $trash1)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$name = db_get_value('id', 'talert_commands', 'name', $id);
@ -11801,12 +11751,10 @@ function api_set_delete_user($id, $thrash1, $thrash2, $thrash3)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if (!delete_user($id)) {
@ -11844,12 +11792,10 @@ function api_set_add_user_profile($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$group = (int) $other['data'][0];
@ -11905,12 +11851,10 @@ function api_set_delete_user_profile($id, $thrash1, $other, $thrash2)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$group = $other['data'][0];
@ -12020,12 +11964,10 @@ function api_set_create_user_profile_info($thrash1, $thrash2, $other, $returnTyp
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$values = [
@ -12081,12 +12023,10 @@ function api_set_update_user_profile_info($id_profile, $thrash1, $other, $return
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$profile = db_get_row('tperfil', 'id_perfil', $id_profile);
@ -12148,12 +12088,10 @@ function api_set_delete_user_profile_info($id_profile, $thrash1, $thrash2, $retu
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$profile = db_get_value('id_perfil', 'tperfil', 'id_perfil', $id_profile);
@ -13040,12 +12978,10 @@ function api_set_create_tag($id, $trash1, $other, $returnType)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$data = [];
@ -13371,12 +13307,6 @@ function api_set_add_event_comment($id, $thrash2, $other, $thrash3)
{
global $config;
if (defined('METACONSOLE')) {
$meta = true;
} else {
$meta = $other['data'][1];
}
if (!check_acl($config['id_user'], 0, 'EW')) {
returnError('forbidden', 'string');
return;
@ -13387,13 +13317,46 @@ function api_set_add_event_comment($id, $thrash2, $other, $thrash3)
return;
} else if ($other['type'] == 'array') {
$comment = $other['data'][0];
$history = $other['data'][2];
$status = events_comment(
$id,
$comment,
'Added comment'
);
$node_int = 0;
if (is_metaconsole() === true) {
if (isset($other['data'][1]) === true
&& empty($other['data'][1]) === false
) {
$node_int = $other['data'][1];
}
}
try {
if (is_metaconsole() === true
&& (int) $node_int > 0
) {
$node = new Node($node_int);
$node->connect();
}
$status = events_comment(
$id,
$comment,
'Added comment'
);
} catch (\Exception $e) {
// Unexistent agent.
if (is_metaconsole() === true
&& $node_int > 0
) {
$node->disconnect();
}
$status = false;
} finally {
if (is_metaconsole() === true
&& $node_int > 0
) {
$node->disconnect();
}
}
if (is_error($status)) {
returnError(
'The event comment could not be added.'
@ -14760,6 +14723,11 @@ function api_set_metaconsole_license_file($key)
return;
}
$license_encryption_key = db_get_value('value', 'tupdate_settings', '`key`', 'license_encryption_key');
if (empty($license_encryption_key) === false) {
$key = openssl_blowfish_encrypt_hex($key, io_safe_output($license_encryption_key));
}
// Update the license file.
$result = file_put_contents($config['remote_config'].'/'.LICENSE_FILE, $key);
if ($result === false) {
@ -17128,12 +17096,10 @@ function api_set_delete_user_permission($thrash1, $thrash2, $other, $returnType)
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
if ($other['data'][0] != '') {
@ -17189,12 +17155,10 @@ function api_set_add_permission_user_to_group($thrash1, $thrash2, $other, $retur
return;
}
$headers = getallheaders();
if (isset($headers['idk']) === false
&& is_management_allowed($headers['idk']) === false
) {
$idk = get_header('idk');
if (is_management_allowed($idk) === false) {
returnError('centralized');
return;
exit;
}
$sql = 'SELECT id_up
@ -17551,3 +17515,302 @@ function api_set_enable_disable_discovery_task($id_task, $thrash2, $other)
}
}
}
/**
* Make report (PDF, CSV or XML) and send it via e-mail (this method is intended to be used by server's execution
* of alert actions that involve sending reports by e-mail).
*
* @param [string] $server_id id server (Node)
* @param [string] $console_event_id console Id node event in tevent
* @param [string] $trash2 don't use
* @param [string] $returnType
*
* --Internal use--
*
* @return void
*/
function api_set_send_report($thrash1, $thrash2, $other, $returnType)
{
global $config;
$id_item = (int) $other['data'][0];
$report_type = $other['data'][1];
$email = $other['data'][2];
$subject_email = $other['data'][3];
$body_email = $other['data'][4];
$make_report_from_template = (bool) $other['data'][5];
$template_regex_agents = $other['data'][6];
// Filter normal and metaconsole reports.
if (is_metaconsole() === true) {
$filter['metaconsole'] = 1;
} else {
$filter['metaconsole'] = 0;
}
$own_info = get_user_info($config['id_user']);
if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'RM') || check_acl($config['id_user'], 0, 'RR')) {
$return_all_group = true;
} else {
$return_all_group = false;
}
if (is_user_admin($config['id_user']) === false) {
$filter[] = sprintf(
'private = 0 OR (private = 1 AND id_user = "%s")',
$config['id_user']
);
}
$date_today = date($config['date_format']);
$date_today = preg_split('/[\s,]+/', io_safe_output($date_today));
$date_today = __($date_today[0]).' '.$date_today[1].' '.$date_today[2].' '.$date_today[3].' '.$date_today[4];
if ($make_report_from_template === true) {
$filter['id_report'] = $id_item;
$template = reports_get_report_templates(
$filter,
['description'],
$return_all_group,
'RR'
)[0];
$description = $template['description'];
// Report macros post-process.
$body_email = str_replace(
[
'_report_description_',
'_report_generated_date_',
'_report_date_',
],
[
$description,
$date_today,
$date_today,
],
$body_email
);
$report_type = strtoupper($report_type);
$body_email = io_safe_output(io_safe_output($body_email));
cron_task_generate_report_by_template(
$id_item,
'',
$template_regex_agents,
false,
'',
$email,
$subject_email,
$body_email,
$report_type,
''
);
} else {
$report = reports_get_report($id_item);
if ($report === false) {
// User has no grant to access this report.
return;
}
// Report macros post-process.
$body_email = str_replace(
[
'_report_description_',
'_report_generated_date_',
'_report_date_',
],
[
$report['description'],
$date_today,
$date_today,
],
$body_email
);
$body_email = io_safe_output(io_safe_output($body_email));
// Set the languaje of user.
global $l10n;
if (isset($l10n) === false) {
$l10n = null;
$user_language = get_user_language($config['id_user']);
if (file_exists(
$config['homedir'].'/include/languages/'.$user_language.'.mo'
) === true
) {
$obj = new CachedFileReader(
$config['homedir'].'/include/languages/'.$user_language.'.mo'
);
$l10n = new gettext_reader($obj);
$l10n->load_tables();
}
}
// Attachments.
$attachments = [];
// Set the datetime for the report.
$report['datetime'] = time();
$date = date('Y-m-j');
$time = date('h:iA');
$tmpfile = false;
switch ($report_type) {
case 'pdf':
$tmpfile = $config['homedir'].'/attachment/'.date('Ymd-His').'.pdf';
$report = reporting_make_reporting_data(
null,
$id_item,
$date,
$time,
null,
'static',
null,
null,
true
);
pdf_get_report($report, $tmpfile);
$attachments[0] = [
'file' => $tmpfile,
'content_type' => 'application/pdf',
];
break;
case 'csv':
$report = reporting_make_reporting_data(
null,
$id_item,
$date,
$time,
null,
'data'
);
$name = explode(' - ', $report['name']);
$tmpfile = $config['homedir'].'/attachment/'.$name[0].'.csv';
// Remove unused fields.
unset($report['header']);
unset($report['first_page']);
unset($report['footer']);
unset($report['custom_font']);
unset($report['id_template']);
unset($report['id_group_edit']);
unset($report['metaconsole']);
unset($report['private']);
unset($report['custom_logo']);
ob_start();
csv_get_report($report, true);
$output = ob_get_clean();
file_put_contents($tmpfile, $output);
ob_end_clean();
$attachments[0] = [
'file' => $tmpfile,
'content_type' => 'text/csv',
];
break;
case 'json':
$report = reporting_make_reporting_data(
null,
$id_item,
$date,
$time,
null,
'data'
);
// Remove unused fields.
unset($report['header']);
unset($report['first_page']);
unset($report['footer']);
unset($report['custom_font']);
unset($report['id_template']);
unset($report['id_group_edit']);
unset($report['metaconsole']);
unset($report['private']);
unset($report['custom_logo']);
$name = explode(' - ', $report['name']);
$tmpfile = $config['homedir'].'/attachment/'.$name[0].'.json';
file_put_contents($tmpfile, json_encode($report, JSON_PRETTY_PRINT));
$attachments[0] = [
'file' => $tmpfile,
'content_type' => 'text/json',
];
break;
case 'xml':
$report = reporting_make_reporting_data(
null,
$id_item,
$date,
$time,
null,
'data'
);
$name = explode(' - ', $report['name']);
$tmpfile = $config['homedir'].'/attachment/'.$name[0].'.xml';
// Remove unused fields.
unset($report['header']);
unset($report['first_page']);
unset($report['footer']);
unset($report['custom_font']);
unset($report['id_template']);
unset($report['id_group_edit']);
unset($report['metaconsole']);
unset($report['private']);
unset($report['custom_logo']);
ob_start();
reporting_xml_get_report($report, true);
$output = ob_get_clean();
file_put_contents($tmpfile, $output);
ob_end_clean();
$attachments[0] = [
'file' => $tmpfile,
'content_type' => 'text/xml',
];
break;
default:
break;
}
reporting_email_template(
$subject_email,
$body_email,
'',
$report['name'],
$email,
$attachments
);
unlink($other['data'][0]);
$data = [
'type' => 'string',
'data' => '1',
];
returnData($returnType, $data, ';');
}
}

View File

@ -1572,6 +1572,18 @@ function config_update_config()
$error_update[] = __('Days');
}
if (config_update_value('history_db_adv', get_parameter_switch('history_db_adv', 0), true) === false) {
$error_update[] = __('Enable history database advanced');
}
$history_db_string_days = get_parameter('history_db_string_days');
if (is_numeric($history_db_string_days) === false
|| $history_db_string_days <= 0
|| config_update_value('history_db_string_days', $history_db_string_days) === false
) {
$error_update[] = __('String Days');
}
$history_event_days = get_parameter('history_event_days');
if (is_numeric($history_event_days) === false
|| $history_event_days <= 0
@ -2502,6 +2514,14 @@ function config_process_config()
config_update_value('history_db_days', 0);
}
if (!isset($config['history_db_adv'])) {
config_update_value('history_db_adv', false);
}
if (!isset($config['history_db_string_days'])) {
config_update_value('history_db_string_days', 0);
}
if (!isset($config['history_event_days'])) {
config_update_value('history_event_days', 90);
}

View File

@ -1381,7 +1381,7 @@ function events_get_all(
// Pagination.
$pagination = '';
if (is_metaconsole() === true
&& empty($id_server) === true
&& (empty($id_server) === true || is_array($id_server) === true)
&& isset($filter['csv_all']) === false
) {
// TODO: XXX TIP. captura el error.
@ -1494,6 +1494,15 @@ function events_get_all(
MAX(id_evento) as max_id_evento',
($idx !== false) ? 'GROUP_CONCAT(DISTINCT user_comment SEPARATOR "<br>") AS comments,' : ''
);
$group_selects_trans = sprintf(
',tmax_event.event_rep,
%s
tmax_event.timestamp_last,
tmax_event.timestamp_first,
tmax_event.max_id_evento',
($idx !== false) ? 'tmax_event.comments,' : ''
);
}
} else {
$idx = array_search('te.user_comment', $fields);
@ -1502,43 +1511,107 @@ function events_get_all(
}
}
$sql = sprintf(
'SELECT %s
if ((int) $filter['group_rep'] === 1 && $count === false) {
$sql = sprintf(
'SELECT %s
%s
FROM %s
INNER JOIN (
SELECT te.id_evento %s
FROM %s
%s
%s
%s JOIN %s ta
ON ta.%s = te.id_agente
%s
%s
%s JOIN tgrupo tg
ON %s
WHERE 1=1
%s
%s
%s
%s
%s
) tmax_event
ON te.id_evento = tmax_event.max_id_evento
%s
FROM %s
%s
%s
%s JOIN %s ta
ON ta.%s = te.id_agente
%s
%s
%s JOIN tgrupo tg
ON %s
WHERE 1=1
%s
%s
%s
%s
%s
',
join(',', $fields),
$group_selects,
$tevento,
$event_lj,
$agentmodule_join,
$tagente_join,
$tagente_table,
$tagente_field,
$conditionMetaconsole,
join(' ', $agent_join_filters),
$tgrupo_join,
join(' ', $tgrupo_join_filters),
join(' ', $sql_filters),
$group_by,
$order_by,
$pagination,
$having
);
%s
%s JOIN %s ta
ON ta.%s = te.id_agente
%s
%s
%s JOIN tgrupo tg
ON %s',
join(',', $fields),
$group_selects_trans,
$tevento,
$group_selects,
$tevento,
$event_lj,
$agentmodule_join,
$tagente_join,
$tagente_table,
$tagente_field,
$conditionMetaconsole,
join(' ', $agent_join_filters),
$tgrupo_join,
join(' ', $tgrupo_join_filters),
join(' ', $sql_filters),
$group_by,
$order_by,
$pagination,
$having,
$event_lj,
$agentmodule_join,
$tagente_join,
$tagente_table,
$tagente_field,
$conditionMetaconsole,
join(' ', $agent_join_filters),
$tgrupo_join,
join(' ', $tgrupo_join_filters),
join(' ', $sql_filters)
);
} else {
$sql = sprintf(
'SELECT %s
%s
FROM %s
%s
%s
%s JOIN %s ta
ON ta.%s = te.id_agente
%s
%s
%s JOIN tgrupo tg
ON %s
WHERE 1=1
%s
%s
%s
%s
%s
',
join(',', $fields),
$group_selects,
$tevento,
$event_lj,
$agentmodule_join,
$tagente_join,
$tagente_table,
$tagente_field,
$conditionMetaconsole,
join(' ', $agent_join_filters),
$tgrupo_join,
join(' ', $tgrupo_join_filters),
join(' ', $sql_filters),
$group_by,
$order_by,
$pagination,
$having
);
}
if ($return_sql === true) {
return $sql;
@ -1583,7 +1656,9 @@ function events_get_all(
if ($count === true
&& (is_metaconsole() === false
|| (is_metaconsole() === true && empty($filter['server_id']) === false))
|| (is_metaconsole() === true
&& empty($filter['server_id']) === false
&& is_array($filter['server_id']) === false))
) {
$sql = 'SELECT count(*) as nitems FROM ('.$sql.') tt';
}
@ -1599,8 +1674,21 @@ function events_get_all(
$metaconsole_connections = array_flip($metaconsole_connections);
$metaconsole_connections['meta'] = 0;
} else {
$only_id_server[$metaconsole_connections[$id_server]] = $id_server;
$metaconsole_connections = $only_id_server;
if (is_array($id_server) === false) {
$only_id_server[$metaconsole_connections[$id_server]] = $id_server;
$metaconsole_connections = $only_id_server;
} else {
$metaConnections = [];
foreach ($id_server as $idser) {
if ((int) $idser === 0) {
$metaConnections['meta'] = 0;
} else {
$metaConnections[$metaconsole_connections[$idser]] = $idser;
}
}
$metaconsole_connections = $metaConnections;
}
}
$result_meta = Promise\wait(
@ -1674,7 +1762,7 @@ function events_get_all(
}
}
if (empty($filter['server_id']) === true) {
if ($count === false) {
if ($sort_field !== 'agent_name'
&& $sort_field !== 'server_name'
&& $sort_field !== 'timestamp'
@ -2005,7 +2093,7 @@ function events_change_owner(
events_comment(
$id_event,
'',
'Change owner to '.$new_owner
'Change owner to '.get_user_fullname($new_owner).' ('.$new_owner.')'
);
}
@ -3211,18 +3299,9 @@ function events_page_responses($event)
foreach ($users as $u) {
$owners[$u['id_user']] = $u['id_user'];
}
if (empty($event['owner_user']) === true) {
$owner_name = __('None');
} else {
$owner_name = db_get_value(
'id_user',
'tusuario',
'id_user',
$event['owner_user']
);
$owners[$event['owner_user']] = $owner_name;
if (empty($u['fullname']) === false) {
$owners[$u['id_user']] = $u['fullname'].' ('.$u['id_user'].')';
}
}
$data[1] = html_print_select(
@ -4831,7 +4910,7 @@ function events_page_comments($event, $ajax=false, $groupedComments=[])
'<b>%s %s %s%s</b>',
$c['action'],
__('by'),
$c['id_user'],
get_user_fullname($c['id_user']).' ('.$c['id_user'].')',
$eventIdExplanation
);

View File

@ -86,7 +86,8 @@ function groupview_get_modules_counters($groups_ids=false)
WHERE tasg.id_group IN ($groups_ids)
GROUP BY tasg.id_group
) x GROUP BY g";
return db_get_all_rows_sql($sql);
$data = db_get_all_rows_sql($sql);
return $data;
}

View File

@ -1664,44 +1664,31 @@ function html_print_select_multiple_modules_filtered(array $data):string
]
);
// Show common modules.
$selection = [
0 => __('Show common modules'),
1 => __('Show all modules'),
];
if (true) {
$output .= html_print_input(
[
'label' => __('Only common modules'),
'type' => 'switch',
'value' => 'checked',
'id' => 'filtered-module-show-common-modules-'.$uniqId,
'return' => true,
'onchange' => 'fmModuleChange(\''.$uniqId.'\', '.(int) is_metaconsole().')',
]
);
} else {
$output .= html_print_input(
[
'label' => __('Show common modules'),
'type' => 'select',
'fields' => $selection,
'name' => 'filtered-module-show-common-modules-'.$uniqId,
'return' => true,
'script' => 'fmModuleChange(\''.$uniqId.'\', '.(int) is_metaconsole().')',
]
);
$commonModules = 0;
if (empty($data['mShowCommonModules']) === false) {
$commonModules = 1;
}
$output .= html_print_input(
[
'label' => __('Only common modules'),
'type' => 'switch',
'checked' => $commonModules,
'value' => $commonModules,
'name' => 'filtered-module-show-common-modules-'.$uniqId,
'id' => 'filtered-module-show-common-modules-'.$uniqId,
'return' => true,
'onchange' => 'fmModuleChange(\''.$uniqId.'\', '.(int) is_metaconsole().')',
]
);
if (empty($data['mAgents']) === false
&& empty($data['mModuleGroup'] === false)
) {
$all_modules = get_modules_agents(
$data['mModuleGroup'],
explode(',', $data['mAgents']),
$data['mShowCommonModules'],
!$commonModules,
false,
true
);
@ -1709,10 +1696,18 @@ function html_print_select_multiple_modules_filtered(array $data):string
$all_modules = [];
}
$mModules = $data['mModules'];
if (is_array($data['mModules']) === false) {
$result = explode(((is_metaconsole() === true) ? SEPARATOR_META_MODULE : ','), $data['mModules']);
} else {
$result = $data['mModules'];
$mModules = explode(
',',
$data['mModules']
);
}
$result = [];
// Clean double safe input.
foreach ($mModules as $name) {
$result[] = io_safe_output($name);
}
$output .= html_print_input(
@ -4956,7 +4951,7 @@ function html_print_input($data, $wrapper='div', $input_only=false)
$output = '';
if (($data['label'] ?? false) && $input_only === false) {
$output = '<'.$wrapper.' id="'.$wrapper.'-'.$data['name'].'" ';
$output = '<'.$wrapper.' id="'.$wrapper.'-'.($data['name'] ?? '').'" ';
$output .= ' class="'.($data['input_class'] ?? '').'">';
$output .= '<label '.$style.' class="'.($data['label_class'] ?? '').'">';
$output .= ($data['label'] ?? '');
@ -4977,7 +4972,7 @@ function html_print_input($data, $wrapper='div', $input_only=false)
if (isset($data['wrapper']) === true) {
$output = '<'.$data['wrapper'].' '.$wrapper_attributes.' id="wr_'.$data['name'].'" ';
$output .= ' class="'.$data['input_class'].'">';
$output .= ' class="'.($data['input_class'] ?? '').'">';
}
switch (($data['type'] ?? null)) {
@ -5097,7 +5092,7 @@ function html_print_input($data, $wrapper='div', $input_only=false)
$output .= html_print_input_color(
$data['name'],
$data['value'],
$data['id'],
($data['id'] ?? ''),
((isset($data['class']) === true) ? $data['class'] : false),
((isset($data['return']) === true) ? $data['return'] : false)
);

View File

@ -3656,7 +3656,7 @@ function get_modules_agents($id_module_group, $id_agents, $selection, $select_mo
$id_agents,
$selection,
false,
false,
$useName,
true
);
@ -3684,8 +3684,8 @@ function get_modules_agents($id_module_group, $id_agents, $selection, $select_mo
if ($occurrences === $nodes_consulted) {
// Module already present in ALL nodes.
$modules[] = [
'id_agente_modulo' => $module_name,
'nombre' => $module_name,
'id_agente_modulo' => io_safe_output($module_name),
'nombre' => io_safe_output($module_name),
];
}
}
@ -3730,7 +3730,7 @@ function get_modules_agents($id_module_group, $id_agents, $selection, $select_mo
function ($carry, $item) use ($useName) {
// Only works in select mode.
if ($useName === true) {
$carry[io_safe_input($item['nombre'])] = $item['nombre'];
$carry[$item['id_node'].'|'.$item['nombre']] = $item['nombre'];
} else {
$carry[$item['id_node'].'|'.$item['id_agente_modulo']] = $item['nombre'];
}
@ -3744,6 +3744,8 @@ function get_modules_agents($id_module_group, $id_agents, $selection, $select_mo
$id_module_group,
$id_agents,
$selection,
false,
$useName,
false
);
}

View File

@ -2702,7 +2702,7 @@ function networkmap_clean_duplicate_links($id)
{
global $config;
$sql_duplicate_links = 'SELECT id, id_parent, id_child
$sql_duplicate_links = 'SELECT *
FROM trel_item t1
WHERE t1.deleted = 0 AND t1.id_child IN (
SELECT t2.id_child
@ -2712,7 +2712,7 @@ function networkmap_clean_duplicate_links($id)
AND t1.id_parent = t2.id_parent
AND t2.id_map = '.$id.')
AND t1.id_map = '.$id.'
ORDER BY id_parent, id_child';
ORDER BY id_parent, id_child, id_parent_source_data desc, id_child_source_data desc';
$rows = db_get_all_rows_sql($sql_duplicate_links);
if (empty($rows) === true) {
@ -2721,28 +2721,49 @@ function networkmap_clean_duplicate_links($id)
$pre_parent = -1;
$pre_child = -1;
$pre_parent_source = -1;
$pre_child_source = -1;
foreach ($rows as $row) {
if (($pre_parent === (int) $row['id_parent'])
&& ($pre_child === (int) $row['id_child'])
) {
// Delete the duplicate row.
db_process_sql_delete(
'trel_item',
['id' => $row['id']]
);
// Agent <-> Agent.
if ((int) $row['parent_type'] === 0 && (int) $row['child_type'] === 0) {
// Delete the duplicate row.
db_process_sql_delete(
'trel_item',
['id' => $row['id']]
);
} else {
// Agent <-> Module or Module <-> Agent or Module <-> Module.
if ($pre_parent_source === (int) $row['id_parent_source_data']
&& $pre_child_source === (int) $row['id_child_source_data']
) {
// Delete the duplicate row.
db_process_sql_delete(
'trel_item',
['id' => $row['id']]
);
} else {
$pre_parent_source = (int) $row['id_parent_source_data'];
$pre_child_source = (int) $row['id_child_source_data'];
}
}
} else {
$pre_parent = $row['id_parent'];
$pre_child = $row['id_child'];
$pre_parent = (int) $row['id_parent'];
$pre_child = (int) $row['id_child'];
if ((int) $row['parent_type'] === 1 || (int) $row['child_type'] === 1) {
$pre_parent_source = (int) $row['id_parent_source_data'];
$pre_child_source = (int) $row['id_child_source_data'];
}
}
}
db_process_sql($sql_duplicate_links);
do {
db_clean_cache();
$sql_duplicate_links_parent_as_children = '
SELECT id, id_parent, id_child
SELECT *
FROM trel_item t1
WHERE t1.deleted = 0 AND t1.id_child IN (
SELECT t2.id_parent
@ -2765,14 +2786,51 @@ function networkmap_clean_duplicate_links($id)
if (($row['id'] != $row2['id'])
&& ($row['id_child'] == $row2['id_parent'])
&& ($row['id_parent'] == $row2['id_child'])
&& ($row['parent_type'] == $row2['child_type'])
&& ($row['child_type'] == $row2['parent_type'])
) {
db_process_sql_delete(
'trel_item',
['id' => $row2['id']]
);
// Agent <-> Agent.
if ((int) $row2['parent_type'] === 0 && (int) $row2['child_type'] === 0) {
db_process_sql_delete(
'trel_item',
['id' => $row2['id']]
);
$found = true;
break;
$found = true;
break;
} else {
// Agent <-> Module or Module <-> Agent or Module <-> Module.
if ((int) $row['id_child_source_data'] === (int) $row2['id_parent_source_data']
&& (int) $row['id_parent_source_data'] === (int) $row2['id_child_source_data']
) {
db_process_sql_delete(
'trel_item',
['id' => $row2['id']]
);
$found = true;
break;
}
}
} else {
// Si no son del mismo tipo pero hay un parent_type = 0 y child_type = 0 borrar.
if ((int) $row['parent_type'] === 0 && (int) $row['child_type'] === 0) {
db_process_sql_delete(
'trel_item',
['id' => $row['id']]
);
$found = true;
break;
} else if ((int) $row2['parent_type'] === 0 && (int) $row2['child_type'] === 0) {
db_process_sql_delete(
'trel_item',
['id' => $row2['id']]
);
$found = true;
break;
}
}
}
@ -3020,53 +3078,96 @@ function networkmap_delete_link(
function erase_node($id)
{
$node = db_get_row('titem', 'id', $id['id']);
if ($node['type'] !== '2') {
$return = db_process_sql_update(
'titem',
['deleted' => 1],
[
'id' => (int) $node['id'],
'id_map' => (int) $node['id_map'],
]
);
$return = db_process_sql_update(
'titem',
['deleted' => 1],
['id' => $node['id']]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
[
'id_parent' => (int) $node['id'],
'id_map' => (int) $node['id_map'],
]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
['id_parent' => (int) $node['id']]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
[
'id_child' => (int) $node['id'],
'id_map' => (int) $node['id_map'],
]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
['id_child' => (int) $node['id']]
);
$node_modules = db_get_all_rows_filter(
'titem',
[
'id_map' => $node['id_map'],
'type' => 1,
]
);
$node_modules = db_get_all_rows_filter(
'titem',
[
'id_map' => $node['id_map'],
'type' => 1,
]
);
foreach ($node_modules as $node_module) {
$style = json_decode($node_module['style'], true);
foreach ($node_modules as $node_module) {
$style = json_decode($node_module['style'], true);
if ($style['id_agent'] == $node['source_data']) {
db_process_sql_update(
'titem',
['deleted' => 1],
['id' => $node_module['id']]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
['id_parent_source_data' => (int) $node_module['source_data']]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
['id_child_source_data' => (int) $node_module['source_data']]
);
if ($style['id_agent'] == $node['source_data']) {
db_process_sql_update(
'titem',
['deleted' => 1],
[
'id' => (int) $node_module['id'],
'id_map' => (int) $node_module['id_map'],
]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
[
'id_parent_source_data' => (int) $node_module['source_data'],
'id_map' => (int) $node_module['id_map'],
]
);
db_process_sql_update(
'trel_item',
['deleted' => 1],
[
'id_child_source_data' => (int) $node_module['source_data'],
'id_map' => (int) $node_module['id_map'],
]
);
}
}
} else {
$return = db_process_sql_delete(
'titem',
[
'id' => (int) $node['id'],
'id_map' => (int) $node['id_map'],
]
);
db_process_sql_delete(
'trel_item',
[
'parent_type' => 2,
'id_map' => (int) $node['id_map'],
]
);
db_process_sql_delete(
'trel_item',
[
'child_type' => 2,
'id_map' => (int) $node['id_map'],
]
);
}
if ($return === false) {
@ -3504,6 +3605,7 @@ function update_node($node, $holding_area_x, $holding_area_y)
$values = [];
$values['x'] = $node['x'];
$values['y'] = $node['y'];
$values['refresh'] = 0;
if ($node['state'] === 'holding_area') {
$networkmap_node = db_get_row_filter(
@ -3526,14 +3628,9 @@ function update_node($node, $holding_area_x, $holding_area_y)
) {
// Inside holding area.
$return['state'] = 'holding_area';
$values['refresh'] = 1;
} else {
// The user move the node out the holding area.
db_process_sql_update(
'titem',
['refresh' => 0],
['id' => $node['id_db']]
);
$return['state'] = '';
}
}
@ -4053,6 +4150,7 @@ function add_agent_node_in_option($id_networkmap, $id_agent, $x, $y)
function networkmap_get_new_nodes_and_links($networkmap, $x, $y)
{
$id_networkmap = $networkmap['id'];
$id_recon = $networkmap['source_data'];
$map_filter = $networkmap['filter'];
if (is_array($map_filter) === false) {
@ -4060,11 +4158,11 @@ function networkmap_get_new_nodes_and_links($networkmap, $x, $y)
}
if ((int) $networkmap['source'] === SOURCE_TASK) {
$agents = get_discovery_agents($networkmap, true);
$agents = get_discovery_agents($id_recon, true);
} else if ((int) $networkmap['source'] === SOURCE_NETWORK) {
// Network map, based on direct network.
$agents = networkmap_get_nodes_from_ip_mask(
$networkmap['source_data'],
$id_recon,
true
);
} else {
@ -4274,290 +4372,291 @@ function networkmap_get_new_nodes_and_links($networkmap, $x, $y)
}
}
// Get L2 interface relations.
$interfaces = modules_get_interfaces(
$node['source_data'],
// foreach ($interfaces as $interface) {
// $relations = modules_get_relations(
// ['id_module' => $interface['id_agente_modulo']]
// );
// if (empty($relations) === true) {
// $relations = [];
// }
// foreach ($relations as $relation) {
// Get the links althought they are deleted (for to
// avoid to add)
// Check if the module is ping.
// if (modules_get_agentmodule_type($relation['module_a']) === '6') {
// The pings modules are not exist as interface
// the link is with the agent.
// $node_a = db_get_value_filter(
// 'id',
// 'titem',
// [
// 'source_data' => modules_get_agentmodule_agent(
// $relation['module_a']
// ),
// 'id_map' => $id_networkmap,
// ]
// );
// } else {
// $node_a = db_get_value_filter(
// 'id',
// 'titem',
// [
// 'source_data' => $relation['module_a'],
// 'type' => 1,
// 'id_map' => $id_networkmap,
// ]
// );
// }
// Check if the module is ping.
// if (modules_get_agentmodule_type($relation['module_b']) == 6) {
// The pings modules are not exist as interface
// the link is with the agent.
// $node_b = db_get_value_filter(
// 'id',
// 'titem',
// [
// 'source_data' => modules_get_agentmodule_agent(
// $relation['module_b']
// ),
// 'id_map' => $id_networkmap,
// ]
// );
// } else {
// $node_b = db_get_value_filter(
// 'id',
// 'titem',
// [
// 'source_data' => $relation['module_b'],
// 'type' => 1,
// 'id_map' => $id_networkmap,
// ]
// );
// }
// $exist = db_get_row_filter(
// 'trel_item',
// [
// 'id_map' => $id_networkmap,
// 'id_parent_source_data' => $relation['module_a'],
// 'id_child_source_data' => $relation['module_b'],
// 'deleted' => 0,
// ]
// );
// $exist_reverse = db_get_row_filter(
// 'trel_item',
// [
// 'id_map' => $id_networkmap,
// 'id_parent_source_data' => $relation['module_b'],
// 'id_child_source_data' => $relation['module_a'],
// 'deleted' => 0,
// ]
// );
// if (empty($exist) && empty($exist_reverse)) {
// Create the nodes for interfaces
// Ag1 ----- I1 ------ I2 ----- Ag2
// * 2 interfaces nodes
// * 3 relations
// * I1 between I2
// * Ag1 between I1
// * Ag2 between I2
//
// But check if it exists the relations
// agent between interface.
// if ($interface['id_agente_modulo'] == $relation['module_a']) {
// $agent_a = $interface['id_agente'];
// $agent_b = modules_get_agentmodule_agent(
// $relation['module_b']
// );
// } else {
// $agent_a = modules_get_agentmodule_agent(
// $relation['module_a']
// );
// $agent_b = $interface['id_agente'];
// }
// $item_a = db_get_value(
// 'id',
// 'titem',
// 'source_data',
// $agent_a
// );
// $item_b = db_get_value(
// 'id',
// 'titem',
// 'source_data',
// $agent_b
// );
// hd('----------------------', true);
// hd($agent_a, true);
// hd($agent_b, true);
// foreach ($interfaces as $interface) {
// $relations = modules_get_relations(
// ['id_module' => $interface['id_agente_modulo']]
// );
// if (empty($relations) === true) {
// $relations = [];
// }
// foreach ($relations as $relation) {hd($item_a. '<->'. $item_b, true);
// hd('----------------------', true);
// continue;
// $exist_node_interface1 = db_get_row_filter(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'type' => 0,
// 'source_data' => $relation['module_a'],
// ]
// );
// if (empty($exist_node_interface1) === true) {
// Crete the interface node
// and create the relation between agent and
// interface.
// $style = [];
// $style['id_agent'] = $agent_a;
// $style['shape'] = 'circle';
// $style['image'] = 'images/mod_snmp_proc.png';
// $style['width'] = 50;
// $style['height'] = 16;
// $style['label'] = modules_get_agentmodule_name($relation['module_a']);
// $id_int1 = db_process_sql_insert(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'x' => 666,
// 'y' => 666,
// 'z' => 0,
// 'deleted' => 0,
// 'type' => 1,
// 'refresh' => 0,
// 'source' => 0,
// 'source_data' => $relation['module_a'],
// 'style' => json_encode($style),
// ]
// );
// $node_interface1 = db_get_row_filter(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'type' => 1,
// 'id' => $id_int1,
// ]
// );
// $node_agent1 = db_get_value(
// 'id',
// 'titem',
// 'source_data',
// $agent_a
// );
// db_process_sql_insert(
// 'trel_item',
// [
// 'id_map' => $id_networkmap,
// 'id_parent' => $node_agent1,
// 'id_child' => $node_interface1,
// 'id_parent-source_data' => $agent_a,
// 'id_child-source_data' => $relation['module_a'],
// 'parent_type' => 0,
// 'child_type' => 1,
// ]
// );
// } else {
// $node_interface1 = $exist_node_interface1;
// }
// $exist_node_interface2 = db_get_row_filter(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'type' => 1,
// 'source_data' => $relation['module_b'],
// ]
// );
// if (empty($exist_node_interface2) === true) {
// Crete the interface node
// and create the relation between agent and
// interface.
// $style = [];
// $style['id_agent'] = $agent_a;
// $style['shape'] = 'circle';
// $style['image'] = 'images/mod_snmp_proc.png';
// $style['width'] = 50;
// $style['height'] = 16;
// $style['label'] = modules_get_agentmodule_name($relation['module_b']);
// $id_int2 = db_process_sql_insert(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'x' => 666,
// 'y' => 666,
// 'z' => 0,
// 'deleted' => 0,
// 'type' => 1,
// 'refresh' => 0,
// 'source' => 0,
// 'source_data' => $relation['module_b'],
// 'style' => json_encode($style),
// ]
// );
// $node_interface2 = db_get_row_filter(
// 'titem',
// [
// 'id_map' => $id_networkmap,
// 'type' => 1,
// 'id' => $id_int1,
// ]
// );
// $node_agent1 = db_get_value(
// 'id',
// 'titem',
// 'source_data',
// $agent_a
// );
// db_process_sql_insert(
// 'trel_item',
// [
// 'id_map' => $id_networkmap,
// 'id_parent' => $node_agent1,
// 'id_child' => $node_interface1,
// 'id_parent-source_data' => $agent_a,
// 'id_child-source_data' => $relation['module_b'],
// 'parent_type' => 0,
// 'child_type' => 1,
// ]
// );
// } else {
// $node_interface2 = $exist_node_interface2;
// }
// if (empty($node_interface1) === false && empty($node_interface2) === false) {
// if (is_array($node_interface1) === true) {
// $node_interface1 = $node_interface1['id'];
// }
// if (is_array($node_interface2) === true) {
// $node_interface2 = $node_interface2['id'];
// }
// db_process_sql_insert(
// 'trel_item',
// [
// 'id_map' => $id_networkmap,
// 'id_parent' => $node_interface2,
// 'id_child' => $node_interface1,
// 'id_parent_source_data' => $relation['module_b'],
// 'id_child_source_data' => $relation['module_a'],
// 'parent_type' => 1,
// 'child_type' => 1,
// ]
// );
// }
// }
// }
// }
$relations = modules_get_relations(
[
'id_agente',
'id_agente_modulo',
'id_agent' => $node['source_data'],
'networkmap' => true,
]
);
if (empty($interfaces) === true) {
$interfaces = [];
}
foreach ($interfaces as $interface) {
$relations = modules_get_relations(
['id_module' => $interface['id_agente_modulo']]
);
if (empty($relations) === true) {
$relations = [];
}
foreach ($relations as $relation) {
// Get the links althought they are deleted (for to
// avoid to add)
// Check if the module is ping.
if (modules_get_agentmodule_type($relation['module_a']) === '6') {
// The pings modules are not exist as interface
// the link is with the agent.
$node_a = db_get_value_filter(
'id',
'titem',
[
'source_data' => modules_get_agentmodule_agent(
$relation['module_a']
),
'id_map' => $id_networkmap,
]
);
} else {
$node_a = db_get_value_filter(
'id',
'titem',
[
'source_data' => $relation['module_a'],
'type' => 1,
'id_map' => $id_networkmap,
]
);
}
// Check if the module is ping.
if (modules_get_agentmodule_type($relation['module_b']) == 6) {
// The pings modules are not exist as interface
// the link is with the agent.
$node_b = db_get_value_filter(
'id',
'titem',
[
'source_data' => modules_get_agentmodule_agent(
$relation['module_b']
),
'id_map' => $id_networkmap,
]
);
} else {
$node_b = db_get_value_filter(
'id',
'titem',
[
'source_data' => $relation['module_b'],
'type' => 1,
'id_map' => $id_networkmap,
]
);
}
$exist = db_get_row_filter(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent_source_data' => $relation['module_a'],
'id_child_source_data' => $relation['module_b'],
'deleted' => 0,
]
);
$exist_reverse = db_get_row_filter(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent_source_data' => $relation['module_b'],
'id_child_source_data' => $relation['module_a'],
'deleted' => 0,
]
);
if (empty($exist) && empty($exist_reverse)) {
// Create the nodes for interfaces
// Ag1 ----- I1 ------ I2 ----- Ag2
// * 2 interfaces nodes
// * 3 relations
// * I1 between I2
// * Ag1 between I1
// * Ag2 between I2
//
// But check if it exists the relations
// agent between interface.
if ($interface['id_agente_modulo'] == $relation['module_a']) {
$agent_a = $interface['id_agente'];
$agent_b = modules_get_agentmodule_agent(
$relation['module_b']
);
} else {
$agent_a = modules_get_agentmodule_agent(
$relation['module_a']
);
$agent_b = $interface['id_agente'];
}
$exist_node_interface1 = db_get_row_filter(
'titem',
[
'id_map' => $id_networkmap,
'type' => 1,
'source_data' => $relation['module_a'],
]
);
if (empty($exist_node_interface1) === true) {
// Crete the interface node
// and create the relation between agent and
// interface.
$style = [];
$style['id_agent'] = $agent_a;
$style['shape'] = 'circle';
$style['image'] = 'images/mod_snmp_proc.png';
$style['width'] = 50;
$style['height'] = 16;
$style['label'] = modules_get_agentmodule_name($relation['module_a']);
$id_int1 = db_process_sql_insert(
'titem',
[
'id_map' => $id_networkmap,
'x' => 666,
'y' => 666,
'z' => 0,
'deleted' => 0,
'type' => 1,
'refresh' => 0,
'source' => 0,
'source_data' => $relation['module_a'],
'style' => json_encode($style),
]
);
$node_interface1 = db_get_row_filter(
'titem',
[
'id_map' => $id_networkmap,
'type' => 1,
'id' => $id_int1,
]
);
$node_agent1 = db_get_value(
'id',
'titem',
'source_data',
$agent_a
);
db_process_sql_insert(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent' => $node_agent1,
'id_child' => $node_interface1,
'id_parent-source_data' => $agent_a,
'id_child-source_data' => $relation['module_a'],
'parent_type' => 0,
'child_type' => 1,
]
);
} else {
$node_interface1 = $exist_node_interface1;
}
$exist_node_interface2 = db_get_row_filter(
'titem',
[
'id_map' => $id_networkmap,
'type' => 1,
'source_data' => $relation['module_b'],
]
);
if (empty($exist_node_interface2) === true) {
// Crete the interface node
// and create the relation between agent and
// interface.
$style = [];
$style['id_agent'] = $agent_a;
$style['shape'] = 'circle';
$style['image'] = 'images/mod_snmp_proc.png';
$style['width'] = 50;
$style['height'] = 16;
$style['label'] = modules_get_agentmodule_name($relation['module_b']);
$id_int2 = db_process_sql_insert(
'titem',
[
'id_map' => $id_networkmap,
'x' => 666,
'y' => 666,
'z' => 0,
'deleted' => 0,
'type' => 1,
'refresh' => 0,
'source' => 0,
'source_data' => $relation['module_b'],
'style' => json_encode($style),
]
);
$node_interface2 = db_get_row_filter(
'titem',
[
'id_map' => $id_networkmap,
'type' => 1,
'id' => $id_int1,
]
);
$node_agent1 = db_get_value(
'id',
'titem',
'source_data',
$agent_a
);
db_process_sql_insert(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent' => $node_agent1,
'id_child' => $node_interface1,
'id_parent-source_data' => $agent_a,
'id_child-source_data' => $relation['module_b'],
'parent_type' => 0,
'child_type' => 1,
]
);
} else {
$node_interface2 = $exist_node_interface2;
}
if (empty($node_interface1) === false && empty($node_interface2) === false) {
if (is_array($node_interface1) === true) {
$node_interface1 = $node_interface1['id'];
}
if (is_array($node_interface2) === true) {
$node_interface2 = $node_interface2['id'];
}
db_process_sql_insert(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent' => $node_interface2,
'id_child' => $node_interface1,
'id_parent_source_data' => $relation['module_b'],
'id_child_source_data' => $relation['module_a'],
'parent_type' => 1,
'child_type' => 1,
]
);
}
}
}
}
$relations = modules_get_relations(['id_agent' => $node['source_data']]);
if ($relations === false) {
$relations = [];
}
// Relations Module <-> Module.
foreach ($relations as $key => $relation) {
$module_a = $relation['module_a'];
$agent_a = modules_get_agentmodule_agent($module_a);
@ -4584,58 +4683,26 @@ function networkmap_get_new_nodes_and_links($networkmap, $x, $y)
);
if (empty($exist) === true && empty($exist_reverse) === true) {
$style = [];
$style['id_agent'] = $agent_a;
$style['shape'] = 'circle';
$style['image'] = 'images/mod_snmp_proc.png';
$style['width'] = 50;
$style['height'] = 16;
$style['label'] = modules_get_agentmodule_name($module_a);
$id_int1 = db_process_sql_insert(
$item_a = db_get_value(
'id',
'titem',
[
'id_map' => $id_networkmap,
'x' => 666,
'y' => 666,
'z' => 0,
'deleted' => 0,
'type' => 1,
'refresh' => 0,
'source' => 0,
'source_data' => $module_a,
'style' => json_encode($style),
]
'source_data',
$agent_a
);
$style = [];
$style['id_agent'] = $agent_b;
$style['shape'] = 'circle';
$style['image'] = 'images/mod_snmp_proc.png';
$style['width'] = 50;
$style['height'] = 16;
$style['label'] = modules_get_agentmodule_name($module_b);
$id_int2 = db_process_sql_insert(
$item_b = db_get_value(
'id',
'titem',
[
'id_map' => $id_networkmap,
'x' => 666,
'y' => 666,
'z' => 0,
'deleted' => 0,
'type' => 1,
'refresh' => 0,
'source' => 0,
'source_data' => $module_b,
'style' => json_encode($style),
]
'source_data',
$agent_b
);
db_process_sql_insert(
'trel_item',
[
'id_map' => $id_networkmap,
'id_parent' => $id_int1,
'id_child' => $id_int2,
'id_parent' => $item_a,
'id_child' => $item_b,
'id_parent_source_data' => $module_a,
'id_child_source_data' => $module_b,
'parent_type' => 1,
@ -4644,6 +4711,30 @@ function networkmap_get_new_nodes_and_links($networkmap, $x, $y)
);
}
}
// Get L2 interface relations.
$interfaces = modules_get_interfaces(
$node['source_data'],
[
'id_agente',
'id_agente_modulo',
]
);
if (empty($interfaces) === true) {
$interfaces = [];
}
// hd('interfaces', true);
// foreach ($interfaces as $interface) {
// $relations = modules_get_relations(
// ['id_module' => $interface['id_agente_modulo']]
// );
// if (empty($relations) === true) {
// $relations = [];
// }
// foreach ($relations as $relation) {
// }
// }
}
}

View File

@ -7213,7 +7213,7 @@ function reporting_sql($report, $content)
$sql = $content['external_source'];
}
// Check if exist sql macro
// Check if exist sql macro.
$sql = reporting_sql_macro($report, $sql);
// Do a security check on SQL coming from the user.
@ -7746,15 +7746,7 @@ function reporting_advanced_sla(
}
if (isset($max_value) === false || (int) $max_value === 0) {
if ($max_value === '0'
&& $max_value < $min_value
&& isset($min_value_warning) === true
&& $min_value_warning > $max_value
) {
$max_value = $min_value_warning;
} else {
$max_value = null;
}
$max_value = null;
}
if (isset($max_value) === false && isset($min_value) === false) {
@ -8309,18 +8301,21 @@ function reporting_advanced_sla(
$inverse_interval
);
// Warning SLA check.
$sla_check_value_warning = sla_check_value(
$current_data['datos'],
$min_value_warning,
$max_value_warning,
$inverse_interval_warning,
1
);
$sla_check_value_warning = false;
if ($sla_check_value === true) {
// Warning SLA check.
$sla_check_value_warning = sla_check_value(
$current_data['datos'],
$min_value_warning,
$max_value_warning,
$inverse_interval_warning,
1
);
}
}
// Not unknown nor not init values.
if ($sla_check_value_warning && $sla_check_warning === true) {
if ($sla_check_value_warning === true && $sla_check_warning === true) {
if (isset($current_data['type']) === false
|| ((int) $current_data['type'] === 0
&& $i !== 0)
@ -11542,7 +11537,7 @@ function reporting_get_group_stats_resume($id_group=0, $access='AR', $ignore_per
$data['status'] = 'critical';
} else if ($data['monitor_warning'] > 0) {
$data['status'] = 'warning';
} else if (($data['monitor_unknown'] > 0) || ($data['agents_unknown'] > 0)) {
} else if (($data['monitor_unknown'] > 0) || ($data['agent_unknown'] > 0)) {
$data['status'] = 'unknown';
} else if ($data['monitor_ok'] > 0) {
$data['status'] = 'ok';
@ -14723,6 +14718,25 @@ function reporting_sql_macro(array $report, string $sql): string
);
}
if (preg_match('/_start_date_/', $sql)) {
$date_init = get_parameter('date_init', date(DATE_FORMAT, (strtotime(date('Y-m-j')) - SECONDS_1DAY)));
$time_init = get_parameter('time_init', date(TIME_FORMAT, (strtotime(date('Y-m-j')) - SECONDS_1DAY)));
$datetime_init = strtotime($date_init.' '.$time_init);
$sql = str_replace(
'_start_date_',
$datetime_init,
$sql
);
}
if (preg_match('/_end_date_/', $sql)) {
$sql = str_replace(
'_end_date_',
$report['datetime'],
$sql
);
}
return $sql;
}

View File

@ -1408,3 +1408,77 @@ function custom_fields_macros_report($macro, $key_macro)
return $result;
}
/**
* Get a list of the reports the user can view.
*
* A user can view a report by two ways:
* - The user created the report (id_user field in treport)
* - The report is not private and the user has reading privileges on
* the group associated to the report
*
* @param array Extra filter to retrieve reports. All reports are returned by
* default
* @param array Fields to be fetched on every report.
*
* @return array An array with all the reports the user can view.
*/
function reports_get_report_templates(
$filter=false,
$fields=false,
$returnAllGroup=true,
$privileges='RR',
$group=false,
$strict_user=false
) {
global $config;
if (is_array($filter) === false) {
$filter = [];
}
if (is_array($fields) === false) {
$fields[] = 'id_group';
$fields[] = 'id_user';
}
$templates = [];
$all_templates = @db_get_all_rows_filter('treport_template', $filter, $fields);
if (empty($all_templates) === true) {
$all_templates = [];
}
if ($group) {
$groups = $group;
} else {
$groups = users_get_groups($config['id_user'], $privileges, $returnAllGroup);
if ($strict_user) {
$groups = users_get_strict_mode_groups($config['id_user'], $returnAllGroup);
}
}
foreach ($all_templates as $template) {
// If the template is not in all group.
if ($template['id_group'] != 0) {
if (!in_array($template['id_group'], array_keys($groups))) {
continue;
}
if ($config['id_user'] != $template['id_user']
&& !check_acl($config['id_user'], $template['id_group'], $privileges)
) {
continue;
}
} else {
if ($returnAllGroup === false) {
continue;
}
}
array_push($templates, $template);
}
return $templates;
}

View File

@ -1075,7 +1075,7 @@ function ui_format_alert_row(
}
}
if (is_metaconsole() === true) {
if (is_metaconsole() === true && (int) $server_id !== 0) {
$server = db_get_row('tmetaconsole_setup', 'id', $alert['server_data']['id']);
if (metaconsole_connect($server) == NOERR) {
@ -3655,7 +3655,7 @@ function ui_print_datatable(array $parameters)
order: [[ '.$order.' ]]
};
var dt_'.$table_id.' = $("#'.$table_id.'").DataTable(settings_datatable);
dt_'.$table_id.' = $("#'.$table_id.'").DataTable(settings_datatable);
$("#'.$form_id.'_search_bt").click(function (){
dt_'.$table_id.'.draw().page(0)
@ -4101,17 +4101,20 @@ function ui_toggle(
// JQuery Toggle.
$output .= '<script type="text/javascript">'."\n";
$output .= ' var hide_tgl_ctrl_'.$uniqid.' = '.(int) $hidden_default.";\n";
$output .= ' var is_metaconsole = '.(int) is_metaconsole().";\n";
$output .= ' /* <![CDATA[ */'."\n";
$output .= " $(document).ready (function () {\n";
$output .= " $('#checkbox-".$switch_name."').click(function() {\n";
$output .= ' if (hide_tgl_ctrl_'.$uniqid.") {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 0;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " }\n";
$output .= " else {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 1;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " }\n";
$output .= ' if (is_metaconsole == 0) {';
$output .= ' if (hide_tgl_ctrl_'.$uniqid.") {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 0;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " }\n";
$output .= " else {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 1;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " }\n";
$output .= " }\n";
$output .= " });\n";
$output .= " $('#tgl_ctrl_".$uniqid."').click(function() {\n";
$output .= ' if (hide_tgl_ctrl_'.$uniqid.") {\n";

View File

@ -877,3 +877,52 @@ function users_get_users_group_by_group($id_group)
return $users;
}
/**
* Check if IP is in range. Check wildcard `*`, single IP and IP ranges.
*
* @param array $arrayIP List of IPs.
* @param string $userIP IP for determine if is in the list.
*
* @return boolean True if IP is in range.
*/
function checkIPInRange(
array $arrayIP,
string $userIP=''
) {
$output = false;
if (empty($userIP) === true) {
$userIP = $_SERVER['REMOTE_ADDR'];
}
if (empty($arrayIP) === false) {
foreach ($arrayIP as $ip) {
if ($ip === '*') {
// The list has wildcard, this accept all IPs.
$output = true;
break;
} else if ($ip === $userIP) {
$output = true;
break;
} else if (preg_match('/([0-2]?[0-9]{1,2})[.]([0-2]?[0-9]{1,2})[.]([0-2]?[0-9]{0,2})[.](0){1}/', $ip) > 0) {
$rangeArrayIP = explode('.', $ip);
$userArrayIP = explode('.', $userIP);
foreach ($rangeArrayIP as $position => $segmentIP) {
if ($segmentIP === $userArrayIP[$position]) {
$output = true;
} else if ((string) $segmentIP === '0') {
break 2;
} else {
$output = false;
}
}
} else {
$output = false;
}
}
}
return $output;
}

View File

@ -4080,7 +4080,7 @@ function visual_map_get_layout_status($layout_id, $status_data=[], $depth=0)
// 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'
if ((isset($status_data['linked_layout_status_type']) === true && $status_data['linked_layout_status_type'] === 'default')
&& ($status == VISUAL_MAP_STATUS_CRITICAL_BAD
|| $status == VISUAL_MAP_STATUS_CRITICAL_ALERT)
) {
@ -4104,71 +4104,73 @@ function visual_map_get_layout_status($layout_id, $status_data=[], $depth=0)
metaconsole_restore_db();
}
// 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_alert = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT];
$num_items_warning = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING];
$num_items_unknown = $num_elements_by_status[VISUAL_MAP_STATUS_UNKNOWN];
if (isset($status_data['linked_layout_status_type']) === true) {
// 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_alert = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT];
$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_alert > 0) {
return VISUAL_MAP_STATUS_WARNING_ALERT;
} 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_alert = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT];
$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_alert > 0) {
return VISUAL_MAP_STATUS_WARNING_ALERT;
} 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_alert = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT];
$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 > 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_alert > 0)
&& (($num_items_warning_alert + $num_items_warning * 100) / $num_items) >= $weight
) {
return ($num_items_warning_alert > 0) ? VISUAL_MAP_STATUS_WARNING_ALERT : 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;
if (($num_items_critical > 0 || $num_items_critical_alert > 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_alert > 0)
&& (($num_items_warning_alert + $num_items_warning * 100) / $num_items) >= $weight
) {
return ($num_items_warning_alert > 0) ? VISUAL_MAP_STATUS_WARNING_ALERT : 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));
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));
$num_items_warning = ($num_elements_by_status[VISUAL_MAP_STATUS_WARNING] + $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT]);
$warning_percentage = (($num_items_warning * 100) / count($valid_layout_items));
$num_items_warning = ($num_elements_by_status[VISUAL_MAP_STATUS_WARNING] + $num_elements_by_status[VISUAL_MAP_STATUS_WARNING_ALERT]);
$warning_percentage = (($num_items_warning * 100) / count($valid_layout_items));
if ($critical_percentage >= $status_data['linked_layout_status_as_service_critical'] && $critical_percentage !== 0) {
return VISUAL_MAP_STATUS_CRITICAL_BAD;
} else if ($warning_percentage >= $status_data['linked_layout_status_as_service_warning'] && $warning_percentage !== 0) {
return VISUAL_MAP_STATUS_WARNING;
} else {
return VISUAL_MAP_STATUS_NORMAL;
}
break;
if ($critical_percentage >= $status_data['linked_layout_status_as_service_critical'] && $critical_percentage !== 0) {
return VISUAL_MAP_STATUS_CRITICAL_BAD;
} else if ($warning_percentage >= $status_data['linked_layout_status_as_service_warning'] && $warning_percentage !== 0) {
return VISUAL_MAP_STATUS_WARNING;
} else {
return VISUAL_MAP_STATUS_NORMAL;
}
break;
}
}
}

View File

@ -526,8 +526,7 @@ function print_clock_analogic_1(
$color,
$title=true
) {
global $config;
$output .= '<style type="text/css">
$output = '<style type="text/css">
#rim {
fill: none;
stroke: #999;

View File

@ -192,7 +192,8 @@ function delete_link(
source_module_id,
target_id,
target_module_id,
id_link
id_link,
table_row = null
) {
var params = [];
params.push("delete_link=1");
@ -241,8 +242,22 @@ function delete_link(
draw_elements_graph();
init_drag_and_drop();
set_positions_graph();
if (typeof table_row !== "undefined" && table_row !== null) {
$(`#relations_table-template_row_${table_row}`).animate(
{ backgroundColor: "#e6e6e6" },
500,
function() {
$(`#relations_table-template_row_${table_row}`).remove();
const rowCount = $(".relation_link_row").length;
if (rowCount === 0) {
$("#relations_table-no_relations").show();
$(`#update_relations_button`).remove();
}
}
);
}
}
$("#dialog_node_edit").dialog("close");
}
});
}
@ -378,11 +393,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -419,11 +430,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -446,11 +453,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -487,11 +490,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -515,11 +514,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -556,11 +551,7 @@ function change_shape(id_db_node) {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -607,6 +598,10 @@ function update_link(row_index, id_link) {
$(".edit_icon_progress_" + row_index).css("display", "");
$(".edit_icon_" + row_index).css("display", "none");
$(".edit_icon_" + row_index).css("display", "none");
let result = false;
var params = [];
params.push("update_link=1");
params.push("networkmap_id=" + networkmap_id);
@ -621,6 +616,7 @@ function update_link(row_index, id_link) {
data: params.join("&"),
dataType: "json",
type: "POST",
async: false,
url: window.base_url_homedir + "/ajax.php",
success: function(data) {
$(".edit_icon_progress_" + row_index).css("display", "none");
@ -726,11 +722,14 @@ function update_link(row_index, id_link) {
draw_elements_graph();
init_drag_and_drop();
set_positions_graph();
result = data["id_db_link"];
} else {
$(".edit_icon_fail_" + row_index).css("display", "");
}
}
});
return result;
}
function delete_link_from_id(index) {
@ -826,51 +825,81 @@ function edit_node(data_node, dblClick) {
"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=operation/agentes/pandora_networkmap.view");
jQuery.ajax({
data: params.join("&"),
dataType: "json",
type: "POST",
url: window.base_url_homedir + "/ajax.php",
success: function(data) {
if (node_selected.type === "3") {
$("#node_details-0-0").html("<strong>Link to map</strong>");
if (node_selected.networkmap_id > 0) {
$("#node_details-0-1").html(
'<a href="index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=' +
node_selected["id_agent"] +
'<a href="index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=' +
node_selected.networkmap_id +
'">' +
data["alias"] +
$(
`#edit_networkmap_to_link option[value='${node_selected.networkmap_id}']`
).text() +
"</a>"
);
var addresses = "";
if (data["adressess"] instanceof Array) {
for (var i; i < data["adressess"].length; i++) {
addresses += data["adressess"][i] + "<br>";
}
} else {
for (var address in data["adressess"]) {
addresses += address + "<br>";
}
}
$("#node_details-1-1").html(addresses);
$("#node_details-2-1").html(data["os"]);
$("#node_details-3-1").html(data["group"]);
$("[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"
});
get_interface_data_to_table(node_selected, selected_links);
} else {
$("#node_details-0-1").html(
$(
`#edit_networkmap_to_link option[value='${node_selected.networkmap_id}']`
).text()
);
}
});
$("#node_details-1").hide();
$("#node_details-2").hide();
$("#node_details-3").hide();
} else {
$("#node_details-0-0").html("<strong>Agent</strong>");
$("#node_details-1").show();
$("#node_details-2").show();
$("#node_details-3").show();
var params = [];
params.push("get_agent_info=1");
params.push("id_agent=" + node_selected["id_agent"]);
params.push("page=operation/agentes/pandora_networkmap.view");
jQuery.ajax({
data: params.join("&"),
dataType: "json",
type: "POST",
url: window.base_url_homedir + "/ajax.php",
success: function(data) {
$("#node_details-0-1").html(
'<a href="index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=' +
node_selected["id_agent"] +
'">' +
data["alias"] +
"</a>"
);
var addresses = "";
if (data["adressess"] instanceof Array) {
for (var i; i < data["adressess"].length; i++) {
addresses += data["adressess"][i] + "<br>";
}
} else {
for (var address in data["adressess"]) {
addresses += address + "<br>";
}
}
$("#node_details-1-1").html(addresses);
$("#node_details-2-1").html(data["os"]);
$("#node_details-3-1").html(data["group"]);
$("[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"
});
get_interface_data_to_table(node_selected, selected_links);
}
});
}
$("#dialog_node_edit").dialog(
"option",
@ -887,6 +916,7 @@ function edit_node(data_node, dblClick) {
$("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);
$("#edit_networkmap_to_link").trigger("change");
$("#node_options-fictional_node_update_button").css("display", "");
$("#node_options-node_name").css("display", "none");
$("#node_options-node_update_button").css("display", "none");
@ -957,6 +987,7 @@ function get_interface_data_to_table(node_selected, selected_links) {
function load_interfaces(selected_links) {
//Clean
$("#relations_table .relation_link_row").remove();
$("#update_relations_button").remove();
//Show the no relations
$("#relations_table-loading").css("display", "none");
$("#relations_table-no_relations").css("display", "");
@ -969,6 +1000,7 @@ function load_interfaces(selected_links) {
$(template_relation_row).css("display", "");
$(template_relation_row).attr("class", "relation_link_row");
$(template_relation_row).attr("id", `relations_table-template_row_${i}`);
$("select[name='interface_source']", template_relation_row)
.attr("name", "interface_source_" + i)
@ -989,11 +1021,6 @@ function load_interfaces(selected_links) {
"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");
@ -1093,6 +1120,17 @@ function load_interfaces(selected_links) {
"align",
"center"
);
$("#relations_table-template_row-edit", template_relation_row).css({
display: "flex",
"align-items": "center",
"justify-content": "center"
});
$(
"#relations_table-template_row-edit .delete_icon",
template_relation_row
).attr("id", `delete_icon_${i}`);
$(
"#relations_table-template_row-edit .delete_icon",
template_relation_row
@ -1109,6 +1147,8 @@ function load_interfaces(selected_links) {
link_each.id_module_end +
"," +
link_each.id_db +
"," +
i +
");"
);
$("#relations_table tbody").append(template_relation_row);
@ -1119,6 +1159,42 @@ function load_interfaces(selected_links) {
template_relation_row = null;
});
if (selected_links.length > 0) {
$("#relations_table")
.parent()
.append(
`<div class='action-buttons w100p'>
<input id='update_relations_button' class='sub upd' type='button' value='update relations'>
</div>`
);
$("#update_relations_button").click(function() {
jQuery.each(selected_links, function(i, link_each) {
const new_id_db = update_link(i, link_each.id_db);
if (new_id_db !== false) {
selected_links[i]["id_db"] = new_id_db;
$(`#delete_icon_${i}`).attr(
"href",
"javascript: " +
"delete_link(" +
link_each.source.id_db +
"," +
link_each.id_module_start +
"," +
link_each.target.id_db +
"," +
link_each.id_module_end +
"," +
new_id_db +
"," +
i +
");"
);
}
});
});
}
}
function add_node() {
@ -1303,11 +1379,6 @@ function function_close_minimap() {
function delete_nodes() {
var selection = d3.selectAll(".node_selected");
selection.each(function(d) {
//Avoid to delete pandora node center
if (d.id_agent == 0) {
return;
}
var params = [];
params.push("id=" + d.id_db);
params.push("delete_node=1");
@ -1973,17 +2044,14 @@ function show_menu(item, data) {
};
}
// Avoid deletion if Pandora FMS node.
if (data.type != 2) {
items_list["delete"] = {
name: delete_menu,
icon: "delete",
disabled: false,
callback: function(key, options) {
delete_nodes();
}
};
}
items_list["delete"] = {
name: delete_menu,
icon: "delete",
disabled: false,
callback: function(key, options) {
delete_nodes();
}
};
$.contextMenu("destroy");
$.contextMenu({
@ -2030,15 +2098,7 @@ function show_menu(item, data) {
icon: "refresh",
disabled: false,
callback: function(key, options) {
update_networkmap();
}
};
items_list["refresh_holding_area"] = {
name: refresh_holding_area_menu,
icon: "refresh_holding_area",
disabled: false,
callback: function(key, options) {
refresh_holding_area();
refresh();
}
};
items_list["restart_map"] = {
@ -2398,6 +2458,99 @@ function refresh_holding_area() {
});
}
function refresh() {
$("#spinner_networkmap").css("display", "flex");
var holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x");
var 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);
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=operation/agentes/pandora_networkmap.view");
$.ajax({
data: {
page: "operation/agentes/pandora_networkmap.view",
refresh_holding_area: 1,
id: networkmap_id,
x: pos_x,
y: pos_y
},
dataType: "json",
type: "POST",
url: window.base_url_homedir + "/ajax.php",
success: function(data) {
if (data["correct"]) {
const array_nodes = data["holding_area"]["nodes"];
let array_links = data["holding_area"]["links"];
jQuery.each(graph.links, function(j, g_link) {
for (var i = 0; i < array_links.length; i++) {
if (g_link["id_db"] == array_links[i]["id_db"]) {
array_links.splice(i, 1);
}
}
});
let location = "";
if ($("#main").height()) {
location = `index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=${networkmap_id}`;
} else {
location = `index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&pure=1&id_networkmap=${networkmap_id}`;
}
if (array_nodes.length === 0 && array_links.length === 0) {
update_networkmap();
$("#spinner_networkmap").css("display", "none");
startCountDown(refresh_time);
} else {
if (array_nodes.length > 0) {
$.ajax({
data: {
page: "operation/agentes/pandora_networkmap.view",
refresh_map: 1,
id: networkmap_id
},
dataType: "json",
type: "POST",
url: window.base_url_homedir + "/ajax.php",
success: function(data) {
$("#spinner_networkmap").css("display", "none");
window.location = location;
}
});
} else if (array_links.length > 0) {
$("#spinner_networkmap").css("display", "none");
window.location = location;
}
}
}
},
error: function(e) {
$("#spinner_networkmap").css("display", "none");
}
});
}
function startCountDown(duration) {
$("div.vc-countdown").countdown("destroy");
if (!duration) return;
var t = new Date();
t.setTime(t.getTime() + duration * 1000);
$("div.vc-countdown").countdown({
until: t,
format: "MS",
layout: "(%M%nn%M:%S%nn%S Until refreshed) ",
alwaysExpire: true,
onExpiry: function() {
refresh();
}
});
}
function restart_map() {
$(
"<div id='restart_map_confirm' class='dialog ui-dialog-content' title='" +
@ -2935,6 +3088,10 @@ function init_graph(parameter_object) {
window.url_background_grid = "";
}
if (typeof parameter_object.refresh_time != "undefined") {
window.refresh_time = parameter_object.refresh_time;
}
var rect_center_x = graph.nodes[0].x;
var rect_center_y = graph.nodes[0].y;
@ -3644,11 +3801,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -3685,11 +3838,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -3721,11 +3870,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -3767,11 +3912,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -3804,11 +3945,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);
@ -3850,11 +3987,7 @@ function draw_elements_graph() {
})
.on("click", selected_node)
.on("dblclick", function(d) {
if (d.type == 3) {
move_to_networkmap(d);
} else {
edit_node(d, true);
}
edit_node(d, true);
})
.on("contextmenu", function(d) {
show_menu("node", d);

View File

@ -466,9 +466,12 @@ function event_change_status(event_ids, server_id) {
}
if (data.status == "status_ok") {
if (typeof dt_events !== "undefined") {
dt_events.draw(false);
}
// if (typeof dt_events !== "undefined") {
// dt_events.draw(false);
// }
$("#table_events")
.DataTable()
.draw(false);
$("#notification_status_success").show();
if (new_status == 1) {
$("#extended_event_general_page table td.general_acknowleded").text(
@ -526,9 +529,12 @@ function event_change_owner(event_id, server_id) {
}
if (data == "owner_ok") {
if (typeof dt_events !== "undefined") {
dt_events.draw(false);
}
// if (typeof dt_events !== "undefined") {
// dt_events.draw(false);
// }
$("#table_events")
.DataTable()
.draw(false);
$("#notification_owner_success").show();
if (new_owner == -1) {
$("#extended_event_general_page table td.general_owner").html(

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -73,7 +73,7 @@ final class Config
$config['history_db_user'],
io_output_password($config['history_db_pass']),
$config['history_db_name'],
$config['history_db_port']
(int) $config['history_db_port']
);
if ($rc === false) {
@ -84,7 +84,7 @@ final class Config
$config['history_db_name'],
$config['history_db_user'],
io_output_password($config['history_db_pass']),
$config['history_db_port'],
(int) $config['history_db_port'],
false
);
}

View File

@ -135,9 +135,9 @@ final class DBMaintainer
$this->user = $params['user'];
$this->pass = io_output_password($params['pass']);
$this->host = $params['host'];
$this->port = $params['port'];
$this->port = (int) $params['port'];
$this->name = $params['name'];
$this->charset = $params['charset'];
$this->charset = (isset($params['charset']) === true) ? $params['charset'] : '';
// Try to connect.
$this->connect();
@ -170,7 +170,10 @@ final class DBMaintainer
if ($rc === false) {
$this->dbh = null;
$this->connected = false;
$this->lastError = __('Connection problems');
$this->lastError = __(
'Connection problems: %s',
mysqli_connect_error()
);
} else {
$dbc = new \mysqli(
$this->host,

View File

@ -387,17 +387,17 @@ class BlockHistogram extends Widget
$output = '';
if (is_metaconsole() === true) {
$modules_nodes = array_reduce(
$this->values['moduleBlockHistogram'],
function ($carry, $item) {
$explode = explode('|', $item);
$carry[$explode[0]][] = $explode[1];
return $carry;
},
[]
);
$modules_nodes = array_reduce(
$this->values['moduleBlockHistogram'],
function ($carry, $item) {
$explode = explode('|', $item);
$carry[$explode[0]][] = $explode[1];
return $carry;
},
[]
);
$modules = [];
$modules = [];
foreach ($modules_nodes as $n => $mod) {
try {
$node = new Node((int) $n);
@ -475,7 +475,8 @@ class BlockHistogram extends Widget
private function getInfoModules(array $modules): array
{
$where = sprintf(
'tagente_modulo.id_agente_modulo IN (%s)',
'tagente_modulo.id_agente_modulo IN (%s)
AND tagente_modulo.delete_pending = 0',
implode(',', $modules)
);

View File

@ -426,7 +426,8 @@ class ColorModuleTabs extends Widget
private function getInfoModules(array $modules): array
{
$where = sprintf(
'tagente_modulo.id_agente_modulo IN (%s)',
'tagente_modulo.id_agente_modulo IN (%s)
AND tagente_modulo.delete_pending = 0',
implode(',', $modules)
);

View File

@ -338,22 +338,6 @@ class AgentModuleWidget extends Widget
)
);
if (is_metaconsole() === true) {
$values['mModules'] = implode(
SEPARATOR_META_MODULE,
array_reduce(
$values['mModules'],
function ($carry, $item) {
$d = explode('|', $item);
$carry[] = (isset($d[1]) === true) ? $d[1] : $item;
return $carry;
},
[]
)
);
}
return $values;
}
@ -670,64 +654,34 @@ class AgentModuleWidget extends Widget
return $output;
}
// Extract info all modules selected.
$target_modules = $this->values['mModules'];
if (is_metaconsole() === true) {
$target_modules = explode(
SEPARATOR_META_MODULE,
$this->values['mModules']
);
$reduceAllModules = array_reduce(
$this->values['mModules'],
function ($carry, $item) {
if ($item === null) {
return $carry;
}
$all_modules = $target_modules;
} else {
if (is_array($target_modules) === true
|| is_numeric($target_modules) === true
) {
$target_modules = array_reduce(
$target_modules,
function ($carry, $item) {
$carry[] = io_safe_output($item);
return $carry;
if (is_metaconsole() === true) {
$item = explode('|', $item);
$serverId = $item[0];
$fullname = $item[1];
if ($this->values['mShowCommonModules'] !== 'on') {
$item = explode('&#x20;&raquo;&#x20;', $fullname);
$name = $item[1];
$carry['modules_selected'][$serverId][$name] = null;
$carry['modules'][$name] = null;
} else {
$carry['modules'][$fullname] = null;
}
);
} else {
$carry['modules'][$item] = null;
}
$all_modules = Module::search(
['nombre' => $target_modules]
);
} else {
// From previous definitions.
$all_modules = Module::search(
['id_agente_modulo' => explode(',', $target_modules)]
);
return $carry;
}
}
if ($all_modules !== null) {
if (is_metaconsole() === true
&& $this->values['mShowCommonModules'] === '1'
) {
$reduceAllModules = [];
} else {
$reduceAllModules = array_reduce(
$all_modules,
function ($carry, $item) {
if ($item === null) {
return $carry;
}
if (is_object($item) === true) {
$carry[$item->name()] = null;
} else {
$carry[io_safe_output($item)] = null;
}
return $carry;
}
);
}
}
);
$allModules = $reduceAllModules['modules'];
$visualData = [];
// Extract info agents selected.
$target_agents = explode(',', $this->values['mAgents']);
@ -754,54 +708,33 @@ class AgentModuleWidget extends Widget
$visualData[$agent_id]['agent_alias'] = $agent->alias();
$visualData[$agent_id]['modules'] = [];
if (is_metaconsole() === true
&& $this->values['mShowCommonModules'] === '1'
) {
// MC should connect to nodes and retrieve information
// from targets.
$tmpModules = array_reduce(
$target_modules,
function ($carry, $item) {
// In this case, the modules come with '» ' chain.
$tmpCarry = explode('&raquo;&#x20;', $item);
$carry[trim($tmpCarry[1])] = null;
return $carry;
}
);
$modules = $agent->searchModules(
['nombre' => array_keys($tmpModules)]
);
foreach ($modules as $module) {
if ($module === null) {
$reduceAllModules[] = null;
} else {
$reduceAllModules[$module->name()] = null;
}
}
} else {
if (empty($reduceAllModules) === false) {
if (empty($allModules) === false) {
if (is_metaconsole() === true && $this->values['mShowCommonModules'] !== 'on') {
$modules = $agent->searchModules(
['nombre' => array_keys($reduceAllModules)]
['nombre' => array_keys($reduceAllModules['modules_selected'][$tserver])]
);
} else {
$modules = $agent->searchModules(
['nombre' => array_keys($allModules)]
);
}
}
$visualData[$agent_id]['modules'] = $reduceAllModules;
$visualData[$agent_id]['modules'] = $allModules;
foreach ($modules as $module) {
if ($module === null) {
continue;
}
$key_name_module = $module->name();
if ($this->values['mTypeShow'] === '1') {
$mod = $module->toArray();
$mod['datos'] = $module->lastValue();
$module_last_value = modules_get_agentmodule_data_for_humans($mod);
$visualData[$agent_id]['modules'][$module->name()] = $module_last_value;
$visualData[$agent_id]['modules'][$key_name_module] = $module_last_value;
} else {
$visualData[$agent_id]['modules'][$module->name()] = $module->getStatus()->estado();
$visualData[$agent_id]['modules'][$key_name_module] = $module->getStatus()->estado();
}
}
@ -813,17 +746,9 @@ class AgentModuleWidget extends Widget
}
}
if (empty($reduceAllModules) === false) {
$allModules = array_keys($reduceAllModules);
}
if ($allModules === null) {
$allModules = [];
}
$output = $this->generateViewAgentModule(
$visualData,
$allModules
array_keys($allModules)
);
return $output;

View File

@ -170,6 +170,17 @@ class AlertsFiredWidget extends Widget
$this->configurationRequired = false;
if (isset($this->values['groupId']) === false) {
$this->configurationRequired = true;
} else {
$check_exist = \db_get_value(
'id_grupo',
'tgrupo',
'id_grupo',
$this->values['groupId']
);
if ($check_exist === false) {
$this->loadError = true;
}
}
$this->overflow_scrollbars = false;

View File

@ -28,6 +28,8 @@
namespace PandoraFMS\Dashboard;
use PandoraFMS\Enterprise\Metaconsole\Node;
/**
* Custom graph Widgets
*/
@ -178,6 +180,41 @@ class CustomGraphWidget extends Widget
$this->configurationRequired = false;
if (empty($this->values['id_graph']) === true) {
$this->configurationRequired = true;
} else {
try {
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node = new Node($this->values['node']);
$node->connect();
}
$check_exist = \db_get_value(
'name',
'tgraph',
'id_graph',
$this->values['id_graph']
);
} catch (\Exception $e) {
// Unexistent agent.
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node->disconnect();
}
$check_exist = false;
} finally {
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node->disconnect();
}
}
if ($check_exist === false) {
$this->loadError = true;
}
}
}

View File

@ -553,6 +553,18 @@ class EventsListWidget extends Widget
);
$filter['module_search'] = $name[0]['nombre'];
}
} else if (empty($this->values['customFilter']) === false
&& (int) $this->values['customFilter'] !== -1
) {
$output = '<div class="container-center">';
$output .= \ui_print_error_message(
__('Widget cannot be loaded').'. '.__('Please, event filter has been removed.'),
'',
true
);
$output .= '</div>';
echo $output;
return;
} else {
// Filtering.
$filter['event_view_hr'] = $this->values['maxHours'];

View File

@ -28,6 +28,8 @@
namespace PandoraFMS\Dashboard;
use PandoraFMS\Enterprise\Metaconsole\Node;
global $config;
/**
@ -183,6 +185,44 @@ class GraphModuleHistogramWidget extends Widget
$this->configurationRequired = false;
if (empty($this->values['moduleId']) === true) {
$this->configurationRequired = true;
} else {
try {
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node = new Node($this->values['metaconsoleId']);
$node->connect();
}
$check_exist = db_get_sql(
sprintf(
'SELECT id_agente_modulo
FROM tagente_modulo
WHERE id_agente_modulo = %s
AND delete_pending = 0',
$this->values['moduleId']
)
);
} catch (\Exception $e) {
// Unexistent agent.
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node->disconnect();
}
$check_exist = false;
} finally {
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node->disconnect();
}
}
if ($check_exist === false) {
$this->loadError = true;
}
}
$this->overflow_scrollbars = false;
@ -304,7 +344,6 @@ class GraphModuleHistogramWidget extends Widget
'label' => __('Module'),
'arguments' => [
'type' => 'autocomplete_module',
'fields' => $fields,
'name' => 'moduleId',
'selected' => $values['moduleId'],
'return' => true,
@ -312,7 +351,9 @@ class GraphModuleHistogramWidget extends Widget
'agent_id' => $values['agentId'],
'metaconsole_id' => $values['metaconsoleId'],
'style' => 'width: inherit;',
'filter_modules' => users_access_to_agent($values['agentId']) === false ? [$values['moduleId']] : [],
'filter_modules' => (users_access_to_agent($values['agentId']) === false) ? [$values['moduleId']] : [],
'nothing' => __('None'),
'nothing_value' => 0,
],
];

View File

@ -166,6 +166,17 @@ class GroupsStatusWidget extends Widget
$this->configurationRequired = false;
if (empty($this->values['groupId']) === true) {
$this->configurationRequired = true;
} else {
$check_exist = \db_get_value(
'id_grupo',
'tgrupo',
'id_grupo',
$this->values['groupId']
);
if ($check_exist === false) {
$this->loadError = true;
}
}
$this->overflow_scrollbars = false;
@ -520,7 +531,7 @@ class GroupsStatusWidget extends Widget
{
$size = [
'width' => 400,
'height' => 270,
'height' => 330,
];
return $size;

View File

@ -29,6 +29,7 @@
namespace PandoraFMS\Dashboard;
// Load Visual Console.
use Models\VisualConsole\Container as VisualConsole;
use PandoraFMS\Enterprise\Metaconsole\Node;
use PandoraFMS\User;
/**
* Maps by users Widgets.
@ -183,12 +184,36 @@ class MapsMadeByUser extends Widget
if (empty($this->values['vcId']) === true) {
$this->configurationRequired = true;
} else {
$check_exist = db_get_value(
'id',
'tlayout',
'id',
$this->values['vcId']
);
try {
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node = new Node($this->values['node']);
$node->connect();
}
$check_exist = db_get_value(
'id',
'tlayout',
'id',
$this->values['vcId']
);
} catch (\Exception $e) {
// Unexistent agent.
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node->disconnect();
}
$check_exist = false;
} finally {
if (is_metaconsole() === true
&& $this->values['node'] > 0
) {
$node->disconnect();
}
}
if ($check_exist === false) {
$this->loadError = true;
@ -334,12 +359,14 @@ class MapsMadeByUser extends Widget
$inputs[] = [
'label' => __('Visual console'),
'arguments' => [
'id' => 'vcId',
'type' => 'select',
'fields' => $fields,
'name' => 'vcId',
'selected' => $values['vcId'],
'return' => true,
'id' => 'vcId',
'type' => 'select',
'fields' => $fields,
'name' => 'vcId',
'selected' => $values['vcId'],
'return' => true,
'nothing' => __('None'),
'nothing_value' => 0,
],
];

View File

@ -320,6 +320,17 @@ class MapsStatusWidget extends Widget
$output = '';
if (isset($maps) === true && empty($maps) === false) {
foreach ($maps as $id_layout) {
$check_exist = db_get_value(
'id',
'tlayout',
'id',
$id_layout
);
if ($check_exist === false) {
continue;
}
$data = [];
$url = $config['homeurl'];
@ -366,12 +377,22 @@ class MapsStatusWidget extends Widget
array_push($table->data, $data);
}
// 31 px for each map.
$minHeight = (count($maps) * 31);
$style = 'min-width:200px; min-height:'.$minHeight.'px';
$output = '<div class="container-center" style="'.$style.'">';
$output .= html_print_table($table, true);
$output .= '</div>';
if (empty($table->data) === false) {
// 31 px for each map.
$minHeight = (count($maps) * 31);
$style = 'min-width:200px; min-height:'.$minHeight.'px';
$output = '<div class="container-center" style="'.$style.'">';
$output .= html_print_table($table, true);
$output .= '</div>';
} else {
$output .= '<div class="container-center">';
$output .= \ui_print_error_message(
__('Widget cannot be loaded').'. '.__('Please, configure the widget again to recover it'),
'',
true
);
$output .= '</div>';
}
}
return $output;

View File

@ -28,6 +28,7 @@
namespace PandoraFMS\Dashboard;
use PandoraFMS\Dashboard;
use PandoraFMS\Enterprise\Metaconsole\Node;
global $config;
@ -186,6 +187,44 @@ class ModuleIconWidget extends Widget
$this->configurationRequired = false;
if (empty($this->values['moduleId']) === true) {
$this->configurationRequired = true;
} else {
try {
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node = new Node($this->values['metaconsoleId']);
$node->connect();
}
$check_exist = db_get_sql(
sprintf(
'SELECT id_agente_modulo
FROM tagente_modulo
WHERE id_agente_modulo = %s
AND delete_pending = 0',
$this->values['moduleId']
)
);
} catch (\Exception $e) {
// Unexistent agent.
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node->disconnect();
}
$check_exist = false;
} finally {
if (is_metaconsole() === true
&& $this->values['metaconsoleId'] > 0
) {
$node->disconnect();
}
}
if ($check_exist === false) {
$this->loadError = true;
}
}
$this->overflow_scrollbars = false;
@ -334,7 +373,6 @@ class ModuleIconWidget extends Widget
'label' => __('Module'),
'arguments' => [
'type' => 'autocomplete_module',
'fields' => $fields,
'name' => 'moduleId',
'selected' => $values['moduleId'],
'return' => true,
@ -343,6 +381,8 @@ class ModuleIconWidget extends Widget
'metaconsole_id' => $values['metaconsoleId'],
'style' => 'width: inherit;',
'filter_modules' => users_access_to_agent($values['agentId']) === false ? [$values['moduleId']] : [],
'nothing' => __('None'),
'nothing_value' => 0,
],
];

Some files were not shown because too many files have changed in this diff Show More