diff --git a/extras/chrome_extension/js/popup.js b/extras/chrome_extension/js/popup.js index 44e0725a73..e323a9b12b 100644 --- a/extras/chrome_extension/js/popup.js +++ b/extras/chrome_extension/js/popup.js @@ -1,170 +1,183 @@ var max_events; var bg; -$(document).ready(function(){ - max_events=localStorage["events"]; - if(localStorage["events"]==undefined){ - localStorage["events"]="20"; - } - bg=chrome.extension.getBackgroundPage(); +$(document).ready(function() { + max_events = localStorage["events"]; + if (localStorage["events"] == undefined) { + localStorage["events"] = "20"; + } + bg = chrome.extension.getBackgroundPage(); - // Display the information - if (bg.fetchEvents().length == 0) { - showError("Error in fetching data!! Check your internet connection"); - } else { - showEvents(); - } + // Display the information + if (bg.fetchEvents().length == 0) { + showError("No events"); + } else { + showEvents(); + } - // Adding buttons listeners - document.getElementById("m_refresh").addEventListener("click", mrefresh); + // Adding buttons listeners + document.getElementById("m_refresh").addEventListener("click", mrefresh); - // Added listener to background messages - chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ - switch (message.text) { - case "FETCH_EVENTS": - setSpinner(); - //$('div.b').hide(); - break; - case "FETCH_EVENTS_SUCCESS": - unsetSpinner(); - showEvents(); - break; - case "FETCH_EVENTS_DATA_ERROR": - unsetSpinner(); - showError("Error in fetching data!! Check your internet connection"); - break; - case "FETCH_EVENTS_URL_ERROR": - unsetSpinner(); - showError("Configure ip address,API password, user name and password with correct values"); - break; - default: - console.log("Unrecognized message: ", message.text); - break; - } - }); + // Added listener to background messages + chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { + switch (message.text) { + case "FETCH_EVENTS": + setSpinner(); + //$('div.b').hide(); + break; + case "FETCH_EVENTS_SUCCESS": + unsetSpinner(); + showEvents(); + break; + case "FETCH_EVENTS_DATA_ERROR": + unsetSpinner(); + showError("Error in fetching data!! Check your internet connection"); + break; + case "FETCH_EVENTS_URL_ERROR": + unsetSpinner(); + showError( + "Configure ip address,API password, user name and password with correct values" + ); + break; + default: + console.log("Unrecognized message: ", message.text); + break; + } + }); }); -function setSpinner () { - $('#refr_img_id').attr("src", "images/spinny.gif"); +function setSpinner() { + $("#refr_img_id").attr("src", "images/spinny.gif"); } function unsetSpinner() { - $('#refr_img_id').attr("src", "images/refresh.png"); + $("#refr_img_id").attr("src", "images/refresh.png"); } function clearError() { - $('.error').hide(); - $('.error a').text(""); - $('.result').css('height', null); + $(".error").hide(); + $(".error a").text(""); + $(".result").css("height", null); } -function showError(text){ - $('.error a').text(text); - $('.error').show(); - $('.result').height(420); +function showError(text) { + $(".error a").text(text); + $(".error").show(); + $(".result").height(420); } -function showEvents(){ +function showEvents() { + clearError(); + $("#events").empty(); + var e_refr = document.getElementById("event_temp"); + if (e_refr) { + wrapper.removeChild(e_refr); + } + var allEvents = bg.fetchEvents(); + var notVisitedEvents = bg.fetchNotVisited(); + var eve = document.createElement("div"); + eve.id = "event_temp"; + eve.setAttribute("class", "b"); - clearError(); - $('#events').empty(); - var e_refr = document.getElementById('event_temp'); - if(e_refr){ - wrapper.removeChild(e_refr); - } - var allEvents = bg.fetchEvents(); - var notVisitedEvents = bg.fetchNotVisited(); - var eve=document.createElement('div'); - eve.id="event_temp"; - eve.setAttribute("class","b"); - - var i=0; - if(allEvents.length>0){ - while(i 0) { + while (i < max_events && i < allEvents.length) { + var eve_title = document.createElement("div"); + eve_title.id = "e_" + i + "_" + allEvents[i]["id"]; + var img = document.createElement("img"); + img.src = "images/plus.png"; + img.className = "pm"; + img.id = "i_" + i + "_" + allEvents[i]["id"]; + eve_title.appendChild(img); + var div_empty = document.createElement("img"); + var a = document.createElement("a"); + var temp_style; - if (notVisitedEvents[allEvents[i]['id']] === true) { - eve_title.style.fontWeight = 600; - } - - eve_title.appendChild(a); - eve.appendChild(eve_title); - - var time=allEvents[i]['date'].split(" "); - var time_text = time[0]+" "+time[1]; - - var p = document.createElement('p'); - var id = (allEvents[i]['module']==0) - ? "." - : " in the module with Id "+ allEvents[i]['module'] + "."; - - p.innerText = allEvents[i]['type']+" : "+allEvents[i]['source']+". Event occured at "+ time_text+id; - p.id = 'p_' + i; - eve_title.appendChild(p); - i++; - } - - $('#events').append(eve); + var agent_url = + allEvents[i]["agent"] == 0 + ? localStorage["ip_address"] + + "/index.php?sec=eventos&sec2=operation/events/events" + : localStorage["ip_address"] + + "/index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=" + + allEvents[i]["agent"]; + a.setAttribute("href", agent_url); + a.target = "_blank"; + a.className = "a_2_mo"; - $('img.pm').click(showHide); - $('div.b').show(); - } else { - showError("Error in fetching data!! Check your internet connection"); - } - - localStorage["new_events"]=0; - bg.updateBadge(); + a.innerText = allEvents[i]["title"]; + eve_title.setAttribute("class", "event sev-" + allEvents[i]["severity"]); + + if (notVisitedEvents[allEvents[i]["id"]] === true) { + eve_title.style.fontWeight = 600; + } + + eve_title.appendChild(a); + eve.appendChild(eve_title); + + var time = allEvents[i]["date"].split(" "); + var time_text = time[0] + " " + time[1]; + + var p = document.createElement("p"); + var id = + allEvents[i]["module"] == 0 + ? "." + : " in the module with Id " + allEvents[i]["module"] + "."; + + p.innerText = + allEvents[i]["type"] + + " : " + + allEvents[i]["source"] + + ". Event occured at " + + time_text + + id; + p.id = "p_" + i; + eve_title.appendChild(p); + i++; + } + + $("#events").append(eve); + + $("img.pm").click(showHide); + $("div.b").show(); + } else { + showError("No events"); + } + + localStorage["new_events"] = 0; + bg.updateBadge(); } function showHide() { - var id = $(this).attr('id'); - // Image id has the form i__ - var nums = id.split('_'); - var pid = "p_" + nums[1]; + var id = $(this).attr("id"); + // Image id has the form i__ + var nums = id.split("_"); + var pid = "p_" + nums[1]; - // Mark as visited if visited - if($(this).parent().css('font-weight') == '600') { - bg.removeNotVisited(nums[2]); - $(this).parent().css('font-weight', ''); - } + // Mark as visited if visited + if ( + $(this) + .parent() + .css("font-weight") == "600" + ) { + bg.removeNotVisited(nums[2]); + $(this) + .parent() + .css("font-weight", ""); + } - // Toggle information - if($('#' + pid).css('display') == 'none') { - $('#' + pid).slideDown(); - $(this).attr({src: 'images/minus.png'}); - } - else { - $('#' + pid).slideUp(); - $(this).attr({src: 'images/plus.png'}); - } + // Toggle information + if ($("#" + pid).css("display") == "none") { + $("#" + pid).slideDown(); + $(this).attr({ src: "images/minus.png" }); + } else { + $("#" + pid).slideUp(); + $(this).attr({ src: "images/plus.png" }); + } } -function mrefresh(){ - localStorage["new_events"]=0; - bg.updateBadge(); - clearError(); - bg.resetInterval(); - bg.main(); +function mrefresh() { + localStorage["new_events"] = 0; + bg.updateBadge(); + clearError(); + bg.resetInterval(); + bg.main(); } diff --git a/extras/chrome_extension/manifest.json b/extras/chrome_extension/manifest.json index b591121309..bff5586f0c 100644 --- a/extras/chrome_extension/manifest.json +++ b/extras/chrome_extension/manifest.json @@ -1,30 +1,30 @@ { - "name": "__MSG_name__", - "version": "2.1", - "manifest_version": 2, - "description": "Pandora FMS Event viewer Chrome extension", - "homepage_url": "http://pandorafms.com", - "browser_action": { - "default_title": "__MSG_default_title__", - "default_icon": "images/icon.png", - "default_popup": "popup.html" - }, - "background": { - "page": "background.html" - }, - "icons": { - "128": "images/icon128.png", - "16": "images/icon16.png", - "32": "images/icon32.png", - "48": "images/icon48.png" - }, - "options_page": "options.html", - "permissions": [ - "tabs", - "notifications", - "http://*/*", - "https://*/*", - "background" - ], - "default_locale": "en" - } + "name": "__MSG_name__", + "version": "2.2", + "manifest_version": 2, + "description": "Pandora FMS Event viewer Chrome extension", + "homepage_url": "http://pandorafms.com", + "browser_action": { + "default_title": "__MSG_default_title__", + "default_icon": "images/icon.png", + "default_popup": "popup.html" + }, + "background": { + "page": "background.html" + }, + "icons": { + "128": "images/icon128.png", + "16": "images/icon16.png", + "32": "images/icon32.png", + "48": "images/icon48.png" + }, + "options_page": "options.html", + "permissions": [ + "tabs", + "notifications", + "http://*/*", + "https://*/*", + "background" + ], + "default_locale": "en" +} diff --git a/pandora_agents/Dockerfile b/pandora_agents/Dockerfile new file mode 100644 index 0000000000..945a74b1c9 --- /dev/null +++ b/pandora_agents/Dockerfile @@ -0,0 +1,50 @@ +FROM centos:centos7 +MAINTAINER Pandora FMS Team + +# Add Pandora FMS agent installer +ADD unix /tmp/pandora_agent/unix + +# Install dependencies +RUN yum -y install \ + epel-release \ + unzip \ + perl \ + sed \ + "perl(Sys::Syslog)" + +# Install Pandora FMS agent +RUN cd /tmp/pandora_agent/unix \ + && chmod +x pandora_agent_installer \ + && ./pandora_agent_installer --install + +# Set default variables +ENV SERVER_IP '127.0.0.1' +ENV REMOTE_CONFIG '0' +ENV GROUP 'Servers' +ENV DEBUG '0' +ENV AGENT_NAME 'agent_docker' +ENV AGENT_ALIAS 'agent_docker' +ENV TIMEZONE 'UTC' +ENV SECONDARY_GROUPS '' + +# Create the entrypoint script. +RUN echo -e '#/bin/bash\n \ +sed -i "s/^server_ip.*$/server_ip $SERVER_IP/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^remote_config.*$/remote_config $REMOTE_CONFIG/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^group.*$/group $GROUP/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^debug.*$/debug $DEBUG/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^#agent_name.*$/agent_name $AGENT_NAME/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^#agent_alias.*$/agent_alias $AGENT_ALIAS/g" /etc/pandora/pandora_agent.conf\n \ +sed -i "s/^# secondary_groups.*$/secondary_groups $SECONDARY_GROUPS/g" /etc/pandora/pandora_agent.conf\n \ +if [ $TIMEZONE != "" ]; then\n \ +\tln -sfn /usr/share/zoneinfo/$TIMEZONE /etc/localtime\n \ +fi\n \ +/etc/init.d/pandora_agent_daemon start\n \ +rm -f $0\n \ +tail -f /var/log/pandora/pandora_agent.log' \ +>> /entrypoint.sh && \ +chmod +x /entrypoint.sh + +# Entrypoint + CMD +ENTRYPOINT ["bash"] +CMD ["/entrypoint.sh"] \ No newline at end of file diff --git a/pandora_agents/build_agent_docker.sh b/pandora_agents/build_agent_docker.sh new file mode 100644 index 0000000000..0ebf8ac7a0 --- /dev/null +++ b/pandora_agents/build_agent_docker.sh @@ -0,0 +1,18 @@ +#!/bin/bash +source /root/code/pandorafms/extras/build_vars.sh + +# Set tag for docker build +if [ "$1" == "nightly" ]; then + LOCAL_VERSION="latest" +else + LOCAL_VERSION=$VERSION +fi + +# Build image with code +docker build --rm=true --pull --no-cache -t pandorafms/pandorafms-agent:$LOCAL_VERSION -f $CODEHOME/pandora_agents/Dockerfile $CODEHOME/pandora_agents/ + +# Push image +docker push pandorafms/pandorafms-agent:$LOCAL_VERSION + +# Delete local image +docker image rm -f pandorafms/pandorafms-agent:$LOCAL_VERSION \ No newline at end of file diff --git a/pandora_agents/pc/AIX/pandora_agent.conf b/pandora_agents/pc/AIX/pandora_agent.conf index 0ff67a62d3..fbea6eb404 100644 --- a/pandora_agents/pc/AIX/pandora_agent.conf +++ b/pandora_agents/pc/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, AIX version +# Version 7.0NG.738, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/FreeBSD/pandora_agent.conf b/pandora_agents/pc/FreeBSD/pandora_agent.conf index c7c6fdd493..ded3ec4b9c 100644 --- a/pandora_agents/pc/FreeBSD/pandora_agent.conf +++ b/pandora_agents/pc/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, FreeBSD Version +# Version 7.0NG.738, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/HP-UX/pandora_agent.conf b/pandora_agents/pc/HP-UX/pandora_agent.conf index 1a349583dc..0d3e20d05e 100644 --- a/pandora_agents/pc/HP-UX/pandora_agent.conf +++ b/pandora_agents/pc/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, HP-UX Version +# Version 7.0NG.738, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Linux/pandora_agent.conf b/pandora_agents/pc/Linux/pandora_agent.conf index dc172b7e2f..5d951d984d 100644 --- a/pandora_agents/pc/Linux/pandora_agent.conf +++ b/pandora_agents/pc/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, GNU/Linux +# Version 7.0NG.738, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/NT4/pandora_agent.conf b/pandora_agents/pc/NT4/pandora_agent.conf index 3d76832397..1c73d12fc9 100644 --- a/pandora_agents/pc/NT4/pandora_agent.conf +++ b/pandora_agents/pc/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, GNU/Linux +# Version 7.0NG.738, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/SunOS/pandora_agent.conf b/pandora_agents/pc/SunOS/pandora_agent.conf index 9b088eae51..fc59e308e4 100644 --- a/pandora_agents/pc/SunOS/pandora_agent.conf +++ b/pandora_agents/pc/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, Solaris Version +# Version 7.0NG.738, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Win32/pandora_agent.conf b/pandora_agents/pc/Win32/pandora_agent.conf index e2c442a520..f12cb5089c 100644 --- a/pandora_agents/pc/Win32/pandora_agent.conf +++ b/pandora_agents/pc/Win32/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2010 Artica Soluciones Tecnologicas -# Version 7.0NG.735 +# Version 7.0NG.738 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/shellscript/aix/pandora_agent.conf b/pandora_agents/shellscript/aix/pandora_agent.conf index fea0cb56db..863ab92907 100644 --- a/pandora_agents/shellscript/aix/pandora_agent.conf +++ b/pandora_agents/shellscript/aix/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.735, AIX version +# Version 7.0NG.738, AIX version # General Parameters # ================== diff --git a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf index f0ce5b2519..f56402fbcc 100644 --- a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf +++ b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.735 +# Version 7.0NG.738 # FreeBSD/IPSO version # Licenced under GPL licence, 2003-2007 Sancho Lerena diff --git a/pandora_agents/shellscript/hp-ux/pandora_agent.conf b/pandora_agents/shellscript/hp-ux/pandora_agent.conf index 20cdfeff99..55576e58fd 100644 --- a/pandora_agents/shellscript/hp-ux/pandora_agent.conf +++ b/pandora_agents/shellscript/hp-ux/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.735, HPUX Version +# Version 7.0NG.738, HPUX Version # General Parameters # ================== diff --git a/pandora_agents/shellscript/linux/pandora_agent.conf b/pandora_agents/shellscript/linux/pandora_agent.conf index e8ba9653ce..a584a597cb 100644 --- a/pandora_agents/shellscript/linux/pandora_agent.conf +++ b/pandora_agents/shellscript/linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735 +# Version 7.0NG.738 # Licensed under GPL license v2, # (c) 2003-2010 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/mac_osx/pandora_agent.conf b/pandora_agents/shellscript/mac_osx/pandora_agent.conf index 29d13ff75c..18db7a174f 100644 --- a/pandora_agents/shellscript/mac_osx/pandora_agent.conf +++ b/pandora_agents/shellscript/mac_osx/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735 +# Version 7.0NG.738 # Licensed under GPL license v2, # (c) 2003-2009 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/openWRT/pandora_agent.conf b/pandora_agents/shellscript/openWRT/pandora_agent.conf index 8ef8a6fdc1..d3266f091d 100644 --- a/pandora_agents/shellscript/openWRT/pandora_agent.conf +++ b/pandora_agents/shellscript/openWRT/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735 +# Version 7.0NG.738 # Licensed under GPL license v2, # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/solaris/pandora_agent.conf b/pandora_agents/shellscript/solaris/pandora_agent.conf index 1ace947818..aa59a262c4 100644 --- a/pandora_agents/shellscript/solaris/pandora_agent.conf +++ b/pandora_agents/shellscript/solaris/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.735, Solaris version +# Version 7.0NG.738, Solaris version # General Parameters # ================== diff --git a/pandora_agents/unix/AIX/pandora_agent.conf b/pandora_agents/unix/AIX/pandora_agent.conf index c67f64d16c..dedf2c366f 100644 --- a/pandora_agents/unix/AIX/pandora_agent.conf +++ b/pandora_agents/unix/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, AIX version +# Version 7.0NG.738, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 84194913b7..79ec8e1e38 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.735-190605 +Version: 7.0NG.738-190906 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index c5aa33342d..a1152c73bb 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.735-190605" +pandora_version="7.0NG.738-190906" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/Darwin/pandora_agent.conf b/pandora_agents/unix/Darwin/pandora_agent.conf index d7ee481255..4624a5ceff 100644 --- a/pandora_agents/unix/Darwin/pandora_agent.conf +++ b/pandora_agents/unix/Darwin/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, GNU/Linux +# Version 7.0NG.738, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2012 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/FreeBSD/pandora_agent.conf b/pandora_agents/unix/FreeBSD/pandora_agent.conf index b02b379470..0895974d7b 100644 --- a/pandora_agents/unix/FreeBSD/pandora_agent.conf +++ b/pandora_agents/unix/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, FreeBSD Version +# Version 7.0NG.738, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2016 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/HP-UX/pandora_agent.conf b/pandora_agents/unix/HP-UX/pandora_agent.conf index 57e35c0a03..bfd0612672 100644 --- a/pandora_agents/unix/HP-UX/pandora_agent.conf +++ b/pandora_agents/unix/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, HP-UX Version +# Version 7.0NG.738, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/Linux/pandora_agent.conf b/pandora_agents/unix/Linux/pandora_agent.conf index db07876f12..e1a83ed6e5 100644 --- a/pandora_agents/unix/Linux/pandora_agent.conf +++ b/pandora_agents/unix/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, GNU/Linux +# Version 7.0NG.738, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2014 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/NT4/pandora_agent.conf b/pandora_agents/unix/NT4/pandora_agent.conf index 8cda0f8fe0..b0841bd0f7 100644 --- a/pandora_agents/unix/NT4/pandora_agent.conf +++ b/pandora_agents/unix/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, GNU/Linux +# Version 7.0NG.738, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/NetBSD/pandora_agent.conf b/pandora_agents/unix/NetBSD/pandora_agent.conf index 629fe6a6fb..4d96ba223d 100644 --- a/pandora_agents/unix/NetBSD/pandora_agent.conf +++ b/pandora_agents/unix/NetBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, NetBSD Version +# Version 7.0NG.738, NetBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/SunOS/pandora_agent.conf b/pandora_agents/unix/SunOS/pandora_agent.conf index 8ff3c52de5..c4a4c578d9 100644 --- a/pandora_agents/unix/SunOS/pandora_agent.conf +++ b/pandora_agents/unix/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.735, Solaris Version +# Version 7.0NG.738, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 8fefec9ec8..80a2c23b12 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -41,8 +41,8 @@ my $Sem = undef; # Semaphore used to control the number of threads my $ThreadSem = undef; -use constant AGENT_VERSION => '7.0NG.735'; -use constant AGENT_BUILD => '190605'; +use constant AGENT_VERSION => '7.0NG.738'; +use constant AGENT_BUILD => '190906'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; @@ -3038,10 +3038,10 @@ while (1) { my @address_list; if( -x "/bin/ip" || -x "/sbin/ip" || -x "/usr/sbin/ip" ) { - @address_list = `ip addr show 2>$DevNull | sed -e '/127.0.0/d' -e '/[0-9]*\\.[0-9]*\\.[0-9]*/!d' -e 's/^[ \\t]*\\([^ \\t]*\\)[ \\t]*\\([^ \\t]*\\)[ \\t].*/\\2/' -e 's/\\/.*//'`; + @address_list = `ip addr show 2>$DevNull | sed -e '/127.0.0/d' -e '/\\([0-9][0-9]*\\.\\)\\{3\\}[0-9][0-9]*/!d' -e 's/^[ \\t]*\\([^ \\t]*\\)[ \\t]*\\([^ \\t]*\\)[ \\t].*/\\2/' -e 's/\\/.*//'`; } else { - @address_list = `ifconfig -a 2>$DevNull | sed -e '/127.0.0/d' -e '/[0-9]*\\.[0-9]*\\.[0-9]*/!d' -e 's/^[ \\t]*\\([^ \\t]*\\)[ \\t]*\\([^ \\t]*\\)[ \\t].*/\\2/' -e 's/.*://'`; + @address_list = `ifconfig -a 2>$DevNull | sed -e '/127.0.0/d' -e '/\\([0-9][0-9]*\\.\\)\\{3\\}[0-9][0-9]*/!d' -e 's/^[ \\t]*\\([^ \\t]*\\)[ \\t]*\\([^ \\t]*\\)[ \\t].*/\\2/' -e 's/.*://'`; } for (my $i = 0; $i <= $#address_list; $i++) { diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 0ca9923632..13cc96d73e 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.735 -%define release 190605 +%define version 7.0NG.738 +%define release 190906 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index a4fc651f2d..8b77150184 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.735 -%define release 190605 +%define version 7.0NG.738 +%define release 190906 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index ff2c1c7d80..54858a1d3e 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -9,8 +9,8 @@ # Please see http://www.pandorafms.org. This code is licensed under GPL 2.0 license. # ********************************************************************** -PI_VERSION="7.0NG.735" -PI_BUILD="190605" +PI_VERSION="7.0NG.738" +PI_BUILD="190906" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/unix/plugins/grep_log b/pandora_agents/unix/plugins/grep_log index 2e17210a51..76661c5230 100755 --- a/pandora_agents/unix/plugins/grep_log +++ b/pandora_agents/unix/plugins/grep_log @@ -6,17 +6,17 @@ # # grep_log Perl script to search log files for a matching pattern. The last # searched position is saved in an index file so that consecutive -# runs do not return the same results. The log file inode number is +# runs do not return the same results. The log file inode number is # also saved to detect log rotation. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. -# +# # 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. +# GNU General Public License for more details. # ############################################################################### use strict; @@ -30,7 +30,7 @@ my $Output = 'module'; my $Verbose = 0; # Index file storage directory, with a trailing '/' -my $Idx_dir=($^O =~ /win/i)?'.\\':'/tmp/'; +my $Idx_dir=($^O =~ /win/i)?"$ENV{'TMP'}\\":"/tmp/"; # Log file my $Log_file = ''; @@ -64,7 +64,7 @@ if ( (defined ($ENV{GREP_LOG_TMP})) && (-d $ENV{GREP_LOG_TMP}) ) { } ######################################################################################## -# Erase blank spaces before and after the string +# Erase blank spaces before and after the string ######################################################################################## sub trim($){ my $string = shift; @@ -226,7 +226,7 @@ sub parse_log (;$$) { open(LOGFILE, $Log_file) || error_msg("Error opening file $Log_file: " . $!); - # Go to starting position. + # Go to starting position. seek(LOGFILE, $Idx_pos, 0); # Parse log file @@ -318,7 +318,7 @@ sub print_log ($) { print_summary() if ($summary_flag == 1); return; } - + # Log module if ($Output eq 'log_module') { my $output = "\n"; diff --git a/pandora_agents/win32/bin/pandora_agent.conf b/pandora_agents/win32/bin/pandora_agent.conf index 518cd3df0e..c74dadfff6 100644 --- a/pandora_agents/win32/bin/pandora_agent.conf +++ b/pandora_agents/win32/bin/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2017 Artica Soluciones Tecnologicas -# Version 7.0NG.735 +# Version 7.0NG.738 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/win32/bin/util/grep_log.exe b/pandora_agents/win32/bin/util/grep_log.exe index a21e080805..4e4029fb60 100644 Binary files a/pandora_agents/win32/bin/util/grep_log.exe and b/pandora_agents/win32/bin/util/grep_log.exe differ diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index a195ab96ee..daa57b099d 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -3,7 +3,7 @@ AllowLanguageSelection {Yes} AppName -{Pandora FMS Windows Agent v7.0NG.735} +{Pandora FMS Windows Agent v7.0NG.738} ApplicationID {17E3D2CF-CA02-406B-8A80-9D31C17BD08F} @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190605} +{190906} ViewReadme {Yes} diff --git a/pandora_agents/win32/modules/pandora_module_factory.cc b/pandora_agents/win32/modules/pandora_module_factory.cc index a4d9553c20..4c84910ac5 100644 --- a/pandora_agents/win32/modules/pandora_module_factory.cc +++ b/pandora_agents/win32/modules/pandora_module_factory.cc @@ -1214,7 +1214,8 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_source, module_eventtype, module_eventcode, - module_pattern); + module_pattern, + module_application); } else if (module_wmiquery != "") { module = new Pandora_Module_WMIQuery (module_name, module_wmiquery, module_wmicolumn); diff --git a/pandora_agents/win32/modules/pandora_module_logchannel.cc b/pandora_agents/win32/modules/pandora_module_logchannel.cc index 4ec72df63c..3c1c4666dd 100755 --- a/pandora_agents/win32/modules/pandora_module_logchannel.cc +++ b/pandora_agents/win32/modules/pandora_module_logchannel.cc @@ -53,7 +53,7 @@ static EvtUpdateBookmarkT EvtUpdateBookmarkF = NULL; * @param name Module name. * @param service_name Service internal name to check. */ -Pandora_Module_Logchannel::Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern) +Pandora_Module_Logchannel::Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern, string application) : Pandora_Module (name) { int i; vector query; @@ -93,6 +93,13 @@ Pandora_Module_Logchannel::Pandora_Module_Logchannel (string name, string source query.push_back(ss.str()); } + // Set the application + if (application != "") { + wstringstream ss; + ss << L"*[System/Provider[@Name='" << application.c_str() << L"']]"; + query.push_back(ss.str()); + } + // Fill the filter if (query.size() == 0) { this->filter = L"*"; @@ -579,4 +586,4 @@ Pandora_Module_Logchannel::GetMessageString(EVT_HANDLE hMetadata, EVT_HANDLE hEv } return pBuffer; -} \ No newline at end of file +} diff --git a/pandora_agents/win32/modules/pandora_module_logchannel.h b/pandora_agents/win32/modules/pandora_module_logchannel.h index 19cde78b93..c008c0aac1 100755 --- a/pandora_agents/win32/modules/pandora_module_logchannel.h +++ b/pandora_agents/win32/modules/pandora_module_logchannel.h @@ -75,7 +75,7 @@ namespace Pandora_Modules { LPWSTR GetMessageString(EVT_HANDLE hMetadata, EVT_HANDLE hEvent, EVT_FORMAT_MESSAGE_FLAGS FormatId); public: - Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern); + Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern, string application); void run (); }; } diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 54994bfa82..9ef2d6ec82 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.735(Build 190605)") +#define PANDORA_VERSION ("7.0NG.738(Build 190906)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index fd912eae71..60ee89d3f1 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.735(Build 190605))" + VALUE "ProductVersion", "(7.0NG.738(Build 190906))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 00e162ac2f..305bc5d62d 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.735-190605 +Version: 7.0NG.738-190906 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 0e4d3c1331..b0d6e3e085 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.735-190605" +pandora_version="7.0NG.738-190906" package_pear=0 package_pandora=1 diff --git a/pandora_console/ajax.php b/pandora_console/ajax.php index 92f6c146bc..beb07e7752 100644 --- a/pandora_console/ajax.php +++ b/pandora_console/ajax.php @@ -1,17 +1,34 @@ '.__('Group').''; $filter_groups = html_print_select_groups(false, 'AR', true, 'group_id', $group_id, '', '', '', true, false, true, '', false, 'width: auto;'); $filter_recursion_label = ''.__('Recursion').''; $filter_recursion = html_print_checkbox('recursion', 1, 0, true); - // groups module + // Groups module. $filter_module_groups_label = ''.__('Module group').''; $filter_module_groups = html_print_select_from_sql( 'SELECT * FROM tmodule_group ORDER BY name', @@ -146,7 +147,7 @@ function mainAgentsModules() 'width: auto;' ); - // agent + // Agent. $agents = agents_get_group_agents($group_id); if ((empty($agents)) || $agents == -1) { $agents = []; @@ -155,7 +156,7 @@ function mainAgentsModules() $filter_agents_label = ''.__('Agents').''; $filter_agents = html_print_select($agents, 'id_agents2[]', $agents_id, '', '', 0, true, true, true, '', false, 'min-width: 180px; max-width: 200px;'); - // type show + // Type show. $selection = [ 0 => __('Show common modules'), 1 => __('Show all modules'), @@ -163,12 +164,12 @@ function mainAgentsModules() $filter_type_show_label = ''.__('Show common modules').''; $filter_type_show = html_print_select($selection, 'selection_agent_module', $selection_a_m, '', '', 0, true, false, true, '', false, 'min-width: 180px;'); - // modules + // Modules. $all_modules = select_modules_for_agent_group($group_id, $agents_id, $selection_a_m, false); $filter_modules_label = ''.__('Module').''; $filter_modules = html_print_select($all_modules, 'module[]', $modules_selected, '', '', 0, true, true, false, '', false, 'min-width: 180px; max-width: 200px;'); - // update + // Update. $filter_update = html_print_submit_button(__('Update item'), 'edit_item', false, 'class="sub upd"', true); $onheader = [ @@ -178,8 +179,11 @@ function mainAgentsModules() 'combo_groups' => $filter_groups, ]; - // Old style table, we need a lot of special formatting,don't use table function - // Prepare old-style table + /* + * Old style table, we need a lot of special formatting,don't use table function. + * Prepare old-style table. + */ + if ($config['pure'] == 0) { // Header. ui_print_page_header( @@ -200,38 +204,51 @@ function mainAgentsModules() $full_modules = urlencode(implode(';', $full_modules_selected)); $full_agents = urlencode(implode(';', $full_agents_id)); - $url = " index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset + $url = 'index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset &group_id=$group_id&modulegroup=$modulegroup&refresh=$refr&full_modules_selected=$full_modules - &full_agents_id=$full_agents&selection_agent_module=$selection_a_m"; + &full_agents_id=$full_agents&selection_agent_module=$selection_a_m'; } else { - $url = " index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset&group_id=$group_id&modulegroup=$modulegroup&refresh=$refr"; + $url = 'index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset&group_id=$group_id&modulegroup=$modulegroup&refresh=$refr'; } - // Floating menu - Start + // Floating menu - Start. echo '
'; echo ''; echo '
'; - // Floating menu - End + // Floating menu - End. ui_require_jquery_file('countdown'); } if ($config['pure'] != 1) { - echo '
'; - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo "'; - echo ''; - echo '
'.$filter_groups_label.''.$filter_groups.'   '.$filter_recursion_label.$filter_recursion.''.$filter_module_groups_label.''.$filter_module_groups.'
'.$filter_agents_label.''.$filter_agents.''.$filter_type_show_label.''.$filter_type_show.''.$filter_modules_label.''.$filter_modules.'
".$filter_update.'
'; - echo '
'; + $show_filters = '
'; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= ''; + $show_filters .= "'; + $show_filters .= ''; + $show_filters .= '
'.$filter_groups_label.''.$filter_groups.'   '.$filter_recursion_label.$filter_recursion.''.$filter_module_groups_label.''.$filter_module_groups.'
'.$filter_agents_label.''.$filter_agents.''.$filter_type_show_label.''.$filter_type_show.''.$filter_modules_label.''.$filter_modules.'
".$filter_update.'
'; + $show_filters .= '
'; + ui_toggle($show_filters, __('Filters')); } if ($agents_id[0] != -1) { @@ -291,7 +308,7 @@ function mainAgentsModules() $count = 0; foreach ($agents as $agent) { - // TODO TAGS agents_get_modules + // TODO TAGS agents_get_modules. $module = agents_get_modules( $agent, false, @@ -339,7 +356,7 @@ function mainAgentsModules() } } } else { - // TODO TAGS agents_get_modules + // TODO TAGS agents_get_modules. $all_modules = agents_get_modules( $agents, false, @@ -414,11 +431,11 @@ function mainAgentsModules() if ($hor_offset > 0) { $new_hor_offset = ($hor_offset - $block); - echo ""."".html_print_image( - 'images/arrow_left.png', + echo "".html_print_image( + 'images/arrow_left_green.png', true, ['title' => __('Previous modules')] - ).''.''; + ).''; } $nmodules = 0; @@ -440,11 +457,11 @@ function mainAgentsModules() if (($hor_offset + $block) < $nmodules) { $new_hor_offset = ($hor_offset + $block); - echo ""."".html_print_image( - 'images/arrow.png', + echo "".html_print_image( + 'images/arrow_right_green.png', true, ['title' => __('More modules')] - ).''.''; + ).''; } echo ''; @@ -457,12 +474,12 @@ function mainAgentsModules() $filter_agents['id_grupo'] = $group_id; } - // Prepare pagination - $url = 'index.php?extension_in_menu=estado&sec=extensions&sec2=extensions/agents_modules&save_serialize=1&'.'hor_offset='.$hor_offset.'&selection_a_m='.$selection_a_m; + // Prepare pagination. + $url = 'index.php?extension_in_menu=estado&sec=extensions&sec2=extensions/agents_modules&save_serialize=1&hor_offset='.$hor_offset.'&selection_a_m='.$selection_a_m; ui_pagination($total_pagination, $url); foreach ($agents as $agent) { - // Get stats for this group + // Get stats for this group. $agent_status = agents_get_status($agent['id_agente']); $alias = db_get_row('tagente', 'id_agente', $agent['id_agente']); if (empty($alias['alias'])) { @@ -471,29 +488,29 @@ function mainAgentsModules() switch ($agent_status) { case 4: - // Alert fired status + // Alert fired status. $rowcolor = 'group_view_alrm'; break; case 1: - // Critical status + // Critical status. $rowcolor = 'group_view_crit'; break; case 2: - // Warning status + // Warning status. $rowcolor = 'group_view_warn'; break; case 0: - // Normal status + // Normal status. $rowcolor = 'group_view_ok'; break; case 3: case -1: default: - // Unknown status + // Unknown status. $rowcolor = 'group_view_unk'; break; } @@ -502,7 +519,7 @@ function mainAgentsModules() echo " ".$alias['alias'].''; - // TODO TAGS agents_get_modules + // TODO TAGS agents_get_modules. $agent_modules = agents_get_modules($agent['id_agente'], false, $filter_module_group, true, true); $nmodules = 0; @@ -572,18 +589,23 @@ function mainAgentsModules() echo ''; - echo "
"; + $show_legend = "
"; + $show_legend .= "
+
".__('Orange cell when the module has fired alerts').'
'; + $show_legend .= "
+
".__('Red cell when the module has a critical status').' +
'; + $show_legend .= "
+
".__('Yellow cell when the module has a warning status').'
'; + $show_legend .= "
+
".__('Green cell when the module has a normal status').'
'; + $show_legend .= "
+
".__('Grey cell when the module has an unknown status').'
'; + $show_legend .= "
+
".__("Cell turns blue when the module is in 'not initialize' status").'
'; + $show_legend .= '
'; + ui_toggle($show_legend, __('Legend')); - echo ''; - echo "'; - echo "'; - echo "'; - echo "'; - echo "'; - echo "'; - echo "'; - echo '
".__('Legend').'
".__('Orange cell when the module has fired alerts').'
".__('Red cell when the module has a critical status').'
".__('Yellow cell when the module has a warning status').'
".__('Green cell when the module has a normal status').'
".__('Grey cell when the module has an unknown status').'
".__("Cell turns blue when the module is in 'not initialize' status").'
'; - echo '
'; $pure_var = $config['pure']; if ($pure_var) { $pure_var = 1; @@ -627,16 +649,14 @@ $ignored_params['refresh'] = ''; $.each($('.th_class_module_r'), function (i, elem) { id = $(elem).attr('id').replace('th_module_r_', ''); $("#th_module_r_" + id).height(($("#div_module_r_" + id).width() + 10) + 'px'); - - //$("#div_module_r_" + id).css('margin-top', (max_width - $("#div_module_r_" + id).width()) + 'px'); $("#div_module_r_" + id).css('margin-top', (max_width - 20) + 'px'); $("#div_module_r_" + id).show(); }); - var refr =" . $refr . "; - var pure =" . $pure_var . "; - var href ='" . ui_get_url_refresh ($ignored_params) . "'; - + var refr = ''; + var pure = ''; + var href =' '; + if (pure) { var startCountDown = function (duration, cb) { $('div.vc-countdown').countdown('destroy'); @@ -646,7 +666,7 @@ $ignored_params['refresh'] = ''; $('div.vc-countdown').countdown({ until: t, format: 'MS', - layout: '(%M%nn%M:%S%nn%S Until refresh)', + layout: '(%M%nn%M:%S%nn%S ) ', alwaysExpire: true, onExpiry: function () { $('div.vc-countdown').countdown('destroy'); @@ -655,8 +675,11 @@ $ignored_params['refresh'] = ''; } }); } - - startCountDown(refr, false); + + if(refr>0){ + startCountDown(refr, false); + } + var controls = document.getElementById('vc-controls'); autoHideElement(controls, 1000); diff --git a/pandora_console/extensions/db_status.php b/pandora_console/extensions/db_status.php index 2d8669f83f..5659ed6d9b 100755 --- a/pandora_console/extensions/db_status.php +++ b/pandora_console/extensions/db_status.php @@ -69,7 +69,7 @@ function extension_db_status() echo "
"; html_print_input_hidden('db_status_execute', 1); - html_print_submit_button(__('Execute Test'), 'submit', false, 'class="sub"'); + html_print_submit_button(__('Execute Test'), 'submit', false, 'class="sub next"'); echo '
'; echo ''; @@ -215,7 +215,7 @@ function extension_db_check_tables_differences( $diff_tables = array_diff($tables_test, $tables_system); ui_print_result_message( - !empty($diff_tables), + empty($diff_tables), __('Success! %s DB contains all tables', get_product_name()), __( '%s DB could not retrieve all tables. The missing tables are (%s)', diff --git a/pandora_console/extensions/module_groups.php b/pandora_console/extensions/module_groups.php index 9e750be932..8b5075f77c 100644 --- a/pandora_console/extensions/module_groups.php +++ b/pandora_console/extensions/module_groups.php @@ -1,17 +1,32 @@ 0, 1, 0)) AS alerts_module_count, - SUM(IF($condition_warning, 1, 0)) AS warning_module_count, - SUM(IF($condition_unknown, 1, 0)) AS unknown_module_count, - SUM(IF($condition_not_init, 1, 0)) AS notInit_module_count, - SUM(IF($condition_critical, 1, 0)) AS critical_module_count, - SUM(IF($condition_normal, 1, 0)) AS normal_module_count, - COUNT(tae.id_agente_modulo) AS total_count, - tmg.id_mg, - tmg.name as n, - tg.id_grupo - FROM ( - SELECT tam.id_agente_modulo, - tam.id_module_group, - ta.id_grupo AS g, - tae.estado, - SUM(IF(tatm.last_fired <> 0, 1, 0)) AS alert_fired - FROM tagente_modulo tam - LEFT JOIN talert_template_modules tatm - ON tatm.id_agent_module = tam.id_agente_modulo - AND tatm.times_fired = 1 - LEFT JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo - INNER JOIN tagente ta - ON ta.id_agente = tam.id_agente - WHERE ta.disabled = 0 - AND tam.disabled = 0 - AND tam.delete_pending = 0 - AND ta.id_grupo IN ($ids_group) - GROUP BY tam.id_agente_modulo - UNION ALL - SELECT tam.id_agente_modulo, - tam.id_module_group, - tasg.id_group AS g, - tae.estado, - SUM(IF(tatm.last_fired <> 0, 1, 0)) AS alert_fired - FROM tagente_modulo tam - LEFT JOIN talert_template_modules tatm - ON tatm.id_agent_module = tam.id_agente_modulo - AND tatm.times_fired = 1 - LEFT JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo - INNER JOIN tagente ta - ON ta.id_agente = tam.id_agente - INNER JOIN tagent_secondary_group tasg - ON ta.id_agente = tasg.id_agent - WHERE ta.disabled = 0 - AND tam.disabled = 0 - AND tam.delete_pending = 0 - AND tasg.id_group IN ($ids_group) - GROUP BY tam.id_agente_modulo, tasg.id_group - ) AS tae - RIGHT JOIN tgrupo tg - ON tg.id_grupo = tae.g - INNER JOIN ( - SELECT * FROM tmodule_group - UNION ALL - SELECT 0 AS 'id_mg', 'Nothing' AS 'name' - ) AS tmg - ON tae.id_module_group = tmg.id_mg - GROUP BY tae.g, tmg.id_mg"; + $sql = sprintf( + "SELECT SUM(IF(tae.alert_fired <> 0, 1, 0)) AS alerts_module_count, + SUM(IF(%s, 1, 0)) AS warning_module_count, + SUM(IF(%s, 1, 0)) AS unknown_module_count, + SUM(IF(%s, 1, 0)) AS notInit_module_count, + SUM(IF(%s, 1, 0)) AS critical_module_count, + SUM(IF(%s, 1, 0)) AS normal_module_count, + COUNT(tae.id_agente_modulo) AS total_count, + tmg.id_mg, + tmg.name as n, + tg.id_grupo + FROM ( + SELECT tam.id_agente_modulo, + tam.id_module_group, + ta.id_grupo AS g, + tae.estado, + SUM(IF(tatm.last_fired <> 0, 1, 0)) AS alert_fired + FROM tagente_modulo tam + LEFT JOIN talert_template_modules tatm + ON tatm.id_agent_module = tam.id_agente_modulo + AND tatm.times_fired = 1 + LEFT JOIN tagente_estado tae + ON tae.id_agente_modulo = tam.id_agente_modulo + INNER JOIN tagente ta + ON ta.id_agente = tam.id_agente + WHERE ta.disabled = 0 + AND tam.disabled = 0 + AND tam.delete_pending = 0 + AND ta.id_grupo IN (%s) + GROUP BY tam.id_agente_modulo + UNION ALL + SELECT tam.id_agente_modulo, + tam.id_module_group, + tasg.id_group AS g, + tae.estado, + SUM(IF(tatm.last_fired <> 0, 1, 0)) AS alert_fired + FROM tagente_modulo tam + LEFT JOIN talert_template_modules tatm + ON tatm.id_agent_module = tam.id_agente_modulo + AND tatm.times_fired = 1 + LEFT JOIN tagente_estado tae + ON tae.id_agente_modulo = tam.id_agente_modulo + INNER JOIN tagente ta + ON ta.id_agente = tam.id_agente + INNER JOIN tagent_secondary_group tasg + ON ta.id_agente = tasg.id_agent + WHERE ta.disabled = 0 + AND tam.disabled = 0 + AND tam.delete_pending = 0 + AND tasg.id_group IN (%s) + GROUP BY tam.id_agente_modulo, tasg.id_group + ) AS tae + RIGHT JOIN tgrupo tg + ON tg.id_grupo = tae.g + INNER JOIN ( + SELECT * FROM tmodule_group + UNION ALL + SELECT 0 AS 'id_mg', 'Nothing' AS 'name' + ) AS tmg + ON tae.id_module_group = tmg.id_mg + GROUP BY tae.g, tmg.id_mg", + $condition_warning, + $condition_unknown, + $condition_not_init, + $condition_critical, + $condition_normal, + $ids_group, + $ids_group + ); $array_data_prev = db_get_all_rows_sql($sql); @@ -220,11 +253,29 @@ function mainModuleGroups() echo ''; echo ''; + $cell_style = ' + min-width: 60px; + width: 100%; + margin: 0; + overflow:hidden; + text-align: center; + padding: 5px; + padding-bottom:10px; + font-size: 18px; + text-align: center; + '; + if (true) { $table = new StdClass(); - $table->style[0] = 'color: #ffffff; background-color: #373737; font-weight: bolder; padding-right: 10px; min-width: 230px;'; + $table->style[0] = 'color: #ffffff; background-color: #373737; font-weight: bolder; min-width: 230px;'; $table->width = '100%'; + if ($config['style'] === 'pandora_black') { + $background_color = '#333'; + } else { + $background_color = '#fff'; + } + $head[0] = __('Groups'); $headstyle[0] = 'width: 20%; font-weight: bolder;'; foreach ($array_module_group as $key => $value) { @@ -248,28 +299,28 @@ function mainModuleGroups() $color = '#FFA631'; // Orange when the cell for this model group and agent has at least one alert fired. } else if ($array_data[$key][$k]['critical_module_count'] != 0) { - $color = '#FC4444'; + $color = '#e63c52'; // Red when the cell for this model group and agent has at least one module in critical state and the rest in any state. } else if ($array_data[$key][$k]['warning_module_count'] != 0) { - $color = '#FAD403'; + $color = '#f3b200'; // Yellow when the cell for this model group and agent has at least one in warning state and the rest in green state. } else if ($array_data[$key][$k]['unknown_module_count'] != 0) { $color = '#B2B2B2 '; // Grey when the cell for this model group and agent has at least one module in unknown state and the rest in any state. } else if ($array_data[$key][$k]['normal_module_count'] != 0) { - $color = '#80BA27'; + $color = '#82b92e'; // Green when the cell for this model group and agent has OK state all modules. } else if ($array_data[$key][$k]['notInit_module_count'] != 0) { $color = '#5BB6E5'; // Blue when the cell for this module group and all modules have not init value. } - $data[$i][$j] = "
"; + $data[$i][$j] = "'; } else { - $data[$i][$j] = "
"; + $data[$i][$j] = "
"; $data[$i][$j] .= 0; $data[$i][$j] .= '
'; } @@ -278,7 +329,7 @@ function mainModuleGroups() } } else { foreach ($value['gm'] as $k => $v) { - $data[$i][$j] = "
"; + $data[$i][$j] = "
"; $data[$i][$j] .= 0; $data[$i][$j] .= '
'; $j++; diff --git a/pandora_console/extensions/net_tools.php b/pandora_console/extensions/net_tools.php index e6ec05977b..ba66cae68e 100644 --- a/pandora_console/extensions/net_tools.php +++ b/pandora_console/extensions/net_tools.php @@ -1,26 +1,60 @@ ".__('The agent hasn\'t got IP').'
'; - return; - } - - echo " - "; - - echo '
'; - echo "
"; - echo ""; - echo ''; - echo ''; - echo "'; - echo '
'; - echo __('Operation'); - ui_print_help_tip( - __('You can set the command path in the menu Administration -> Extensions -> Config Network Tools') - ); - echo ''; - echo "'; - echo ''; - echo __('IP address'); - echo ''; - echo "'; - echo '"; - echo __('SNMP Community').' '; - echo ""; - echo ''; - echo ""; - echo '
'; - echo '
'; - - $operation = get_parameter('operation', 0); - $community = get_parameter('community', 'public'); - $ip = get_parameter('select_ips'); - if (!validate_address($ip)) { - ui_print_error_message(__('The ip or dns name entered cannot be resolved')); + ui_print_error_message(__('The ip or dns name entered cannot be resolved')); } else { switch ($operation) { case 1: @@ -175,7 +147,7 @@ function main_net_tools() } else { echo '

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

'; echo '
';
-                    echo system("$traceroute $ip");
+                    echo system($traceroute.' '.$ip);
                     echo '
'; } break; @@ -187,7 +159,7 @@ function main_net_tools() } else { echo '

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

'; echo '
';
-                    echo system("$ping -c 5 $ip");
+                    echo system($ping.' -c 5 '.$ip);
                     echo '
'; } break; @@ -199,7 +171,7 @@ function main_net_tools() } else { echo '

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

'; echo '
';
-                    echo system("$nmap -F $ip");
+                    echo system($nmap.' -F '.$ip);
                     echo '
'; } break; @@ -212,7 +184,7 @@ function main_net_tools() ui_print_error_message(__('Dig executable does not exist.')); } else { echo '
';
-                    echo system("dig $ip");
+                    echo system('dig '.$ip);
                     echo '
'; } @@ -221,51 +193,227 @@ function main_net_tools() ui_print_error_message(__('Whois executable does not exist.')); } else { echo '
';
-                    echo system("whois $ip");
+                    echo system('whois '.$ip);
                     echo '
'; } break; case 3: + $snmp_obj = [ + 'ip_target' => $ip, + 'snmp_version' => $snmp_version, + 'snmp_community' => $community, + 'format' => '-Oqn', + ]; + + $snmp_obj['base_oid'] = '.1.3.6.1.2.1.1.3.0'; + $result = get_h_snmpwalk($snmp_obj); echo '

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

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

'.__('Uptime').'

'; + echo '
';
+                if (empty($result)) {
+                    ui_print_error_message(__('Target unreachable.'));
+                    break;
                 } else {
-                    echo '

'.__('Uptime').'

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

'.__('Device info').'

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

Interface Information

'; - echo ''; - echo '
'.__('Interface'); - echo ''.__('Status'); - - $int_max = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.1.0 "); - - for ($ax = 0; $ax < $int_max; $ax++) { - $interface = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.2.$ax "); - $estado = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.8.$ax "); - echo "
$interface$estado"; - } - - echo '
'; + echo array_pop($result); } + + echo '
'; + echo '

'.__('Device info').'

'; + echo '
';
+                $snmp_obj['base_oid'] = '.1.3.6.1.2.1.1.1.0';
+                $result = get_h_snmpwalk($snmp_obj);
+                if (empty($result)) {
+                    ui_print_error_message(__('Target unreachable.'));
+                    break;
+                } else {
+                    echo array_pop($result);
+                }
+
+                echo '
'; + + echo '

Interface Information

'; + + $table = new StdClass(); + $table->class = 'databox'; + $table->head = []; + $table->head[] = __('Interface'); + $table->head[] = __('Status'); + + $i = 0; + + $base_oid = '.1.3.6.1.2.1.2.2.1'; + $idx_oids = '.1'; + $names_oids = '.2'; + $status_oids = '.8'; + + $snmp_obj['base_oid'] = $base_oid.$idx_oids; + $idx = get_h_snmpwalk($snmp_obj); + + $snmp_obj['base_oid'] = $base_oid.$names_oids; + $names = get_h_snmpwalk($snmp_obj); + + $snmp_obj['base_oid'] = $base_oid.$status_oids; + $statuses = get_h_snmpwalk($snmp_obj); + + foreach ($idx as $k => $v) { + $index = str_replace($base_oid.$idx_oids, '', $k); + $name = $names[$base_oid.$names_oids.$index]; + + $status = $statuses[$base_oid.$status_oids.$index]; + + $table->data[$i][0] = $name; + $table->data[$i++][1] = $status; + } + + html_print_table($table); + break; + + default: + // Ignore. break; } } +} + + +/** + * Main function. + * + * @return void + */ +function main_net_tools() +{ + $operation = get_parameter('operation', 0); + $community = get_parameter('community', 'public'); + $ip = get_parameter('select_ips'); + $snmp_version = get_parameter('select_version'); + + // Show form. + $id_agente = get_parameter('id_agente', 0); + $principal_ip = db_get_sql( + sprintf( + 'SELECT direccion FROM tagente WHERE id_agente = %d', + $id_agente + ) + ); + + $list_address = db_get_all_rows_sql( + sprintf( + 'SELECT id_a FROM taddress_agent WHERE id_agent = %d', + $id_agente + ) + ); + foreach ($list_address as $address) { + $ids[] = join(',', $address); + } + + $ips = db_get_all_rows_sql( + sprintf( + 'SELECT ip FROM taddress WHERE id_a IN (%s)', + join($ids) + ) + ); + + if ($ips == '') { + echo "
".__('The agent hasn\'t got IP').'
'; + return; + } + + // Javascript. + ?> + + '; + echo "
"; + echo ""; + echo ''; + echo ''; + echo "'; + echo '
'; + echo __('Operation'); + ui_print_help_tip( + __('You can set the command path in the menu Administration -> Extensions -> Config Network Tools') + ); + echo ''; + + html_print_select( + [ + 1 => __('Traceroute'), + 2 => __('Ping host & Latency'), + 3 => __('SNMP Interface status'), + 4 => __('Basic TCP Port Scan'), + 5 => __('DiG/Whois Lookup'), + ], + 'operation', + $operation, + 'mostrarColumns(this.value)', + __('Please select') + ); + + echo ''; + echo __('IP address'); + echo ''; + + $ips_for_select = array_reduce( + $ips, + function ($carry, $item) { + $carry[$item['ip']] = $item['ip']; + return $carry; + } + ); + + html_print_select( + $ips_for_select, + 'select_ips', + $principal_ip + ); + echo '"; + echo __('SNMP Version'); + html_print_select( + [ + '1' => 'v1', + '2c' => 'v2c', + ], + 'select_version', + $snmp_version + ); + echo ''; + echo __('SNMP Community').' '; + html_print_input_text('community', $community); + echo ''; + echo ""; + echo '
'; + echo '
'; + + if ($operation) { + // Execute form. + net_tools_execute($operation, $ip, $community, $snmp_version); + } + echo '
'; } +/** + * Add option. + * + * @return void + */ function godmode_net_tools() { global $config; diff --git a/pandora_console/extensions/realtime_graphs.php b/pandora_console/extensions/realtime_graphs.php index cea09fe4d5..e487d49ee5 100644 --- a/pandora_console/extensions/realtime_graphs.php +++ b/pandora_console/extensions/realtime_graphs.php @@ -173,7 +173,7 @@ function pandora_realtime_graphs() $table->colspan[2]['snmp_oid'] = 2; $data['snmp_ver'] = __('Version').'  '.html_print_select($snmp_versions, 'snmp_version', $snmp_ver, '', '', 0, true); - $data['snmp_ver'] .= '  '.html_print_button(__('SNMP walk'), 'snmp_walk', false, 'javascript:realtimeGraphs.snmpBrowserWindow();', 'class="sub next"', true); + $data['snmp_ver'] .= '  '.html_print_button(__('SNMP walk'), 'snmp_walk', false, 'javascript:snmpBrowserWindow();', 'class="sub next"', true); $table->colspan[2]['snmp_ver'] = 2; $table->data[] = $data; diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.css b/pandora_console/extensions/realtime_graphs/realtime_graphs.css index ab6c94e238..2219c6152a 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.css +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.css @@ -11,5 +11,5 @@ #graph_container { width: 800px; - margin: 20px auto !important; + margin: 20px auto; } diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.js b/pandora_console/extensions/realtime_graphs/realtime_graphs.js index 7140d245d4..b5d6c1eaa8 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.js +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.js @@ -10,7 +10,9 @@ var plot; var plotOptions = { - legend: { container: $("#chartLegend") }, + legend: { + container: $("#chartLegend") + }, xaxis: { tickFormatter: function(timestamp, axis) { var date = new Date(timestamp * 1000); @@ -131,47 +133,6 @@ resetDataPooling(); } - // Set the form OID to the value selected in the SNMP browser - function setOID() { - if ($("#snmp_browser_version").val() == "3") { - $("#text-snmp_oid").val($("#table1-0-1").text()); - } else { - $("#text-snmp_oid").val($("#snmp_selected_oid").text()); - } - - // Close the SNMP browser - $(".ui-dialog-titlebar-close").trigger("click"); - } - - // Show the SNMP browser window - function snmpBrowserWindow() { - // Keep elements in the form and the SNMP browser synced - $("#text-target_ip").val($("#text-ip_target").val()); - $("#text-community").val($("#text-snmp_community").val()); - $("#snmp_browser_version").val($("#snmp_version").val()); - $("#snmp3_browser_auth_user").val($("#snmp3_auth_user").val()); - $("#snmp3_browser_security_level").val($("#snmp3_security_level").val()); - $("#snmp3_browser_auth_method").val($("#snmp3_auth_method").val()); - $("#snmp3_browser_auth_pass").val($("#snmp3_auth_pass").val()); - $("#snmp3_browser_privacy_method").val($("#snmp3_privacy_method").val()); - $("#snmp3_browser_privacy_pass").val($("#snmp3_privacy_pass").val()); - - $("#snmp_browser_container") - .show() - .dialog({ - title: "", - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: "black" - }, - width: 920, - height: 500 - }); - } - function shortNumber(number) { if (Math.round(number) != number) return number; number = Number.parseInt(number); @@ -187,6 +148,7 @@ return number + " " + shorts[pos]; } + function roundToTwo(num) { return +(Math.round(num + "e+2") + "e-2"); } diff --git a/pandora_console/extras/delete_files/delete_files.txt b/pandora_console/extras/delete_files/delete_files.txt index 82ce1527aa..c0d8f0a9db 100644 --- a/pandora_console/extras/delete_files/delete_files.txt +++ b/pandora_console/extras/delete_files/delete_files.txt @@ -1,3 +1 @@ -/general/login_identification_wizard.php -/general/login_required.php -/godmode/update_manager/update_manager.messages.php \ No newline at end of file +operation/servers/recon_view.php \ No newline at end of file diff --git a/pandora_console/extras/mr/29.sql b/pandora_console/extras/mr/29.sql new file mode 100644 index 0000000000..2bc8b9a8c9 --- /dev/null +++ b/pandora_console/extras/mr/29.sql @@ -0,0 +1,28 @@ +START TRANSACTION; + +ALTER TABLE `tmetaconsole_agent` ADD INDEX `id_tagente_idx` (`id_tagente`); + +DELETE FROM `ttipo_modulo` WHERE `nombre` LIKE 'log4x'; + +CREATE TABLE IF NOT EXISTS `tcredential_store` ( + `identifier` varchar(100) NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL DEFAULT 0, + `product` enum('CUSTOM', 'AWS', 'AZURE', 'GOOGLE') default 'CUSTOM', + `username` text, + `password` text, + `extra_1` text, + `extra_2` text, + PRIMARY KEY (`identifier`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +INSERT INTO `tcredential_store` (`identifier`, `id_group`, `product`, `username`, `password`) VALUES ("imported_aws_account", 0, "AWS", (SELECT `value` FROM `tconfig` WHERE `token` = "aws_access_key_id" LIMIT 1), (SELECT `value` FROM `tconfig` WHERE `token` = "aws_secret_access_key" LIMIT 1)); +DELETE FROM `tcredential_store` WHERE `username` IS NULL AND `password` IS NULL; + +UPDATE `tagente` ta INNER JOIN `tagente` taa on ta.`id_parent` = taa.`id_agente` AND taa.`nombre` IN ("us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "eu-west-3", "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "sa-east-1") SET ta.nombre = md5(concat((SELECT `username` FROM `tcredential_store` WHERE `identifier` = "imported_aws_account" LIMIT 1), ta.`nombre`)); + +UPDATE `tagente` SET `nombre` = md5(concat((SELECT `username` FROM `tcredential_store` WHERE `identifier` = "imported_aws_account" LIMIT 1), `nombre`)) WHERE `nombre` IN ("Aws", "us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "eu-west-3", "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "sa-east-1"); + +UPDATE `trecon_task` SET `auth_strings` = "imported_aws_account" WHERE `type` IN (2,6,7); + +COMMIT; diff --git a/pandora_console/extras/mr/30.sql b/pandora_console/extras/mr/30.sql new file mode 100644 index 0000000000..84e5adfa3e --- /dev/null +++ b/pandora_console/extras/mr/30.sql @@ -0,0 +1,51 @@ +START TRANSACTION; + +ALTER TABLE `treport_content_sla_combined` ADD `id_agent_module_failover` int(10) unsigned NOT NULL; + +ALTER TABLE `treport_content` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '0'; +ALTER TABLE `treport_content` ADD COLUMN `failover_type` tinyint(1) DEFAULT '0'; + +ALTER TABLE `treport_content_template` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '1'; +ALTER TABLE `treport_content_template` ADD COLUMN `failover_type` tinyint(1) DEFAULT '1'; + +ALTER TABLE `tmodule_relationship` ADD COLUMN `type` ENUM('direct', 'failover') DEFAULT 'direct'; + +ALTER TABLE `treport_content` MODIFY COLUMN `name` varchar(300) NULL; + +CREATE TABLE `tagent_repository` ( + `id` SERIAL, + `id_os` INT(10) UNSIGNED DEFAULT 0, + `arch` ENUM('x64', 'x86') DEFAULT 'x64', + `version` VARCHAR(10) DEFAULT '', + `path` text, + `uploaded_by` VARCHAR(100) DEFAULT '', + `uploaded` bigint(20) NOT NULL DEFAULT 0 COMMENT "When it was uploaded", + `last_err` text, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_os`) REFERENCES `tconfig_os`(`id_os`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tdeployment_hosts` ( + `id` SERIAL, + `id_cs` VARCHAR(100), + `ip` VARCHAR(100) NOT NULL UNIQUE, + `id_os` INT(10) UNSIGNED DEFAULT 0, + `os_version` VARCHAR(100) DEFAULT '' COMMENT "OS version in STR format", + `arch` ENUM('x64', 'x86') DEFAULT 'x64', + `current_agent_version` VARCHAR(100) DEFAULT '' COMMENT "String latest installed agent", + `target_agent_version_id` BIGINT UNSIGNED, + `deployed` bigint(20) NOT NULL DEFAULT 0 COMMENT "When it was deployed", + `server_ip` varchar(100) default NULL COMMENT "Where to point target agent", + `last_err` text, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_cs`) REFERENCES `tcredential_store`(`identifier`) + ON UPDATE CASCADE ON DELETE SET NULL, + FOREIGN KEY (`id_os`) REFERENCES `tconfig_os`(`id_os`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`target_agent_version_id`) REFERENCES `tagent_repository`(`id`) + ON UPDATE CASCADE ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +COMMIT; diff --git a/pandora_console/extras/mr/31.sql b/pandora_console/extras/mr/31.sql new file mode 100644 index 0000000000..3e527bff53 --- /dev/null +++ b/pandora_console/extras/mr/31.sql @@ -0,0 +1,12 @@ +START TRANSACTION; + +UPDATE `tconfig` SET `value` = 'mini_severity,evento,id_agente,estado,timestamp' WHERE `token` LIKE 'event_fields'; + +DELETE FROM `talert_commands` WHERE `id` = 11; + +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_enabled'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_api_password'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_inventory'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_url'; + +COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandora_diag.php b/pandora_console/extras/pandora_diag.php index c5420c26bd..9258a3be42 100644 --- a/pandora_console/extras/pandora_diag.php +++ b/pandora_console/extras/pandora_diag.php @@ -139,8 +139,9 @@ function get_logs_size($file) function get_status_logs($path) { $status_server_log = ''; - $size_server_log = get_logs_size($path); - if ($size_server_log <= 1048576) { + $size_server_log = number_format(get_logs_size($path)); + $size_server_log = (0 + str_replace(',', '', $size_server_log)); + if ($size_server_log <= 10485760) { $status_server_log = "Normal Status   You have less than 10 MB of logs"; } else { $status_server_log = "Warning Status   You have more than 10 MB of logs"; @@ -361,7 +362,7 @@ if ($console_mode == 1) { true ); - echo ""; + echo "
"; echo "'; } diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 2c9ff7e7de..704ab61d74 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -724,7 +724,7 @@ CREATE TABLE IF NOT EXISTS `treport_content_template` ( `type` varchar(30) default 'simple_graph', `period` int(11) NOT NULL default 0, `order` int (11) NOT NULL default 0, - `description` mediumtext, + `description` mediumtext, `text_agent` text, `text` TEXT, `external_source` Text, @@ -796,6 +796,8 @@ ALTER TABLE `treport_content_template` ADD COLUMN `unknown_checks` TINYINT(1) DE ALTER TABLE `treport_content_template` ADD COLUMN `agent_max_value` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content_template` ADD COLUMN `agent_min_value` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content_template` ADD COLUMN `current_month` TINYINT(1) DEFAULT '1'; +ALTER TABLE `treport_content_template` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '1'; +ALTER TABLE `treport_content_template` ADD COLUMN `failover_type` tinyint(1) DEFAULT '1'; -- ----------------------------------------------------- -- Table `treport_content_sla_com_temp` (treport_content_sla_combined_template) @@ -1007,10 +1009,12 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_agent` ( `agent_version` varchar(100) default '', `ultimo_contacto_remoto` datetime default '1970-01-01 00:00:00', `disabled` tinyint(2) NOT NULL default '0', + `remote` tinyint(1) NOT NULL default '0', `id_parent` int(10) unsigned default '0', `custom_id` varchar(255) default '', `server_name` varchar(100) default '', `cascade_protection` tinyint(2) NOT NULL default '0', + `cascade_protection_module` int(10) unsigned default '0', `timezone_offset` TINYINT(2) NULL DEFAULT '0' COMMENT 'number of hours of diference with the server timezone' , `icon_path` VARCHAR(127) NULL DEFAULT NULL COMMENT 'path in the server to the image of the icon representing the agent' , `update_gis_data` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'set it to one to update the position data (altitude, longitude, latitude) when getting information from the agent or to 0 to keep the last value and do not update it' , @@ -1025,19 +1029,21 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_agent` ( `fired_count` bigint(20) NOT NULL default '0', `update_module_count` tinyint(1) NOT NULL default '0', `update_alert_count` tinyint(1) NOT NULL default '0', + `update_secondary_groups` tinyint(1) NOT NULL default '0', + `transactional_agent` tinyint(1) NOT NULL default '0', + `alias` varchar(600) BINARY NOT NULL default '', + `alias_as_name` tinyint(2) NOT NULL default '0', + `safe_mode_module` int(10) unsigned NOT NULL default '0', + `cps` int NOT NULL default 0, PRIMARY KEY (`id_agente`), KEY `nombre` (`nombre`(255)), KEY `direccion` (`direccion`), + KEY `id_tagente_idx` (`id_tagente`), KEY `disabled` (`disabled`), KEY `id_grupo` (`id_grupo`), FOREIGN KEY (`id_tmetaconsole_setup`) REFERENCES tmetaconsole_setup(`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -ALTER TABLE tmetaconsole_agent ADD COLUMN `remote` tinyint(1) NOT NULL default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `cascade_protection_module` int(10) default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `transactional_agent` tinyint(1) NOT NULL default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `alias` VARCHAR(600) not null DEFAULT ''; - -- --------------------------------------------------------------------- -- Table `ttransaction` -- --------------------------------------------------------------------- @@ -1219,6 +1225,8 @@ ALTER TABLE `talert_commands` ADD COLUMN `fields_hidden` text; UPDATE `talert_actions` SET `field4` = 'text/html', `field4_recovery` = 'text/html' WHERE id = 1; +DELETE FROM `talert_commands` WHERE `id` = 11; + -- --------------------------------------------------------------------- -- Table `tmap` -- --------------------------------------------------------------------- @@ -1235,14 +1243,19 @@ ALTER TABLE titem MODIFY `source_data` int(10) unsigned; INSERT INTO `tconfig` (`token`, `value`) VALUES ('big_operation_step_datos_purge', '100'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('small_operation_step_datos_purge', '1000'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('days_autodisable_deletion', '30'); -INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 28); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 31); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_docs_logo', 'default_docs.png'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_support_logo', 'default_support.png'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_logo_white_bg_preview', 'pandora_logo_head_white_bg.png'); UPDATE tconfig SET value = 'https://licensing.artica.es/pandoraupdate7/server.php' WHERE token='url_update_manager'; DELETE FROM `tconfig` WHERE `token` = 'current_package_enterprise'; -INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '735'); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '737'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('status_monitor_fields', 'policy,agent,data_type,module_name,server_type,interval,status,graph,warn,data,timestamp'); +UPDATE `tconfig` SET `value` = 'mini_severity,evento,id_agente,estado,timestamp' WHERE `token` LIKE 'event_fields'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_enabled'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_api_password'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_inventory'; +DELETE FROM `tconfig` WHERE `token` LIKE 'integria_url'; -- --------------------------------------------------------------------- -- Table `tconfig_os` @@ -1438,11 +1451,15 @@ ALTER TABLE `treport_content` ADD COLUMN `unknown_checks` TINYINT(1) DEFAULT '1' ALTER TABLE `treport_content` ADD COLUMN `agent_max_value` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content` ADD COLUMN `agent_min_value` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content` ADD COLUMN `current_month` TINYINT(1) DEFAULT '1'; +ALTER TABLE `treport_content` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '0'; +ALTER TABLE `treport_content` ADD COLUMN `failover_type` tinyint(1) DEFAULT '0'; +ALTER table `treport_content` MODIFY COLUMN `name` varchar(300) NULL; -- --------------------------------------------------------------------- -- Table `tmodule_relationship` -- --------------------------------------------------------------------- ALTER TABLE tmodule_relationship ADD COLUMN `id_server` varchar(100) NOT NULL DEFAULT ''; +ALTER TABLE `tmodule_relationship` ADD COLUMN `type` ENUM('direct', 'failover') DEFAULT 'direct'; -- --------------------------------------------------------------------- -- Table `tpolicy_module` @@ -2192,3 +2209,62 @@ CREATE TABLE `tvisual_console_elements_cache` ( ON UPDATE CASCADE ) engine=InnoDB DEFAULT CHARSET=utf8; +-- --------------------------------------------------------------------- +-- Table `tcredential_store` +-- --------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `tcredential_store` ( + `identifier` varchar(100) NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL DEFAULT 0, + `product` enum('CUSTOM', 'AWS', 'AZURE', 'GOOGLE') default 'CUSTOM', + `username` text, + `password` text, + `extra_1` text, + `extra_2` text, + PRIMARY KEY (`identifier`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- --------------------------------------------------------------------- +-- Table `treport_content_sla_combined` +-- --------------------------------------------------------------------- +ALTER TABLE `treport_content_sla_combined` ADD `id_agent_module_failover` int(10) unsigned NOT NULL; + +-- --------------------------------------------------------------------- +-- Table `tagent_repository` +-- --------------------------------------------------------------------- +CREATE TABLE `tagent_repository` ( + `id` SERIAL, + `id_os` INT(10) UNSIGNED DEFAULT 0, + `arch` ENUM('x64', 'x86') DEFAULT 'x64', + `version` VARCHAR(10) DEFAULT '', + `path` text, + `uploaded_by` VARCHAR(100) DEFAULT '', + `uploaded` bigint(20) NOT NULL DEFAULT 0 COMMENT "When it was uploaded", + `last_err` text, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_os`) REFERENCES `tconfig_os`(`id_os`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tdeployment_hosts` +-- ---------------------------------------------------------------------- +CREATE TABLE `tdeployment_hosts` ( + `id` SERIAL, + `id_cs` VARCHAR(100), + `ip` VARCHAR(100) NOT NULL UNIQUE, + `id_os` INT(10) UNSIGNED DEFAULT 0, + `os_version` VARCHAR(100) DEFAULT '' COMMENT "OS version in STR format", + `arch` ENUM('x64', 'x86') DEFAULT 'x64', + `current_agent_version` VARCHAR(100) DEFAULT '' COMMENT "String latest installed agent", + `target_agent_version_id` BIGINT UNSIGNED, + `deployed` bigint(20) NOT NULL DEFAULT 0 COMMENT "When it was deployed", + `server_ip` varchar(100) default NULL COMMENT "Where to point target agent", + `last_err` text, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_cs`) REFERENCES `tcredential_store`(`identifier`) + ON UPDATE CASCADE ON DELETE SET NULL, + FOREIGN KEY (`id_os`) REFERENCES `tconfig_os`(`id_os`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`target_agent_version_id`) REFERENCES `tagent_repository`(`id`) + ON UPDATE CASCADE ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/pandora_console/general/firts_task/recon_view.php b/pandora_console/general/firts_task/recon_view.php index 282a6b75be..8c59b23f64 100755 --- a/pandora_console/general/firts_task/recon_view.php +++ b/pandora_console/general/firts_task/recon_view.php @@ -35,6 +35,7 @@ ui_require_css_file('firts_task');

+ diff --git a/pandora_console/general/footer.php b/pandora_console/general/footer.php index b35123b5d3..dcc894989b 100644 --- a/pandora_console/general/footer.php +++ b/pandora_console/general/footer.php @@ -20,6 +20,8 @@ if (isset($_SERVER['REQUEST_TIME'])) { $time = get_system_time(); } +ui_require_css_file('footer'); + $license_file = 'general/license/pandora_info_'.$config['language'].'.html'; if (! file_exists($config['homedir'].$license_file)) { $license_file = 'general/license/pandora_info_en.html'; @@ -41,9 +43,17 @@ if ($current_package == 0) { $build_package_version = $current_package; } -echo sprintf(__('%s %s - Build %s - MR %s', get_product_name(), $pandora_version, $build_package_version, $config['MR'])); +echo __( + '%s %s - Build %s - MR %s', + get_product_name(), + $pandora_version, + $build_package_version, + $config['MR'] +); +echo '
'; +echo ''.__('Page generated on %s', date('Y-m-d H:i:s')).''; + -echo ' '; if (isset($config['debug'])) { $cache_info = []; diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index a093596b2b..99bb38cc21 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -670,21 +670,49 @@ if ($config['menu_type'] == 'classic') { + + var autorefresh_draw = ''; $("#header_autorefresh").css('padding-right', '5px'); - var refr_time = ; - var t = new Date(); - t.setTime (t.getTime () + parseInt()); - $("#refrcounter").countdown ({ - until: t, - layout: '%M%nn%M:%S%nn%S', - labels: ['', '', '', '', '', '', ''], - onExpiry: function () { + if(autorefresh_draw == true) { + var refresh_interval = parseInt(''); + var until_time=''; + + function events_refresh() { + until_time = new Date(); + until_time.setTime (until_time.getTime () + parseInt()); + + $("#refrcounter").countdown ({ + until: until_time, + layout: '%M%nn%M:%S%nn%S', + labels: ['', '', '', '', '', '', ''], + onExpiry: function () { + dt_events.draw(false); + } + }); + } + // Start the countdown when page is loaded (first time). + events_refresh(); + // Repeat countdown according to refresh_interval. + setInterval(events_refresh, refresh_interval); + } else { + var refr_time = ; + var t = new Date(); + t.setTime (t.getTime () + parseInt()); + $("#refrcounter").countdown ({ + until: t, + layout: '%M%nn%M:%S%nn%S', + labels: ['', '', '', '', '', '', ''], + onExpiry: function () { href = $("a.autorefresh").attr ("href"); href = href + refr_time; $(document).attr ("location", href); } }); + } @@ -694,8 +722,38 @@ if ($config['menu_type'] == 'classic') { $("#combo_refr").toggle (); $("select#ref").change (function () { href = $("a.autorefresh").attr ("href"); - $(document).attr ("location", href + this.value); - }); + + if(autorefresh_draw == true){ + inputs = $("#events_form :input"); + values = {}; + inputs.each(function() { + values[this.name] = $(this).val(); + }) + + var newValue = btoa(JSON.stringify(values)); + + var fb64 = ''; + // Check if the filters have changed. + if(fb64 !== newValue){ + href = href.replace(fb64, newValue); + } + + $(document).attr("location", href+ '&refr=' + this.value); + + $(document).attr("location", href+'&fb64=' + newValue + '&refr=' + this.value); + + } else { + $(document).attr ("location", href + this.value); + } + }); return false; }); diff --git a/pandora_console/general/login_page.php b/pandora_console/general/login_page.php index 86dccfa53a..5aecfcc92c 100755 --- a/pandora_console/general/login_page.php +++ b/pandora_console/general/login_page.php @@ -19,8 +19,8 @@ if (isset($config['homedir'])) { ui_require_css_file('login'); -require_once $homedir.'include/functions_ui.php'; -require_once $homedir.'include/functions.php'; +require_once __DIR__.'/../include/functions_ui.php'; +require_once __DIR__.'/../include/functions.php'; require_once __DIR__.'/../include/functions_html.php'; @@ -376,6 +376,9 @@ if (isset($correct_reset_pass_process)) { } if (isset($login_failed)) { + $nick = get_parameter_post('nick'); + $fails = db_get_value('failed_attempt', 'tusuario', 'id_user', $nick); + $attemps = ($config['number_attempts'] - $fails); echo '
'; echo '
'; echo '
'; @@ -386,6 +389,12 @@ if (isset($login_failed)) { echo '

'.__('ERROR').'

'; echo '

'.$config['auth_error'].'

'; echo '
'; + if ($config['enable_pass_policy']) { + echo '
'; + echo '

Remaining attempts: '.$attemps.'

'; + echo '
'; + } + echo '
'; html_print_submit_button('Ok', 'hide-login-error', false); echo '
'; @@ -518,6 +527,7 @@ if ($login_screen == 'error_authconfig' || $login_screen == 'error_emptyconfig' ui_require_css_file('dialog'); ui_require_css_file('jquery-ui.min', 'include/styles/js/'); ui_require_jquery_file('jquery-ui.min'); +ui_require_jquery_file('jquery-ui_custom'); ?> 'forced_title_layer', 'class' => 'forced_title_layer', ' $("#final_process_correct").dialog('close'); }); }); + /* ]]> */ diff --git a/pandora_console/general/logon_ok.php b/pandora_console/general/logon_ok.php index 649a2d2f68..cdbc09c9f9 100644 --- a/pandora_console/general/logon_ok.php +++ b/pandora_console/general/logon_ok.php @@ -103,199 +103,205 @@ if (!empty($all_data)) { $data['server_sanity'] = format_numeric((100 - $data['module_sanity']), 1); } +ui_require_css_file('logon'); -?> -
".__('Pandora status info').'
- - - - - - - -
- - - class = 'databox'; - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->head = []; - $table->data = []; - $table->headstyle[0] = 'text-align:center;'; - $table->width = '100%'; - $table->head[0] = ''.__('%s Overview', get_product_name()).''; - $table->head_colspan[0] = 4; +echo '
'; - // Indicators. - $tdata = []; - $stats = reporting_get_stats_indicators($data, 120, 10, false); - $status = ''; - foreach ($stats as $stat) { - $status .= ''; - } +// +// Overview Table. +// +$table = new stdClass(); +$table->class = 'no-class'; +$table->cellpadding = 4; +$table->cellspacing = 4; +$table->head = []; +$table->data = []; +$table->headstyle[0] = 'text-align:center;'; +$table->width = '100%'; +$table->head_colspan[0] = 4; - $status .= '
'.$stat['title'].''.$stat['graph'].'
'; - $table->data[0][0] = $status; - $table->rowclass[] = ''; +// Indicators. +$tdata = []; +$stats = reporting_get_stats_indicators($data, 120, 10, false); +$status = ''; +foreach ($stats as $stat) { + $status .= ''; +} - $table->data[] = $tdata; +$status .= '
'.$stat['title'].''.$stat['graph'].'
'; +$table->data[0][0] = $status; +$table->rowclass[] = ''; - // Alerts. - $tdata = []; - $tdata[0] = reporting_get_stats_alerts($data); - $table->rowclass[] = ''; - $table->data[] = $tdata; +$table->data[] = $tdata; - // Modules by status. - $tdata = []; - $tdata[0] = reporting_get_stats_modules_status($data, 180, 100); - $table->rowclass[] = ''; - $table->data[] = $tdata; +// Alerts. +$tdata = []; +$tdata[0] = reporting_get_stats_alerts($data); +$table->rowclass[] = ''; +$table->data[] = $tdata; - // Total agents and modules. - $tdata = []; - $tdata[0] = reporting_get_stats_agents_monitors($data); - $table->rowclass[] = ''; - $table->data[] = $tdata; +// Modules by status. +$tdata = []; +$tdata[0] = reporting_get_stats_modules_status($data, 180, 100); +$table->rowclass[] = ''; +$table->data[] = $tdata; - // Users. - if (users_is_admin()) { - $tdata = []; - $tdata[0] = reporting_get_stats_users($data); - $table->rowclass[] = ''; - $table->data[] = $tdata; - } +// Total agents and modules. +$tdata = []; +$tdata[0] = reporting_get_stats_agents_monitors($data); +$table->rowclass[] = ''; +$table->data[] = $tdata; - html_print_table($table); - unset($table); - ?> - - -
- - - rowclass[] = ''; + $table->data[] = $tdata; +} + +ui_toggle( + html_print_table($table, true), + __('%s Overview', get_product_name()), + '', + 'overview', + false +); +unset($table); + +echo '
+ + $data[0] = ''.$session_id_usuario.''; + $data[1] = ui_print_session_action_icon($session['accion'], true).' '.$session['accion']; + $data[2] = ui_print_help_tip( + date($config['date_format'], $session['utimestamp']), + true + ).human_time_comparation($session['utimestamp'], 'tiny'); + $data[3] = $session_ip_origen; + $description = str_replace([',', ', '], ', ', $session['descripcion']); + if (strlen($description) > 100) { + $data[4] = '
'.io_safe_output(substr($description, 0, 150).'...').'
'; + } else { + $data[4] = '
'.io_safe_output($description).'
'; + } + + array_push($table->data, $data); +} + +$activity .= html_print_table($table, true); +unset($table); + +ui_toggle( + $activity, + __('Latest activity'), + '', + 'activity', + false, + false, + '', + 'white-box-content padded' +); +// END OF LAST ACTIVIYY. +// Close right panel. +echo '
'; + +// Close welcome panel. +echo '
'; diff --git a/pandora_console/general/main_menu.php b/pandora_console/general/main_menu.php index 877f171090..ca6c0fd473 100644 --- a/pandora_console/general/main_menu.php +++ b/pandora_console/general/main_menu.php @@ -30,12 +30,6 @@ $(document).ready(function(){ } }); - -// Set the height of the menu. -$(window).on('load', function (){ - $("#menu_full").height($("#container").height()); -}); - + + + + + + +
+ +
+ images/input_cross.png'> +
+ +
+
+ +
+ +
+
'; + echo __('Please make sure you have SAML authentication properly configured. For more information the error to access this page are recorded in security logs of %s System Database', get_product_name()); + ?> + +
+ +
+ OK +
+
+
+ +
+ + + + + diff --git a/pandora_console/general/register.php b/pandora_console/general/register.php index e6a26bb250..b1d58aada4 100644 --- a/pandora_console/general/register.php +++ b/pandora_console/general/register.php @@ -122,7 +122,6 @@ if (is_ajax()) { exit(); } - ui_require_css_file('register'); $initial = isset($config['initial_wizard']) !== true @@ -150,26 +149,27 @@ if ($initial && users_is_admin()) { ); } -if ($registration && users_is_admin()) { - // Prepare registration wizard, not launch. leave control to flow. - registration_wiz_modal( - false, - // Launch only if not being launch from 'initial'. - !$initial, - (($show_newsletter === true) ? 'force_run_newsletter()' : null) - ); -} else { - if ($show_newsletter) { - // Show newsletter wizard for current user. - newsletter_wiz_modal( +if (!$config['disabled_newsletter']) { + if ($registration && users_is_admin()) { + // Prepare registration wizard, not launch. leave control to flow. + registration_wiz_modal( false, - // Launch only if not being call from 'registration'. - !$registration && !$initial + // Launch only if not being launch from 'initial'. + !$initial, + (($show_newsletter === true) ? 'force_run_newsletter()' : null) ); + } else { + if ($show_newsletter) { + // Show newsletter wizard for current user. + newsletter_wiz_modal( + false, + // Launch only if not being call from 'registration'. + !$registration && !$initial + ); + } } } - $newsletter = null; ?> diff --git a/pandora_console/godmode/admin_access_logs.php b/pandora_console/godmode/admin_access_logs.php index 67a933d8cb..112a45754f 100644 --- a/pandora_console/godmode/admin_access_logs.php +++ b/pandora_console/godmode/admin_access_logs.php @@ -94,7 +94,7 @@ $table->data[1] = $data; $form = '
'; $form .= html_print_table($table, true); $form .= '
'; -ui_toggle($form, __('Filter'), '', false); +ui_toggle($form, __('Filter'), '', '', false); $filter = '1=1'; diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index dfdd7390c3..6ee2343fc0 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -77,6 +77,7 @@ if (is_ajax()) { } $get_modules_json_for_multiple_snmp = (bool) get_parameter('get_modules_json_for_multiple_snmp', 0); + $get_common_modules = (bool) get_parameter('get_common_modules', 1); if ($get_modules_json_for_multiple_snmp) { include_once 'include/graphs/functions_utils.php'; @@ -100,7 +101,16 @@ if (is_ajax()) { if ($out === false) { $out = $oid_snmp; } else { - $out = array_intersect($out, $oid_snmp); + $commons = array_intersect($out, $oid_snmp); + if ($get_common_modules) { + // Common modules is selected (default) + $out = $commons; + } else { + // All modules is selected + $array1 = array_diff($out, $oid_snmp); + $array2 = array_diff($oid_snmp, $out); + $out = array_merge($commons, $array1, $array2); + } } $oid_snmp = []; @@ -176,7 +186,7 @@ if ($disk_conf_delete) { @unlink($filename['conf']); } -echo '
'; +echo ''; // Custom ID. $custom_id_div = '
'; @@ -201,7 +211,7 @@ if (!$new_agent && $alias != '') { $table_agent_name .= '
'; if ($id_agente) { - $table_agent_name .= ''; + $table_agent_name .= ''; $table_agent_name .= ''; $table_agent_name .= html_print_image( 'images/zoom.png', @@ -245,7 +255,7 @@ if (!$new_agent && $alias != '') { $table_agent_name .= '
'; // QR code div. - $table_qr_code = '
'; + $table_qr_code = '
'; $table_qr_code .= '

'.__('QR Code Agent view').':

'; $table_qr_code .= '
'; if ($id_agente) { @@ -372,13 +382,13 @@ $table_server = '

'.__('Server') $table_server .= '

'; if ($new_agent) { // Set first server by default. - $servers_get_names = servers_get_names(); + $servers_get_names = $servers; $array_keys_servers_get_names = array_keys($servers_get_names); $server_name = reset($array_keys_servers_get_names); } $table_server .= html_print_select( - servers_get_names(), + $servers, 'server_name', $server_name, '', @@ -401,7 +411,7 @@ $table_description .= html_print_textarea( // QR code. echo '
-
+
'.$table_agent_name.$table_alias.$table_ip.$table_primary_group.'
'.$table_interval.$table_os.$table_server.$table_description.'
'; @@ -413,8 +423,8 @@ echo '
'; if (enterprise_installed()) { $secondary_groups_selected = enterprise_hook('agents_get_secondary_groups', [$id_agente]); - $table_adv_secondary_groups = '

'.__('Secondary groups').':

'; - $table_adv_secondary_groups_left = html_print_select_groups( + $adv_secondary_groups_label = '

'.__('Secondary groups').':

'; + $adv_secondary_groups_left = html_print_select_groups( false, // Use the current user to select the groups. 'AR', @@ -441,7 +451,7 @@ if (enterprise_installed()) { // CSS classnames (default). false, // Not disabled (default). - 'width:50%; min-width:170px;', + 'min-width:170px;', // Inline styles (default). false, // Option style select (default). @@ -455,7 +465,7 @@ if (enterprise_installed()) { // Do not show the primary group in this selection. ); - $table_adv_secondary_groups_arrows = html_print_input_image( + $adv_secondary_groups_arrows = html_print_input_image( 'add_secondary', 'images/darrowright_green.png', 1, @@ -479,7 +489,7 @@ if (enterprise_installed()) { ] ); - $table_adv_secondary_groups_right .= html_print_select( + $adv_secondary_groups_right .= html_print_select( $secondary_groups_selected['for_select'], // Values. 'secondary_groups_selected', @@ -502,7 +512,7 @@ if (enterprise_installed()) { // Class. false, // Disabled. - 'width:50%; min-width:170px;' + 'min-width:170px;' // Style. ); @@ -514,8 +524,10 @@ if (enterprise_installed()) { ); $safe_mode_modules = []; $safe_mode_modules[0] = __('Any'); - foreach ($sql_modules as $m) { - $safe_mode_modules[$m['id_module']] = $m['name']; + if (is_array($sql_modules)) { + foreach ($sql_modules as $m) { + $safe_mode_modules[$m['id_module']] = $m['name']; + } } $table_adv_safe = '

'.__('Safe operation mode').': '.ui_print_help_tip( @@ -579,7 +591,7 @@ if (enterprise_installed()) { } -$table_adv_parent = '

'.__('Parent').':

'; +$table_adv_parent = '
'; $params = []; $params['return'] = true; $params['show_helptip'] = true; @@ -648,13 +660,15 @@ $table_adv_module_mode .= html_print_radio_button_extended( $table_adv_module_mode .= '
'; // Status (Disabled / Enabled). -$table_adv_status = '

'.__('Disabled').': '.ui_print_help_tip(__('If the remote configuration is enabled, it will also go into standby mode when disabling it.'), true).'

'; +$table_adv_status = '
'; $table_adv_status .= html_print_checkbox_switch( 'disabled', 1, $disabled, true -).'
'; +); +$table_adv_status .= '

'.__('Disabled').': '.ui_print_help_tip(__('If the remote configuration is enabled, it will also go into standby mode when disabling it.'), true).'

'; +$table_adv_status .= '
'; // Url address. if (enterprise_installed()) { @@ -665,7 +679,14 @@ if (enterprise_installed()) { '', 45, 255, - true + true, + false, + false, + '', + '', + '', + // Autocomplete. + 'new-password' ).'
'; } else { $table_adv_url = '

'.__('Url address').':

'; @@ -679,9 +700,11 @@ if (enterprise_installed()) { ).'
'; } -$table_adv_quiet = '

'.__('Quiet').': '; +$table_adv_quiet = '

'; +$table_adv_quiet .= html_print_checkbox_switch('quiet', 1, $quiet, true); +$table_adv_quiet .= '

'.__('Quiet').': '; $table_adv_quiet .= ui_print_help_tip(__('The agent still runs but the alerts and events will be stop'), true).'

'; -$table_adv_quiet .= html_print_checkbox_switch('quiet', 1, $quiet, true).'
'; +$table_adv_quiet .= '
'; $listIcons = gis_get_array_list_icons(); @@ -753,33 +776,48 @@ if ($config['activate_gis']) { // General display distribution. -$table_adv_options = $table_adv_secondary_groups.'
-
- '.$table_adv_secondary_groups_left.' +$table_adv_options = ' +
+ '.$adv_secondary_groups_label.' +
+ '.$adv_secondary_groups_left.' +
+
+ '.$adv_secondary_groups_arrows.' +
+
+ '.$adv_secondary_groups_right.' +
-
- '.$table_adv_secondary_groups_arrows.' -
-
- '.$table_adv_secondary_groups_right.' -
-
-
-
'.$table_adv_parent.$table_adv_module_mode.$table_adv_cascade; +
+ '.$table_adv_parent.$table_adv_module_mode.$table_adv_cascade; if ($new_agent) { // If agent is new, show custom id as old style format. $table_adv_options .= $custom_id_div; } -$table_adv_options .= $table_adv_gis.'
-
'.$table_adv_agent_icon.$table_adv_url.$table_adv_quiet.$table_adv_status.$table_adv_remote.$table_adv_safe.'
-
'; +$table_adv_options .= '
'; -echo '
'; - ui_toggle($table_adv_options, __('Advanced options'), '', true, false, 'white_box white_box_opened'); -echo '
'; +$table_adv_options .= ' +
+ '.$table_adv_gis.$table_adv_agent_icon.$table_adv_url.$table_adv_quiet.$table_adv_status.$table_adv_remote.$table_adv_safe.' +
'; +if (enterprise_installed()) { + echo '
'; + ui_toggle( + $table_adv_options, + __('Advanced options'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border flex' + ); + echo '
'; +} $table = new stdClass(); $table->width = '100%'; @@ -787,7 +825,7 @@ $table->class = 'custom_fields_table'; $table->head = [ 0 => __('Click to display').ui_print_help_tip( - __('This field allows url insertion using the BBCode\'s url tag').'.
'.__('The format is: [url=\'url to navigate\']\'text to show\'[/url]').'.

'.__('e.g.: [url=google.com]Google web search[/url]'), + __('This field allows url insertion using the BBCode\'s url tag').'.
'.__('The format is: [url=\'url to navigate\']\'text to show\'[/url] or [url]\'url to navigate\'[/url] ').'.

'.__('e.g.: [url=google.com]Google web search[/url] or [url]www.goole.com[/url]'), true ), ]; @@ -831,7 +869,7 @@ foreach ($fields as $field) { $custom_value = ''; } - $table->rowstyle[$i] = 'cursor: pointer;'; + $table->rowstyle[$i] = 'cursor: pointer;user-select: none;'; if (!empty($custom_value)) { $table->rowstyle[($i + 1)] = 'display: table-row;'; } else { @@ -893,16 +931,48 @@ foreach ($fields as $field) { $i += 2; } -if (!empty($fields)) { +if (enterprise_installed()) { + if (!empty($fields)) { + echo '
'; + ui_toggle( + html_print_table($table, true), + __('Custom fields'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border' + ); + echo '
'; + } +} else { echo '
'; - ui_toggle( - html_print_table($table, true), - __('Custom fields'), - '', - true, - false, - 'white_box white_box_opened' - ); + ui_toggle( + $table_adv_options, + __('Advanced options'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border flex' + ); + if (!empty($fields)) { + ui_toggle( + html_print_table($table, true), + __('Custom fields'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border' + ); + } + + echo '
'; + echo '
'; } @@ -1134,6 +1204,19 @@ ui_require_jquery_file('bgiframe'); } $(document).ready (function() { + + var previous_primary_group_select; + $("#grupo").on('focus', function () { + previous_primary_group_select = this.value; + }).change(function() { + if ($("#secondary_groups_selected option[value="+$("#grupo").val()+"]").length) { + alert(""); + $("#grupo").val(previous_primary_group_select); + } else { + previous_primary_group_select = this.value; + } + }); + $("select#id_os").pandoraSelectOS (); var checked = $("#checkbox-cascade_protection").is(":checked"); @@ -1182,7 +1265,7 @@ ui_require_jquery_file('bgiframe'); 128, 128 ); - $("#text-agente").prop('disabled', true); + $("#text-agente").prop('readonly', true); }); diff --git a/pandora_console/godmode/agentes/agent_wizard.snmp_interfaces_explorer.php b/pandora_console/godmode/agentes/agent_wizard.snmp_interfaces_explorer.php index 5730fea501..3eb404340e 100644 --- a/pandora_console/godmode/agentes/agent_wizard.snmp_interfaces_explorer.php +++ b/pandora_console/godmode/agentes/agent_wizard.snmp_interfaces_explorer.php @@ -1,16 +1,32 @@ ] => [] array + // Build a [] => [] array. if (!empty($snmp_int_ip)) { foreach ($snmp_int_ip as $key => $value) { - // The key is something like IP-MIB::ipAddressIfIndex.ipv4."" - // or IP-MIB::ipAddressIfIndex.ipv6."" - // The value is something like INTEGER: + // The key is something like IP-MIB::ipAddressIfIndex.ipv4."". + // or IP-MIB::ipAddressIfIndex.ipv6."". + // The value is something like INTEGER: . $data = explode(': ', $value); $interface_id = !empty($data) && isset($data[1]) ? $data[1] : false; @@ -111,7 +126,7 @@ if ($snmpwalk) { $interface_ip = $matches[1]; } - // Get the first ip + // Get the first ip. if ($interface_id !== false && !empty($interface_ip) && !isset($interfaces_ip[$interface_id])) { $interfaces_ip[$interface_id] = $interface_ip; } @@ -120,17 +135,17 @@ if ($snmpwalk) { unset($snmp_int_ip); } - $snmpis = array_merge(($snmpis === false ? [] : $snmpis), ($ifxitems === false ? [] : $ifxitems)); + $snmpis = array_merge((($snmpis === false) ? [] : $snmpis), (($ifxitems === false) ? [] : $ifxitems)); $interfaces = []; - // We get here only the interface part of the MIB, not full mib + // We get here only the interface part of the MIB, not full mib. foreach ($snmpis as $key => $snmp) { $data = explode(': ', $snmp, 2); $keydata = explode('::', $key); $keydata2 = explode('.', $keydata[1]); - // Avoid results without index and interfaces without name + // Avoid results without index and interfaces without name. if (!isset($keydata2[1]) || !isset($data[1])) { continue; } @@ -240,24 +255,22 @@ if ($create_modules) { $oid_array[(count($oid_array) - 1)] = $id; $oid = implode('.', $oid_array); - // Get the name + // Get the name. $name_array = explode('::', $oid_array[0]); $name = $ifname.'_'.$name_array[1]; - // Clean the name + // Clean the name. $name = str_replace('"', '', $name); - // Proc moduletypes + // Proc moduletypes. if (preg_match('/Status/', $name_array[1])) { $module_type = 18; } else if (preg_match('/Present/', $name_array[1])) { $module_type = 18; } else if (preg_match('/PromiscuousMode/', $name_array[1])) { $module_type = 18; - } - - // String moduletypes - else if (preg_match('/Alias/', $name_array[1])) { + } else if (preg_match('/Alias/', $name_array[1])) { + // String moduletypes. $module_type = 17; } else if (preg_match('/Address/', $name_array[1])) { $module_type = 17; @@ -267,15 +280,11 @@ if ($create_modules) { $module_type = 17; } else if (preg_match('/Descr/', $name_array[1])) { $module_type = 17; - } - - // Specific counters (ends in s) - else if (preg_match('/s$/', $name_array[1])) { + } else if (preg_match('/s$/', $name_array[1])) { + // Specific counters (ends in s). $module_type = 16; - } - - // Otherwise, numeric - else { + } else { + // Otherwise, numeric. $module_type = 15; } @@ -322,7 +331,7 @@ if ($create_modules) { } else if (preg_match('/ifAdminStatus/', $name_array[1])) { $module_type = 2; } else if (preg_match('/ifOperStatus/', $name_array[1])) { - $module_type = 18; + $module_type = 2; } else { $module_type = 4; } @@ -331,7 +340,7 @@ if ($create_modules) { $output_oid = ''; - exec('ssh pandora_exec_proxy@'.$row['ip_address'].' snmptranslate -On '.$oid, $output_oid, $rc); + exec('snmptranslate -On '.$oid, $output_oid, $rc); $conf_oid = $output_oid[0]; $oid = $conf_oid; @@ -398,7 +407,9 @@ if ($create_modules) { } if ($done > 0) { - ui_print_success_message(__('Successfully modules created')." ($done)"); + ui_print_success_message( + __('Successfully modules created').' ('.$done.')' + ); } if (!empty($errors)) { @@ -408,17 +419,17 @@ if ($create_modules) { foreach ($errors as $code => $number) { switch ($code) { case ERR_EXIST: - $msg .= '
'.__('Another module already exists with the same name')." ($number)"; + $msg .= '
'.__('Another module already exists with the same name').' ('.$number.')'; break; case ERR_INCOMPLETE: - $msg .= '
'.__('Some required fields are missed').': ('.__('name').') '." ($number)"; + $msg .= '
'.__('Some required fields are missed').': ('.__('name').') ('.$number.')'; break; case ERR_DB: case ERR_GENERIC: default: - $msg .= '
'.__('Processing error')." ($number)"; + $msg .= '
'.__('Processing error').' ('.$number.')'; break; } } @@ -427,10 +438,10 @@ if ($create_modules) { } } -// Create the interface list for the interface +// Create the interface list for the interface. $interfaces_list = []; foreach ($interfaces as $interface) { - // Get the interface name, removing " " characters and avoid "blank" interfaces + // Get the interface name, removing " " characters and avoid "blank" interfaces. if (isset($interface['ifDescr']) && $interface['ifDescr']['value'] != '') { $ifname = $interface['ifDescr']['value']; } else if (isset($interface['ifName']) && $interface['ifName']['value'] != '') { @@ -443,7 +454,7 @@ foreach ($interfaces as $interface) { } echo ''; -echo ""; +echo ""; $table->width = '100%'; $table->cellpadding = 0; @@ -465,10 +476,15 @@ if (enterprise_installed()) { enterprise_include_once('include/functions_satellite.php'); $rows = get_proxy_servers(); + + // Check if satellite server has remote configuration enabled. + $satellite_remote = config_agents_has_remote_configuration($id_agent); + foreach ($rows as $row) { if ($row['server_type'] != 13) { $s_type = ' (Standard)'; } else { + $id_satellite = $row['id_server']; $s_type = ' (Satellite)'; } @@ -477,7 +493,16 @@ if (enterprise_installed()) { } $table->data[1][2] = ''.__('Server to execute command').''; -$table->data[1][3] = html_print_select($servers_to_exec, 'server_to_exec', $server_to_exec, '', '', '', true); +$table->data[1][2] .= ''.ui_print_help_tip(__('In order to use remote executions you need to enable remote execution in satellite server'), true, 'images/tip_help.png', false, 'display:').''; +$table->data[1][4] = html_print_select( + $servers_to_exec, + 'server_to_exec', + $server_to_exec, + 'satellite_remote_warn('.$id_satellite.','.$satellite_remote.')', + '', + '', + true +); $snmp_versions['1'] = 'v. 1'; $snmp_versions['2'] = 'v. 2'; @@ -497,7 +522,7 @@ html_print_table($table); unset($table); -// SNMP3 OPTIONS +// SNMP3 OPTIONS. $table->width = '100%'; $table->data[2][1] = ''.__('Auth user').''; @@ -552,7 +577,7 @@ echo ''; if (!empty($interfaces_list)) { echo ''; - echo "
"; + echo ""; echo ''; $id_snmp_serialize = serialize_in_temp($interfaces, $config['id_user'].'_snmp'); @@ -577,13 +602,30 @@ if (!empty($interfaces_list)) { $table->width = '100%'; - // Agent selector + // Agent selector. $table->data[0][0] = ''.__('Interfaces').''; $table->data[0][1] = ''; $table->data[0][2] = ''.__('Modules').''; $table->data[1][0] = html_print_select($interfaces_list, 'id_snmp[]', 0, false, '', '', true, true, true, '', false, 'width:500px; overflow: auto;'); - $table->data[1][1] = html_print_image('images/darrowright.png', true); + + $table->data[1][1] = __('When selecting interfaces'); + $table->data[1][1] .= '
'; + $table->data[1][1] .= html_print_select( + [ + 1 => __('Show common modules'), + 0 => __('Show all modules'), + ], + 'modules_selection_mode', + 1, + false, + '', + '', + true, + false, + false + ); + $table->data[1][2] = html_print_select([], 'module[]', 0, false, '', 0, true, true, true, '', false, 'width:200px;'); $table->data[1][2] .= html_print_input_hidden('agent', $id_agent, true); @@ -608,11 +650,13 @@ ui_require_jquery_file('bgiframe'); $(document).ready (function () { var inputActive = true; - + + $('#server_to_exec option').trigger('change'); + $(document).data('text_for_module', $("#none_text").html()); - + $("#id_snmp").change(snmp_changed_by_multiple_snmp); - + $("#snmp_version").change(function () { if (this.value == "3") { $("#snmp3_options").css("display", ""); @@ -621,28 +665,36 @@ $(document).ready (function () { $("#snmp3_options").css("display", "none"); } }); - + $("#walk_form").submit(function() { $("#submit-snmp_walk").disable (); $("#oid_loading").show (); $("#no_snmp").hide (); $("#form_interfaces").hide (); }); + + // When select interfaces changes + $("#modules_selection_mode").change (function() { + $("#id_snmp").trigger('change'); + }); + }); function snmp_changed_by_multiple_snmp (event, id_snmp, selected) { var idSNMP = Array(); - + var get_common_modules = $("#modules_selection_mode option:selected").val(); + jQuery.each ($("#id_snmp option:selected"), function (i, val) { idSNMP.push($(val).val()); }); $('#module').attr ('disabled', 1); $('#module').empty (); $('#module').append ($('').html ("Loading...").attr ("value", 0)); - - jQuery.post ('ajax.php', + + jQuery.post ('ajax.php', {"page" : "godmode/agentes/agent_manager", "get_modules_json_for_multiple_snmp": 1, + "get_common_modules" : get_common_modules, "id_snmp[]": idSNMP, "id_snmp_serialize": $("#hidden-id_snmp_serialize").val() }, @@ -655,7 +707,7 @@ function snmp_changed_by_multiple_snmp (event, id_snmp, selected) { $('#module').fadeIn ('normal'); c++; }); - + if (c == 0) { if (typeof($(document).data('text_for_module')) != 'undefined') { $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); @@ -666,11 +718,11 @@ function snmp_changed_by_multiple_snmp (event, id_snmp, selected) { } else { var anyText = $("#any_text").html(); //Trick for catch the translate text. - + if (anyText == null) { anyText = 'Any'; } - + $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); } } @@ -682,6 +734,20 @@ function snmp_changed_by_multiple_snmp (event, id_snmp, selected) { "json"); } + +function satellite_remote_warn(id_satellite, remote) +{ + if(!remote) + { + $('#server_to_exec option[value='+id_satellite+']').prop('disabled', true); + $('#satellite_remote_tip').removeAttr("style").show(); + } + else + { + $('#satellite_remote_tip').removeAttr("style").hide(); + } + +} + /* ]]> */ - diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index 22410b0e23..22a3d46eaa 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -1213,7 +1213,7 @@ if ($update_module || $create_module) { $max_timeout = (int) get_parameter('max_timeout'); $max_retries = (int) get_parameter('max_retries'); - $min = (int) get_parameter_post('min'); + $min = (int) get_parameter('min'); $max = (int) get_parameter('max'); $interval = (int) get_parameter('module_interval', $intervalo); $ff_interval = (int) get_parameter('module_ff_interval'); @@ -1276,18 +1276,10 @@ if ($update_module || $create_module) { $m_hide = $m['hide']; } - if ($update_module) { - if ($m_hide == '1') { - $macros[$k]['value'] = io_input_password(get_parameter($m['macro'], '')); - } else { - $macros[$k]['value'] = get_parameter($m['macro'], ''); - } + if ($m_hide == '1') { + $macros[$k]['value'] = io_input_password(get_parameter($m['macro'], '')); } else { - if ($m_hide == '1') { - $macros[$k]['value'] = io_input_password($macros_names[$k]); - } else { - $macros[$k]['value'] = $macros_names[$k]; - } + $macros[$k]['value'] = get_parameter($m['macro'], ''); } } @@ -1366,7 +1358,11 @@ if ($update_module || $create_module) { $parent_module_id = (int) get_parameter('parent_module_id'); $ip_target = (string) get_parameter('ip_target'); - if ($ip_target == '') { + // No autofill if the module is a webserver module. + if ($ip_target == '' + && $id_module_type < MODULE_WEBSERVER_CHECK_LATENCY + && $id_module_type > MODULE_WEBSERVER_RETRIEVE_STRING_DATA + ) { $ip_target = 'auto'; } @@ -1567,8 +1563,14 @@ if ($update_module) { foreach ($plugin_parameter_split as $key => $value) { if ($key == 1) { - $values['plugin_parameter'] .= 'http_auth_user '.$http_user.' '; - $values['plugin_parameter'] .= 'http_auth_pass '.$http_pass.' '; + if ($http_user) { + $values['plugin_parameter'] .= 'http_auth_user '.$http_user.' '; + } + + if ($http_pass) { + $values['plugin_parameter'] .= 'http_auth_pass '.$http_pass.' '; + } + $values['plugin_parameter'] .= $value.' '; } else { $values['plugin_parameter'] .= $value.' '; @@ -1765,8 +1767,14 @@ if ($create_module) { foreach ($plugin_parameter_split as $key => $value) { if ($key == 1) { - $values['plugin_parameter'] .= 'http_auth_user '.$http_user.' '; - $values['plugin_parameter'] .= 'http_auth_pass '.$http_pass.' '; + if ($http_user) { + $values['plugin_parameter'] .= 'http_auth_user '.$http_user.' '; + } + + if ($http_pass) { + $values['plugin_parameter'] .= 'http_auth_pass '.$http_pass.' '; + } + $values['plugin_parameter'] .= $value.' '; } else { $values['plugin_parameter'] .= $value.' '; @@ -2103,8 +2111,7 @@ if ($delete_module) { } } -// MODULE DUPLICATION -// ==================. +// MODULE DUPLICATION. if (!empty($duplicate_module)) { // DUPLICATE agent module ! $id_duplicate_module = $duplicate_module; @@ -2150,8 +2157,46 @@ if (!empty($duplicate_module)) { } } -// UPDATE GIS -// ==========. +// MODULE ENABLE/DISABLE. +if ($enable_module) { + $result = modules_change_disabled($enable_module, 0); + $modulo_nombre = db_get_row_sql('SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = '.$enable_module.''); + $modulo_nombre = $modulo_nombre['nombre']; + + if ($result === NOERR) { + enterprise_hook('config_agents_enable_module_conf', [$id_agente, $enable_module]); + db_pandora_audit('Module management', 'Enable #'.$enable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } else { + db_pandora_audit('Module management', 'Fail to enable #'.$enable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } + + ui_print_result_message( + $result, + __('Successfully enabled'), + __('Could not be enabled') + ); +} + +if ($disable_module) { + $result = modules_change_disabled($disable_module, 1); + $modulo_nombre = db_get_row_sql('SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = '.$disable_module.''); + $modulo_nombre = $modulo_nombre['nombre']; + + if ($result === NOERR) { + enterprise_hook('config_agents_disable_module_conf', [$id_agente, $disable_module]); + db_pandora_audit('Module management', 'Disable #'.$disable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } else { + db_pandora_audit('Module management', 'Fail to disable #'.$disable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } + + ui_print_result_message( + $result, + __('Successfully disabled'), + __('Could not be disabled') + ); +} + +// UPDATE GIS. $updateGIS = get_parameter('update_gis', 0); if ($updateGIS) { $updateGisData = get_parameter('update_gis_data'); @@ -2239,8 +2284,11 @@ switch ($tab) { break; case 'alert': - // Because $id_agente is set, it will show only agent alerts. - // This var is for not display create button on alert list. + /* + * Because $id_agente is set, it will show only agent alerts + * This var is for not display create button on alert list + */ + $dont_display_alert_create_bttn = true; include 'godmode/alerts/alert_list.php'; break; diff --git a/pandora_console/godmode/agentes/modificar_agente.php b/pandora_console/godmode/agentes/modificar_agente.php index 0e08a3728f..a383de35c4 100644 --- a/pandora_console/godmode/agentes/modificar_agente.php +++ b/pandora_console/godmode/agentes/modificar_agente.php @@ -163,7 +163,7 @@ echo ''; echo __('Group').' '; $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AR') && !check_acl($config['id_user'], 0, 'AW')) { $return_all_group = false; } else { $return_all_group = true; @@ -443,6 +443,14 @@ ui_pagination($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modific if ($agents !== false) { // Urls to sort the table. + // Agent name size and description for Chinese and Japanese languages ​​are adjusted + $agent_font_size = '7'; + $description_font_size = '6.5'; + if ($config['language'] == 'ja' || $config['language'] == 'zh_CN' || $own_info['language'] == 'ja' || $own_info['language'] == 'zh_CN') { + $agent_font_size = '15'; + $description_font_size = '11'; + } + $url_up_agente = 'index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id='.$ag_group.'&recursion='.$recursion.'&search='.$search.'&os='.$os.'&offset='.$offset.'&sort_field=name&sort=up&disabled=$disabled'; $url_down_agente = 'index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id='.$ag_group.'&recursion='.$recursion.'&search='.$search.'&os='.$os.'&offset='.$offset.'&sort_field=name&sort=down&disabled=$disabled'; $url_up_remote = 'index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id='.$ag_group.'&recursion='.$recursion.'&search='.$search.'&os='.$os.'&offset='.$offset.'&sort_field=remote&sort=up&disabled=$disabled'; @@ -529,7 +537,7 @@ if ($agents !== false) { } else { echo '
".''.$agent['alias'].''.''; + id_agente=".$agent['id_agente']."'>".''.$agent['alias'].''.''; } echo ''; @@ -629,7 +637,7 @@ if ($agents !== false) { // Group icon and name echo "".ui_print_group_icon($agent['id_grupo'], true).''; // Description - echo "".ui_print_truncate_text($agent['comentarios'], 'description', true, true, true, '[…]', 'font-size: 6.5pt;').''; + echo "".ui_print_truncate_text($agent['comentarios'], 'description', true, true, true, '[…]', 'font-size: '.$description_font_size.'pt;').''; // Action // When there is only one element in page it's necesary go back page. if ((count($agents) == 1) && ($offset >= $config['block_size'])) { @@ -680,7 +688,7 @@ if ($agents !== false) { } echo ''; - ui_pagination($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset, 0, false, 'offset', true, 'pagination-bottom'); + ui_pagination($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&recursion=$recursion&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset); echo "
"; } else { ui_print_info_message(['no_close' => true, 'message' => __('There are no defined agents') ]); diff --git a/pandora_console/godmode/agentes/module_manager_editor.php b/pandora_console/godmode/agentes/module_manager_editor.php index cee4825faa..13c313892a 100644 --- a/pandora_console/godmode/agentes/module_manager_editor.php +++ b/pandora_console/godmode/agentes/module_manager_editor.php @@ -267,10 +267,10 @@ if ($id_agent_module) { $cron_interval = explode(' ', $module['cron_interval']); if (isset($cron_interval[4])) { $minute_from = $cron_interval[0]; - $min = explode('-', $minute_from); - $minute_from = $min[0]; - if (isset($min[1])) { - $minute_to = $min[1]; + $minute = explode('-', $minute_from); + $minute_from = $minute[0]; + if (isset($minute[1])) { + $minute_to = $minute[1]; } $hour_from = $cron_interval[1]; @@ -583,7 +583,13 @@ echo ''; // TODO: Change to the ui_print_error system echo ''; -html_print_table($table_simple); +ui_toggle( + html_print_table($table_simple, true), + __('Base options'), + '', + '', + false +); ui_toggle( html_print_table($table_advanced, true), diff --git a/pandora_console/godmode/agentes/module_manager_editor_common.php b/pandora_console/godmode/agentes/module_manager_editor_common.php index cb2f071e1c..ac110b0d6f 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_common.php +++ b/pandora_console/godmode/agentes/module_manager_editor_common.php @@ -78,6 +78,13 @@ function push_table_advanced($row, $id=false) function add_component_selection($id_network_component_type) { global $table_simple; + global $config; + + if ($config['style'] === 'pandora_black') { + $background_row = 'background-color: #444'; + } else { + $background_row = 'background-color: #cfcfcf'; + } $data = []; $data[0] = __('Using module component').' '; @@ -116,7 +123,7 @@ function add_component_selection($id_network_component_type) $data[1] .= ''; $table_simple->colspan['module_component'][1] = 3; - $table_simple->rowstyle['module_component'] = 'background-color: #cfcfcf'; + $table_simple->rowstyle['module_component'] = $background_row; prepend_table_simple($data, 'module_component'); } @@ -134,7 +141,9 @@ $largeClassDisabledBecauseInPolicy = ''; $page = get_parameter('page', ''); -if (strstr($page, 'policy_modules') === false && $id_agent_module) { +$in_policies_page = strstr($page, 'policy_modules'); + +if ($in_policies_page === false && $id_agent_module) { if ($config['enterprise_installed']) { if (policies_is_module_linked($id_agent_module) == 1) { $disabledBecauseInPolicy = 1; @@ -162,7 +171,7 @@ $edit_module = (bool) get_parameter_get('edit_module'); $table_simple = new stdClass(); $table_simple->id = 'simple'; $table_simple->width = '100%'; -$table_simple->class = 'databox'; +$table_simple->class = 'no-class'; $table_simple->data = []; $table_simple->style = []; $table_simple->style[0] = 'font-weight: bold; width: 25%;'; @@ -243,6 +252,12 @@ $table_simple->data[0][3] .= html_print_select_from_sql( $disabledBecauseInPolicy ); +if ((isset($id_agent_module) && $id_agent_module) || $id_policy_module != 0) { + $edit = false; +} else { + $edit = true; +} + $in_policy = strstr($page, 'policy_modules'); if (!$in_policy) { // Cannot select the current module to be itself parent @@ -273,17 +288,6 @@ if (!$in_policy) { $table_simple->data[2][0] = __('Type').' '.ui_print_help_icon($help_type, true, '', 'images/help_green.png', '', 'module_type_help'); $table_simple->data[2][0] .= html_print_input_hidden('id_module_type_hidden', $id_module_type, true); -if (isset($id_agent_module)) { - if ($id_agent_module) { - $edit = false; - } else { - $edit = true; - } -} else { - // Run into a policy - $edit = true; -} - if (!$edit) { $sql = sprintf( 'SELECT id_tipo, nombre @@ -637,7 +641,7 @@ if ($disabledBecauseInPolicy) { $table_advanced = new stdClass(); $table_advanced->id = 'advanced'; $table_advanced->width = '100%'; -$table_advanced->class = 'databox filters'; +$table_advanced->class = 'no-class'; $table_advanced->data = []; $table_advanced->style = []; $table_advanced->style[0] = $table_advanced->style[3] = $table_advanced->style[5] = 'font-weight: bold;'; @@ -1066,7 +1070,7 @@ if (check_acl($config['id_user'], 0, 'PM')) { $table_macros = new stdClass(); $table_macros->id = 'module_macros'; $table_macros->width = '100%'; -$table_macros->class = 'databox filters'; +$table_macros->class = 'no-class'; $table_macros->data = []; $table_macros->style = []; $table_macros->style[0] = 'font-weight: bold;'; @@ -1101,20 +1105,20 @@ $macro_count++; html_print_input_hidden('module_macro_count', $macro_count); -/* - Advanced form part */ -// Add relationships +// Advanced form part. +// Add relationships. $table_new_relations = new stdClass(); $table_new_relations->id = 'module_new_relations'; $table_new_relations->width = '100%'; -$table_new_relations->class = 'databox filters'; +$table_new_relations->class = 'no-class'; $table_new_relations->data = []; $table_new_relations->style = []; $table_new_relations->style[0] = 'width: 10%; font-weight: bold;'; $table_new_relations->style[1] = 'width: 25%; text-align: center;'; $table_new_relations->style[2] = 'width: 10%; font-weight: bold;'; $table_new_relations->style[3] = 'width: 25%; text-align: center;'; -$table_new_relations->style[4] = 'width: 30%; text-align: center;'; +$table_new_relations->style[4] = 'width: 10%; font-weight: bold;'; +$table_new_relations->style[5] = 'width: 25%; text-align: center;'; $table_new_relations->data[0][0] = __('Agent'); $params = []; @@ -1128,10 +1132,35 @@ $params['javascript_function_action_after_select_js_call'] = 'change_modules_aut $table_new_relations->data[0][1] = ui_print_agent_autocomplete_input($params); $table_new_relations->data[0][2] = __('Module'); $table_new_relations->data[0][3] = "
"; -$table_new_relations->data[0][4] = html_print_button(__('Add relationship'), 'add_relation', false, 'javascript: add_new_relation();', 'class="sub add"', true); -$table_new_relations->data[0][4] .= "  
"; -// Relationship list +$array_rel_type = []; +$array_rel_type['direct'] = __('Direct'); +$array_rel_type['failover'] = __('Failover'); +$table_new_relations->data[0][4] = __('Rel. type'); +$table_new_relations->data[0][5] = html_print_select( + $array_rel_type, + 'relation_type', + '', + '', + '', + 0, + true, + false, + true, + '' +); + +$table_new_relations->data[0][6] = html_print_button( + __('Add relationship'), + 'add_relation', + false, + 'javascript: add_new_relation();', + 'class="sub add"', + true +); +$table_new_relations->data[0][6] .= "  
"; + +// Relationship list. $table_relations = new stdClass(); $table_relations->id = 'module_relations'; $table_relations->width = '100%'; @@ -1141,19 +1170,26 @@ $table_relations->data = []; $table_relations->rowstyle = []; $table_relations->rowstyle[-1] = 'display: none;'; $table_relations->style = []; -$table_relations->style[2] = 'width: 10%; text-align: center;'; $table_relations->style[3] = 'width: 10%; text-align: center;'; +$table_relations->style[4] = 'width: 10%; text-align: center;'; $table_relations->head[0] = __('Agent'); $table_relations->head[1] = __('Module'); -$table_relations->head[2] = __('Changes').ui_print_help_tip(__('Activate this to prevent the relation from being updated or deleted'), true); -$table_relations->head[3] = __('Delete'); +$table_relations->head[2] = __('Type'); +$table_relations->head[3] = __('Changes').ui_print_help_tip( + __('Activate this to prevent the relation from being updated or deleted'), + true +); +$table_relations->head[4] = __('Delete'); -// Create an invisible row to use their html to add new rows +// Create an invisible row to use their html to add new rows. $table_relations->data[-1][0] = ''; $table_relations->data[-1][1] = ''; -$table_relations->data[-1][2] = ''.html_print_image('images/lock.png', true).''; -$table_relations->data[-1][3] = ''.html_print_image('images/cross.png', true).''; +$table_relations->data[-1][2] = ''; +$table_relations->data[-1][3] = ''; +$table_relations->data[-1][3] .= html_print_image('images/lock.png', true).''; +$table_relations->data[-1][4] = ''; +$table_relations->data[-1][4] .= html_print_image('images/cross.png', true).''; $module_relations = modules_get_relations(['id_module' => $id_agent_module]); if (!$module_relations) { @@ -1164,10 +1200,14 @@ $relations_count = 0; foreach ($module_relations as $key => $module_relation) { if ($module_relation['module_a'] == $id_agent_module) { $module_id = $module_relation['module_b']; - $agent_id = modules_give_agent_id_from_module_id($module_relation['module_b']); + $agent_id = modules_give_agent_id_from_module_id( + $module_relation['module_b'] + ); } else { $module_id = $module_relation['module_a']; - $agent_id = modules_give_agent_id_from_module_id($module_relation['module_a']); + $agent_id = modules_give_agent_id_from_module_id( + $module_relation['module_a'] + ); } $agent_name = ui_print_agent_name($agent_id, true); @@ -1183,14 +1223,16 @@ foreach ($module_relations as $key => $module_relation) { $disabled_update_class = 'alpha50'; } - // Agent name + // Agent name. $table_relations->data[$relations_count][0] = $agent_name; - // Module name + // Module name. $table_relations->data[$relations_count][1] = "".ui_print_truncate_text($module_name, 'module_medium', true, true, true, '[…]').''; - // Lock relationship updates - $table_relations->data[$relations_count][2] = ''.html_print_image('images/lock.png', true).''; - // Delete relationship - $table_relations->data[$relations_count][3] = ''.html_print_image('images/cross.png', true).''; + // Type. + $table_relations->data[$relations_count][2] = ($module_relation['type'] === 'direct') ? __('Direct') : __('Failover'); + // Lock relationship updates. + $table_relations->data[$relations_count][3] = ''.html_print_image('images/lock.png', true).''; + // Delete relationship. + $table_relations->data[$relations_count][4] = ''.html_print_image('images/cross.png', true).''; $relations_count++; } @@ -1198,7 +1240,6 @@ html_print_input_hidden('module_relations_count', $relations_count); ui_require_jquery_file('json'); - ?> diff --git a/pandora_console/godmode/agentes/module_manager_editor_wmi.php b/pandora_console/godmode/agentes/module_manager_editor_wmi.php index 6ad7311179..09501c358b 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_wmi.php +++ b/pandora_console/godmode/agentes/module_manager_editor_wmi.php @@ -83,8 +83,8 @@ $data[3] = html_print_input_password( true, $disabledBecauseInPolicy, false, - '', - $classdisabledBecauseInPolicy + $classdisabledBecauseInPolicy, + 'new-password' ); push_table_simple($data, 'user_pass'); diff --git a/pandora_console/godmode/agentes/planned_downtime.list.php b/pandora_console/godmode/agentes/planned_downtime.list.php index 961ea1f7d0..49a72f125d 100755 --- a/pandora_console/godmode/agentes/planned_downtime.list.php +++ b/pandora_console/godmode/agentes/planned_downtime.list.php @@ -52,7 +52,7 @@ if ($migrate_malformed) { // Header. ui_print_page_header( - __('Planned Downtime'), + __('Scheduled Downtime'), 'images/gm_monitoring.png', false, 'planned_downtime', @@ -136,9 +136,6 @@ $table_form = new StdClass(); $table_form->class = 'databox filters'; $table_form->width = '100%'; $table_form->rowstyle = []; -$table_form->rowstyle[0] = 'background-color: #f9faf9;'; -$table_form->rowstyle[1] = 'background-color: #f9faf9;'; -$table_form->rowstyle[2] = 'background-color: #f9faf9;'; $table_form->data = []; $row = []; diff --git a/pandora_console/godmode/alerts/alert_list.builder.php b/pandora_console/godmode/alerts/alert_list.builder.php index ca3a099bf3..c97fe2feff 100644 --- a/pandora_console/godmode/alerts/alert_list.builder.php +++ b/pandora_console/godmode/alerts/alert_list.builder.php @@ -37,14 +37,10 @@ $table->head = []; $table->data = []; $table->size = []; $table->size = []; -$table->size[0] = '5%'; -$table->size[1] = '25%'; -$table->size[2] = '5%'; -$table->size[3] = '20%'; -$table->style[0] = 'font-weight: bold; '; -$table->style[1] = 'font-weight: bold; '; -$table->style[2] = 'font-weight: bold; '; -$table->style[3] = 'font-weight: bold; '; +$table->style[0] = 'font-weight: bold;'; +$table->style[1] = 'font-weight: bold;display: flex;align-items: baseline;'; +$table->style[2] = 'font-weight: bold;'; +$table->style[3] = 'font-weight: bold;'; // This is because if this view is reused after list alert view then // styles in the previous view can affect this table. @@ -89,7 +85,7 @@ $table->data[0][1] = html_print_select( true, '', ($id_agente == 0), - 'width: 250px;' + 'min-width: 250px;margin-right: 0.5em;' ); $table->data[0][1] .= ' '; @@ -117,7 +113,7 @@ $table->data[1][1] = html_print_select( true, '', false, - 'width: 250px;' + 'min-width: 250px;' ); $table->data[1][1] .= ''; if (check_acl($config['id_user'], 0, 'LM')) { - $table->data[1][1] .= ''; + $table->data[1][1] .= ''; $table->data[1][1] .= html_print_image('images/add.png', true); - $table->data[1][1] .= ''.__('Create Action').''; + $table->data[1][1] .= ''.__('Create Action').''; $table->data[1][1] .= ''; } @@ -162,13 +158,13 @@ if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { if (check_acl($config['id_user'], 0, 'LM')) { $table->data[2][1] .= ''; $table->data[2][1] .= html_print_image('images/add.png', true); - $table->data[2][1] .= ''.__('Create Template').''; + $table->data[2][1] .= ''.__('Create Template').''; $table->data[2][1] .= ''; } $table->data[3][0] = __('Threshold'); $table->data[3][1] = html_print_input_text('module_action_threshold', '0', '', 5, 7, true); - $table->data[3][1] .= ' '.__('seconds'); + $table->data[3][1] .= ''.__('seconds').''; if (!isset($step)) { echo ''; diff --git a/pandora_console/godmode/alerts/alert_list.list.php b/pandora_console/godmode/alerts/alert_list.list.php index 4b3a3395cf..f830f47dbd 100644 --- a/pandora_console/godmode/alerts/alert_list.list.php +++ b/pandora_console/godmode/alerts/alert_list.list.php @@ -438,11 +438,11 @@ if (! $id_agente) { $table->style = []; $table->style[0] = 'font-weight: bold;'; $table->head[0] = __('Agent').ui_get_sorting_arrows($url_up_agente, $url_down_agente, $selectAgentUp, $selectAgentDown); - $table->size[0] = '4%'; - $table->size[1] = '8%'; - $table->size[2] = '8%'; - $table->size[3] = '4%'; - $table->size[4] = '4%'; + $table->headstyle[0] = 'width: 100%; min-width: 12em;'; + $table->headstyle[1] = 'min-width: 15em;'; + $table->headstyle[2] = 'min-width: 20em;'; + $table->headstyle[3] = 'min-width: 1em;'; + $table->headstyle[4] = 'min-width: 15em;'; /* if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { @@ -450,16 +450,11 @@ if (! $id_agente) { }*/ } else { $table->head[0] = __('Module').ui_get_sorting_arrows($url_up_module, $url_down_module, $selectModuleUp, $selectModuleDown); - // Different sizes or the layout screws up - $table->size[0] = '0%'; - $table->size[1] = '10%'; - $table->size[2] = '30%'; - /* - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - $table->size[4] = '25%'; - } */ - $table->size[3] = '1%'; - $table->size[4] = '1%'; + $table->headstyle[0] = 'width: 100%; min-width: 15em;'; + $table->headstyle[1] = 'min-width: 15em;'; + $table->headstyle[2] = 'min-width: 20em;'; + $table->headstyle[3] = 'min-width: 1em;'; + $table->headstyle[4] = 'min-width: 15em;'; } $table->head[1] = __('Template').ui_get_sorting_arrows($url_up_template, $url_down_template, $selectTemplateUp, $selectTemplateDown); diff --git a/pandora_console/godmode/alerts/configure_alert_action.php b/pandora_console/godmode/alerts/configure_alert_action.php index 3b7b5a947d..8ea292445b 100644 --- a/pandora_console/godmode/alerts/configure_alert_action.php +++ b/pandora_console/godmode/alerts/configure_alert_action.php @@ -317,9 +317,9 @@ $(document).ready (function () { jQuery.post (, values, function (data, status) { - original_command = js_html_entity_decode (data["command"]); + original_command = data["command"]; render_command_preview (original_command); - command_description = js_html_entity_decode (data["description"]); + command_description = data["description"]; render_command_description(command_description); var max_fields = parseInt(''); diff --git a/pandora_console/godmode/events/custom_events.php b/pandora_console/godmode/events/custom_events.php index 0bf3b223e2..fb4b6f9ab1 100644 --- a/pandora_console/godmode/events/custom_events.php +++ b/pandora_console/godmode/events/custom_events.php @@ -60,96 +60,12 @@ $fields_selected = explode(',', $config['event_fields']); $result_selected = []; -// show list of fields selected. +// Show list of fields selected. if ($fields_selected[0] != '') { foreach ($fields_selected as $field_selected) { - switch ($field_selected) { - case 'id_evento': - $result = __('Event Id'); - break; - - case 'evento': - $result = __('Event Name'); - break; - - case 'id_agente': - $result = __('Agent Name'); - break; - - case 'id_usuario': - $result = __('User'); - break; - - case 'id_grupo': - $result = __('Group'); - break; - - case 'estado': - $result = __('Status'); - break; - - case 'timestamp': - $result = __('Timestamp'); - break; - - case 'event_type': - $result = __('Event Type'); - break; - - case 'id_agentmodule': - $result = __('Module Name'); - break; - - case 'id_alert_am': - $result = __('Alert'); - break; - - case 'criticity': - $result = __('Severity'); - break; - - case 'user_comment': - $result = __('Comment'); - break; - - case 'tags': - $result = __('Tags'); - break; - - case 'source': - $result = __('Source'); - break; - - case 'id_extra': - $result = __('Extra Id'); - break; - - case 'owner_user': - $result = __('Owner'); - break; - - case 'ack_utimestamp': - $result = __('ACK Timestamp'); - break; - - case 'instructions': - $result = __('Instructions'); - break; - - case 'server_name': - $result = __('Server Name'); - break; - - case 'data': - $result = __('Data'); - break; - - case 'module_status': - $result = __('Module Status'); - break; - } - - $result_selected[$field_selected] = $result; + $result_selected[$field_selected] = events_get_column_name( + $field_selected + ); } } @@ -177,7 +93,8 @@ $fields_available = []; $fields_available['id_evento'] = __('Event Id'); $fields_available['evento'] = __('Event Name'); -$fields_available['id_agente'] = __('Agent Name'); +$fields_available['id_agente'] = __('Agent ID'); +$fields_available['agent_name'] = __('Agent Name'); $fields_available['id_usuario'] = __('User'); $fields_available['id_grupo'] = __('Group'); $fields_available['estado'] = __('Status'); @@ -196,20 +113,20 @@ $fields_available['instructions'] = __('Instructions'); $fields_available['server_name'] = __('Server Name'); $fields_available['data'] = __('Data'); $fields_available['module_status'] = __('Module Status'); +$fields_available['mini_severity'] = __('Severity mini'); -// remove fields already selected + +// Remove fields already selected. foreach ($fields_available as $key => $available) { - foreach ($result_selected as $selected) { - if ($selected == $available) { - unset($fields_available[$key]); - } + if (isset($result_selected[$key])) { + unset($fields_available[$key]); } } $table->data[0][0] = ''.__('Fields available').''; $table->data[1][0] = html_print_select($fields_available, 'fields_available[]', true, '', '', 0, true, true, false, '', false, 'width: 300px'); $table->data[1][1] = ''.html_print_image( - 'images/darrowright.png', + 'images/darrowright_green.png', true, [ 'id' => 'right', @@ -217,7 +134,7 @@ $table->data[1][1] = ''.html_print_image( ] ).''; $table->data[1][1] .= '



'.html_print_image( - 'images/darrowleft.png', + 'images/darrowleft_green.png', true, [ 'id' => 'left', diff --git a/pandora_console/godmode/events/event_edit_filter.php b/pandora_console/godmode/events/event_edit_filter.php index b2b9763d56..e66e1d30b4 100644 --- a/pandora_console/godmode/events/event_edit_filter.php +++ b/pandora_console/godmode/events/event_edit_filter.php @@ -232,10 +232,17 @@ $table->data[0][0] = ''.__('Filter name').''; $table->data[0][1] = html_print_input_text('id_name', $id_name, false, 20, 80, true); $table->data[1][0] = ''.__('Save in group').''.ui_print_help_tip(__('This group will be use to restrict the visibility of this filter with ACLs'), true); + +$returnAllGroup = users_can_manage_group_all(); +// If the user can't manage All group but the filter is for All group, the user should see All group in the select. +if ($returnAllGroup === false && $id_group_filter == 0) { + $returnAllGroup = true; +} + $table->data[1][1] = html_print_select_groups( $config['id_user'], $access, - users_can_manage_group_all(), + $returnAllGroup, 'id_group_filter', $id_group_filter, '', diff --git a/pandora_console/godmode/events/event_filter.php b/pandora_console/godmode/events/event_filter.php index 60ba973996..c9c3f7f226 100644 --- a/pandora_console/godmode/events/event_filter.php +++ b/pandora_console/godmode/events/event_filter.php @@ -93,10 +93,11 @@ if ($strict_acl) { users_can_manage_group_all() ); } else { + // All users should see the filters with the All group. $groups_user = users_get_groups( $config['id_user'], $access, - users_can_manage_group_all(), + true, true ); } diff --git a/pandora_console/godmode/events/event_responses.editor.php b/pandora_console/godmode/events/event_responses.editor.php index 1705605744..c514ded346 100644 --- a/pandora_console/godmode/events/event_responses.editor.php +++ b/pandora_console/godmode/events/event_responses.editor.php @@ -143,12 +143,12 @@ $table->data[3] = $data; $data = []; $data[0] = ''.__('Command').''.ui_print_help_icon('response_macros', true); -$data[1] = html_print_input_text( +$data[1] = html_print_textarea( 'target', + 3, + 1, $event_response['target'], - '', - 100, - 255, + 'style="min-height:initial;"', true ); diff --git a/pandora_console/godmode/events/events.php b/pandora_console/godmode/events/events.php index c937ad281c..72ae001fe1 100644 --- a/pandora_console/godmode/events/events.php +++ b/pandora_console/godmode/events/events.php @@ -50,17 +50,10 @@ if (check_acl($config['id_user'], 0, 'PM')) { 'text' => ''.html_print_image('images/event_responses.png', true, ['title' => __('Event responses')]).'', ]; - if (!is_metaconsole()) { - $buttons['fields'] = [ - 'active' => false, - 'text' => ''.html_print_image('images/custom_columns.png', true, ['title' => __('Custom fields')]).'', - ]; - } else { - $buttons['fields'] = [ - 'active' => false, - 'text' => ''.html_print_image('images/custom_columns.png', true, ['title' => __('Custom fields')]).'', - ]; - } + $buttons['fields'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/custom_columns.png', true, ['title' => __('Custom fields')]).'', + ]; } switch ($section) { diff --git a/pandora_console/godmode/gis_maps/configure_gis_map.php b/pandora_console/godmode/gis_maps/configure_gis_map.php index 0e632380ce..8277463e18 100644 --- a/pandora_console/godmode/gis_maps/configure_gis_map.php +++ b/pandora_console/godmode/gis_maps/configure_gis_map.php @@ -357,8 +357,8 @@ function addConnectionMap() { for (var index in connectionMaps) { if (isInt(index)) { if (connectionMaps[index] == idConnectionMap) { - alert(" "' + connectionMapName + '" "); - + alert(" " + connectionMapName + " "); + return; } } diff --git a/pandora_console/godmode/groups/credential_store.php b/pandora_console/godmode/groups/credential_store.php new file mode 100644 index 0000000000..3273e1c038 --- /dev/null +++ b/pandora_console/godmode/groups/credential_store.php @@ -0,0 +1,627 @@ + 'noaccess']; + } + + include 'general/noaccess.php'; + return; +} + +// Required files. +ui_require_css_file('credential_store'); +require_once $config['homedir'].'/include/functions_credential_store.php'; +require_once $config['homedir'].'/include/functions_io.php'; + +if (is_ajax()) { + $draw = get_parameter('draw', 0); + $filter = get_parameter('filter', []); + $get_key = get_parameter('get_key', 0); + $new_form = get_parameter('new_form', 0); + $new_key = get_parameter('new_key', 0); + $update_key = get_parameter('update_key', 0); + $delete_key = get_parameter('delete_key', 0); + + if ($new_form) { + echo print_inputs(); + exit; + } + + if ($delete_key) { + $identifier = get_parameter('identifier', null); + + if (empty($identifier)) { + ajax_msg('error', __('identifier cannot be empty')); + } + + if (db_process_sql_delete( + 'tcredential_store', + ['identifier' => $identifier] + ) === false + ) { + ajax_msg('error', $config['dbconnection']->error, true); + } else { + ajax_msg('result', $identifier, true); + } + } + + if ($update_key) { + $data = get_parameter('values', null); + + if ($data === null || !is_array($data)) { + echo json_encode(['error' => __('Invalid parameters, please retry')]); + exit; + } + + $values = []; + foreach ($data as $key => $value) { + if ($key == 'identifier') { + $identifier = base64_decode($value); + } else if ($key == 'product') { + $product = base64_decode($value); + } else { + $values[$key] = base64_decode($value); + } + } + + if (empty($identifier)) { + ajax_msg('error', __('identifier cannot be empty')); + } + + if (empty($product)) { + ajax_msg('error', __('product cannot be empty')); + } + + if (db_process_sql_update( + 'tcredential_store', + $values, + ['identifier' => $identifier] + ) === false + ) { + ajax_msg('error', $config['dbconnection']->error); + } else { + ajax_msg('result', $identifier); + } + + exit; + } + + if ($new_key) { + $data = get_parameter('values', null); + + if ($data === null || !is_array($data)) { + echo json_encode(['error' => __('Invalid parameters, please retry')]); + exit; + } + + $values = []; + foreach ($data as $key => $value) { + $values[$key] = base64_decode($value); + if ($key == 'identifier') { + $values[$key] = preg_replace('/\s+/', '-', trim($values[$key])); + } + } + + $identifier = $values['identifier']; + + if (empty($identifier)) { + ajax_msg('error', __('identifier cannot be empty')); + } + + if (empty($values['product'])) { + ajax_msg('error', __('product cannot be empty')); + } + + if (db_process_sql_insert('tcredential_store', $values) === false) { + ajax_msg('error', $config['dbconnection']->error); + } else { + ajax_msg('result', $identifier); + } + + exit; + } + + if ($get_key) { + $identifier = get_parameter('identifier', null); + + $key = get_key($identifier); + echo print_inputs($key); + + exit; + } + + if ($draw) { + // Datatables offset, limit and order. + $start = get_parameter('start', 0); + $length = get_parameter('length', $config['block_size']); + $order = get_datatable_order(true); + try { + ob_start(); + + $fields = [ + 'cs.*', + 'tg.nombre as `group`', + ]; + + // Retrieve data. + $data = credentials_get_all( + // Fields. + $fields, + // Filter. + $filter, + // Offset. + $start, + // Limit. + $length, + // Order. + $order['direction'], + // Sort field. + $order['field'] + ); + + // Retrieve counter. + $count = credentials_get_all( + 'count', + $filter + ); + + if ($data) { + $data = array_reduce( + $data, + function ($carry, $item) { + // Transforms array of arrays $data into an array + // of objects, making a post-process of certain fields. + $tmp = (object) $item; + $tmp->username = io_safe_output($tmp->username); + + if (empty($tmp->group)) { + $tmp->group = __('All'); + } else { + $tmp->group = io_safe_output($tmp->group); + } + + $carry[] = $tmp; + return $carry; + } + ); + } + + // Datatables format: RecordsTotal && recordsfiltered. + echo json_encode( + [ + 'data' => $data, + 'recordsTotal' => $count, + 'recordsFiltered' => $count, + ] + ); + // Capture output. + $response = ob_get_clean(); + } catch (Exception $e) { + return json_encode(['error' => $e->getMessage()]); + } + + // If not valid, show error with issue. + json_decode($response); + if (json_last_error() == JSON_ERROR_NONE) { + // If valid dump. + echo $response; + } else { + echo json_encode( + ['error' => $response] + ); + } + + + exit; + } + + exit; +} + +// Datatables list. +try { + $columns = [ + 'group', + 'identifier', + 'product', + 'username', + 'options', + ]; + + $column_names = [ + __('Group'), + __('Identifier'), + __('Product'), + __('User'), + [ + 'text' => __('Options'), + 'class' => 'action_buttons', + ], + ]; + + $table_id = 'keystore'; + // Load datatables user interface. + ui_print_datatable( + [ + 'id' => $table_id, + 'class' => 'info_table', + 'style' => 'width: 100%', + 'columns' => $columns, + 'column_names' => $column_names, + 'ajax_url' => 'godmode/groups/credential_store', + 'ajax_postprocess' => 'process_datatables_item(item)', + 'no_sortable_columns' => [-1], + 'order' => [ + 'field' => 'identifier', + 'direction' => 'asc', + ], + 'search_button_class' => 'sub filter float-right', + 'form' => [ + 'inputs' => [ + [ + 'label' => __('Group'), + 'type' => 'select', + 'id' => 'filter_id_group', + 'name' => 'filter_id_group', + 'options' => users_get_groups_for_select( + $config['id_user'], + 'AR', + true, + true, + false + ), + ], + [ + 'label' => __('Free search'), + 'type' => 'text', + 'class' => 'mw250px', + 'id' => 'free_search', + 'name' => 'free_search', + ], + ], + ], + ] + ); +} catch (Exception $e) { + echo $e->getMessage(); +} + +// Auxiliar div. +$new = ''; +$details = ''; +$aux = ''; + + +echo $new.$details.$aux; + +// Create button. +echo '
'; +html_print_submit_button( + __('Add key'), + 'create', + false, + 'class="sub next"' +); +echo '
'; + +?> + + diff --git a/pandora_console/godmode/groups/group_list.php b/pandora_console/godmode/groups/group_list.php index ee61cdaf79..8cb3c106c1 100644 --- a/pandora_console/godmode/groups/group_list.php +++ b/pandora_console/godmode/groups/group_list.php @@ -1,20 +1,36 @@ $v) { $agents[$keys_prefix.$k] = $v; unset($agents[$k]); if ($all_agents) { - // Unserialize to get the status + // Unserialize to get the status. if ($serialized && is_metaconsole()) { $agent_info = explode($serialized_separator, $k); $agent_disabled = db_get_value_filter( @@ -174,7 +193,8 @@ if (is_ajax()) { ['id_agente' => $agent_info[1]] ); } else if (!$serialized && is_metaconsole()) { - // Cannot retrieve the disabled status. Mark all as not disabled + // Cannot retrieve the disabled status. + // Mark all as not disabled. $agent_disabled = 0; } else { $agent_disabled = db_get_value_filter( @@ -226,11 +246,13 @@ if (! check_acl($config['id_user'], 0, 'PM')) { } $sec = defined('METACONSOLE') ? 'advanced' : 'gagente'; -$url_tree = "index.php?sec=$sec&sec2=godmode/groups/group_list&tab=tree"; -$url_groups = "index.php?sec=$sec&sec2=godmode/groups/group_list&tab=groups"; +$url_credbox = 'index.php?sec='.$sec.'&sec2=godmode/groups/group_list&tab=credbox'; +$url_tree = 'index.php?sec='.$sec.'&sec2=godmode/groups/group_list&tab=tree'; +$url_groups = 'index.php?sec='.$sec.'&sec2=godmode/groups/group_list&tab=groups'; + $buttons['tree'] = [ 'active' => false, - 'text' => "".html_print_image( + 'text' => ''.html_print_image( 'images/gm_massive_operations.png', true, [ @@ -241,7 +263,7 @@ $buttons['tree'] = [ $buttons['groups'] = [ 'active' => false, - 'text' => "".html_print_image( + 'text' => ''.html_print_image( 'images/group.png', true, [ @@ -250,21 +272,38 @@ $buttons['groups'] = [ ).'', ]; +$buttons['credbox'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/key.png', + true, + [ + 'title' => __('Credential Store'), + ] + ).'', +]; + $tab = (string) get_parameter('tab', 'groups'); -// Marks correct tab +$title = __('Groups defined in %s', get_product_name()); +// Marks correct tab. switch ($tab) { case 'tree': $buttons['tree']['active'] = true; break; + case 'credbox': + $buttons['credbox']['active'] = true; + $title = __('Credential store'); + break; + case 'groups': default: $buttons['groups']['active'] = true; break; } -// Header +// Header. if (defined('METACONSOLE')) { agents_meta_print_header(); echo '
'; @@ -272,7 +311,7 @@ if (defined('METACONSOLE')) { echo '
'; } else { ui_print_page_header( - __('Groups defined in %s', get_product_name()), + $title, 'images/group.png', false, 'group_list_tab', @@ -281,12 +320,19 @@ if (defined('METACONSOLE')) { ); } +// Load credential store view before parse list-tree forms. +if ($tab == 'credbox') { + include_once __DIR__.'/credential_store.php'; + // Stop script. + return; +} + $create_group = (bool) get_parameter('create_group'); $update_group = (bool) get_parameter('update_group'); $delete_group = (bool) get_parameter('delete_group'); $pure = get_parameter('pure', 0); -// Create group +// Create group. if (($create_group) && (check_acl($config['id_user'], 0, 'PM'))) { $name = (string) get_parameter('name'); $icon = (string) get_parameter('icon'); @@ -301,7 +347,7 @@ if (($create_group) && (check_acl($config['id_user'], 0, 'PM'))) { $check = db_get_value('nombre', 'tgrupo', 'nombre', $name); $propagate = (bool) get_parameter('propagate'); - // Check if name field is empty + // Check if name field is empty. if ($name != '') { if (!$check) { $values = [ @@ -328,12 +374,11 @@ if (($create_group) && (check_acl($config['id_user'], 0, 'PM'))) { ui_print_error_message(__('Each group must have a different name')); } } else { - // $result = false; ui_print_error_message(__('Group must have a name')); } } -// Update group +// Update group. if ($update_group) { $id_group = (int) get_parameter('id_group'); $name = (string) get_parameter('name'); @@ -349,49 +394,35 @@ if ($update_group) { $contact = (string) get_parameter('contact'); $other = (string) get_parameter('other'); - // Check if name field is empty + // Check if name field is empty. if ($name != '') { - switch ($config['dbtype']) { - case 'mysql': - $sql = sprintf( - 'UPDATE tgrupo SET nombre = "%s", - icon = "%s", disabled = %d, parent = %d, custom_id = "%s", propagate = %d, id_skin = %d, description = "%s", contact = "%s", other = "%s", password = "%s" - WHERE id_grupo = %d', - $name, - empty($icon) ? '' : substr($icon, 0, -4), - !$alerts_enabled, - $id_parent, - $custom_id, - $propagate, - $skin, - $description, - $contact, - $other, - $group_pass, - $id_group - ); - break; - - case 'postgresql': - case 'oracle': - $sql = sprintf( - 'UPDATE tgrupo SET nombre = \'%s\', - icon = \'%s\', disabled = %d, parent = %d, custom_id = \'%s\', propagate = %d, id_skin = %d, description = \'%s\', contact = \'%s\', other = \'%s\' - WHERE id_grupo = %d', - $name, - substr($icon, 0, -4), - !$alerts_enabled, - $id_parent, - $custom_id, - $propagate, - $skin, - $description, - $contact, - $other, - $id_group - ); - break; - } + $sql = sprintf( + 'UPDATE tgrupo + SET nombre = "%s", + icon = "%s", + disabled = %d, + parent = %d, + custom_id = "%s", + propagate = %d, + id_skin = %d, + description = "%s", + contact = "%s", + other = "%s", + password = "%s" + WHERE id_grupo = %d', + $name, + empty($icon) ? '' : substr($icon, 0, -4), + !$alerts_enabled, + $id_parent, + $custom_id, + $propagate, + $skin, + $description, + $contact, + $other, + $group_pass, + $id_group + ); $result = db_process_sql($sql); } else { @@ -405,7 +436,7 @@ if ($update_group) { } } -// Delete group +// Delete group. if (($delete_group) && (check_acl($config['id_user'], 0, 'PM'))) { $id_group = (int) get_parameter('id_group'); @@ -445,7 +476,14 @@ if (($delete_group) && (check_acl($config['id_user'], 0, 'PM'))) { } } + +// Credential store is loaded previously in this document to avoid +// process group tree - list forms. if ($tab == 'tree') { + /* + * Group tree view. + */ + echo html_print_image( 'images/spinner.gif', true, @@ -456,6 +494,10 @@ if ($tab == 'tree') { ); echo "
"; } else { + /* + * Group list view. + */ + $acl = ''; $search_name = ''; $offset = (int) get_parameter('offset', 0); @@ -463,17 +505,22 @@ if ($tab == 'tree') { $block_size = $config['block_size']; if (!empty($search)) { - $search_name = "AND t.nombre LIKE '%$search%'"; + $search_name = 'AND t.nombre LIKE "%'.$search.'%"'; } if (!users_can_manage_group_all('AR')) { $user_groups_acl = users_get_groups(false, 'AR'); $groups_acl = implode(',', $user_groups_ACL); if (empty($groups_acl)) { - return ui_print_info_message(['no_close' => true, 'message' => __('There are no defined groups') ]); + return ui_print_info_message( + [ + 'no_close' => true, + 'message' => __('There are no defined groups'), + ] + ); } - $acl = "AND t.id_grupo IN ($groups_acl)"; + $acl = 'AND t.id_grupo IN ('.$groups_acl.')'; } $form = "
"; @@ -488,29 +535,37 @@ if ($tab == 'tree') { echo $form; - $groups_sql = "SELECT t.*, + $groups_sql = sprintf( + 'SELECT t.*, p.nombre AS parent_name, IF(t.parent=p.id_grupo, 1, 0) AS has_child - FROM tgrupo t - LEFT JOIN tgrupo p + FROM tgrupo t + LEFT JOIN tgrupo p ON t.parent=p.id_grupo - WHERE 1=1 - $acl - $search_name + WHERE 1=1 + %s + %s ORDER BY nombre - LIMIT $offset, $block_size - "; + LIMIT %d, %d', + $acl, + $search_name, + $offset, + $block_size + ); $groups = db_get_all_rows_sql($groups_sql); if (!empty($groups)) { - // Count all groups for pagination only saw user and filters - $groups_sql_count = "SELECT count(*) + // Count all groups for pagination only saw user and filters. + $groups_sql_count = sprintf( + 'SELECT count(*) FROM tgrupo t WHERE 1=1 - $acl - $search_name - "; + %s + %s', + $acl, + $search_name + ); $groups_count = db_get_value_sql($groups_sql_count); $table = new StdClass(); @@ -545,7 +600,7 @@ if ($tab == 'tree') { $url = 'index.php?sec=gagente&sec2=godmode/groups/configure_group&id_group='.$group['id_grupo']; $url_delete = 'index.php?sec=gagente&sec2=godmode/groups/group_list&delete_group=1&id_group='.$group['id_grupo']; $table->data[$key][0] = $group['id_grupo']; - $table->data[$key][1] = "".$group['nombre'].''; + $table->data[$key][1] = ''.$group['nombre'].''; if ($group['icon'] != '') { $table->data[$key][2] = html_print_image( 'images/groups_small/'.$group['icon'].'.png', @@ -553,22 +608,25 @@ if ($tab == 'tree') { [ 'style' => '', 'class' => 'bot', - 'alt' => $group['nombre'], + 'alt' => $group['nombre'], 'title' => $group['nombre'], - false, false, false, true - ] + ], + false, + false, + false, + true ); } else { $table->data[$key][2] = ''; } - // reporting_get_group_stats - $table->data[$key][3] = $group['disabled'] ? __('Disabled') : __('Enabled'); + // Reporting_get_group_stats. + $table->data[$key][3] = ($group['disabled']) ? __('Disabled') : __('Enabled'); $table->data[$key][4] = $group['parent_name']; $table->data[$key][5] = $group['description']; $table->cellclass[$key][6] = 'action_buttons'; - $table->data[$key][6] = "".html_print_image( + $table->data[$key][6] = ''.html_print_image( 'images/config.png', true, [ diff --git a/pandora_console/godmode/massive/massive_add_profiles.php b/pandora_console/godmode/massive/massive_add_profiles.php index 6000dbe9a6..e337c09f81 100644 --- a/pandora_console/godmode/massive/massive_add_profiles.php +++ b/pandora_console/godmode/massive/massive_add_profiles.php @@ -84,7 +84,9 @@ if ($create_profiles) { ); } -html_print_table($table); +if ($table !== null) { + html_print_table($table); +} unset($table); diff --git a/pandora_console/godmode/massive/massive_copy_modules.php b/pandora_console/godmode/massive/massive_copy_modules.php index b79a64460e..36ab0c310c 100755 --- a/pandora_console/godmode/massive/massive_copy_modules.php +++ b/pandora_console/godmode/massive/massive_copy_modules.php @@ -177,6 +177,9 @@ $table->data['operations'][1] .= html_print_checkbox('copy_alerts', 1, true, tru $table->data['operations'][1] .= html_print_label(__('Copy alerts'), 'checkbox-copy_alerts', true); $table->data['operations'][1] .= ''; +$table->data['form_modules_filter'][0] = __('Filter Modules'); +$table->data['form_modules_filter'][1] = html_print_input_text('filter_modules', '', '', 20, 255, true); + $table->data[1][0] = __('Modules'); $table->data[1][1] = ''; $table->data[1][1] .= html_print_select( @@ -270,6 +273,9 @@ $table->data[1][1] = html_print_select( true ); +$table->data['form_agents_filter'][0] = __('Filter Agents'); +$table->data['form_agents_filter'][1] = html_print_input_text('filter_agents', '', '', 20, 255, true); + $table->data[2][0] = __('Agent'); $table->data[2][0] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/firts_task/icono_grande_reconserver.png', true, [ - 'title' => __('Manage recon tasks'), + 'title' => __('Manage Discovery tasks'), 'style' => 'width:21px;height:21px;', ] ); @@ -165,7 +165,7 @@ foreach ($servers as $server) { } if ($server['type'] == 'data') { - $data[8] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/target.png', true, @@ -173,7 +173,7 @@ foreach ($servers as $server) { ); $data[8] .= ''; } else if ($server['type'] == 'enterprise snmp') { - $data[8] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/target.png', true, @@ -182,7 +182,7 @@ foreach ($servers as $server) { $data[8] .= ''; } - $data[8] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/config.png', true, @@ -191,7 +191,7 @@ foreach ($servers as $server) { $data[8] .= ''; if (($names_servers[$safe_server_name] === true) && ($server['type'] == 'data' || $server['type'] == 'enterprise satellite')) { - $data[8] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/remote_configuration.png', true, @@ -201,7 +201,7 @@ foreach ($servers as $server) { $names_servers[$safe_server_name] = false; } - $data[8] .= ''; + $data[8] .= ''; $data[8] .= html_print_image( 'images/cross.png', true, @@ -234,7 +234,8 @@ if ($tiny) { ui_toggle( html_print_table($table, true), __('Tactical server information'), - false, + '', + '', $hidden_toggle ); } else { diff --git a/pandora_console/godmode/setup/license.php b/pandora_console/godmode/setup/license.php index f03d32ef0a..06d7d2e7e3 100644 --- a/pandora_console/godmode/setup/license.php +++ b/pandora_console/godmode/setup/license.php @@ -135,7 +135,9 @@ $table->data[9][0] = ''.__('Licensed to').''; $table->data[9][1] = html_print_input_text('licensed_to', $license['licensed_to'], '', 64, 255, true, true); html_print_table($table); -if (enterprise_installed()) { + +// If DESTDIR is defined the enterprise license is expired. +if (enterprise_installed() || defined('DESTDIR')) { echo '
'; html_print_input_hidden('update_settings', 1); html_print_submit_button(__('Validate'), 'update_button', false, 'class="sub upd"'); diff --git a/pandora_console/godmode/setup/setup.php b/pandora_console/godmode/setup/setup.php index f5bfc8c635..c32f128ddd 100644 --- a/pandora_console/godmode/setup/setup.php +++ b/pandora_console/godmode/setup/setup.php @@ -86,7 +86,7 @@ $buttons = []; // Draws header. $buttons['general'] = [ 'active' => false, - 'text' => ''.html_print_image('images/gm_setup.png', true, ['title' => __('General')]).'', + 'text' => ''.html_print_image('images/gm_setup.png', true, ['title' => __('General')]).'', ]; if (enterprise_installed()) { @@ -95,37 +95,37 @@ if (enterprise_installed()) { $buttons['auth'] = [ 'active' => false, - 'text' => ''.html_print_image('images/key.png', true, ['title' => __('Authentication')]).'', + 'text' => ''.html_print_image('images/key.png', true, ['title' => __('Authentication')]).'', ]; $buttons['perf'] = [ 'active' => false, - 'text' => ''.html_print_image('images/performance.png', true, ['title' => __('Performance')]).'', + 'text' => ''.html_print_image('images/performance.png', true, ['title' => __('Performance')]).'', ]; $buttons['vis'] = [ 'active' => false, - 'text' => ''.html_print_image('images/chart.png', true, ['title' => __('Visual styles')]).'', + 'text' => ''.html_print_image('images/chart.png', true, ['title' => __('Visual styles')]).'', ]; if (check_acl($config['id_user'], 0, 'AW')) { if ($config['activate_netflow']) { $buttons['net'] = [ 'active' => false, - 'text' => ''.html_print_image('images/op_netflow.png', true, ['title' => __('Netflow')]).'', + 'text' => ''.html_print_image('images/op_netflow.png', true, ['title' => __('Netflow')]).'', ]; } } $buttons['ehorus'] = [ 'active' => false, - 'text' => ''.html_print_image('images/ehorus/ehorus.png', true, ['title' => __('eHorus')]).'', + 'text' => ''.html_print_image('images/ehorus/ehorus.png', true, ['title' => __('eHorus')]).'', ]; // FIXME: Not definitive icon $buttons['notifications'] = [ 'active' => false, - 'text' => ''.html_print_image('images/alerts_template.png', true, ['title' => __('Notifications')]).'', + 'text' => ''.html_print_image('images/alerts_template.png', true, ['title' => __('Notifications')]).'', ]; $help_header = ''; diff --git a/pandora_console/godmode/setup/setup_general.php b/pandora_console/godmode/setup/setup_general.php index eb37a608ea..8d9636e438 100644 --- a/pandora_console/godmode/setup/setup_general.php +++ b/pandora_console/godmode/setup/setup_general.php @@ -1,5 +1,13 @@ data = []; $table_mail_conf->style[0] = 'font-weight: bold'; // Current config["language"] could be set by user, not taken from global setup ! -switch ($config['dbtype']) { - case 'mysql': - $current_system_lang = db_get_sql( - 'SELECT `value` - FROM tconfig WHERE `token` = "language"' - ); - break; - - case 'postgresql': - $current_system_lang = db_get_sql( - 'SELECT "value" - FROM tconfig WHERE "token" = \'language\'' - ); - break; - - case 'oracle': - $current_system_lang = db_get_sql( - 'SELECT value - FROM tconfig WHERE token = \'language\'' - ); - break; -} +$current_system_lang = db_get_sql( + 'SELECT `value` FROM tconfig WHERE `token` = "language"' +); if ($current_system_lang == '') { $current_system_lang = 'en'; } -$table->data[0][0] = __('Language code'); -$table->data[0][1] = html_print_select_from_sql( +$i = 0; + +$table->data[$i][0] = __('Language code'); +$table->data[$i++][1] = html_print_select_from_sql( 'SELECT id_language, name FROM tlanguage', 'language', $current_system_lang, @@ -77,68 +96,67 @@ $table->data[0][1] = html_print_select_from_sql( true ); -$table->data[1][0] = __('Remote config directory').ui_print_help_tip(__('Directory where agent remote configuration is stored.'), true); +$table->data[$i][0] = __('Remote config directory').ui_print_help_tip(__('Directory where agent remote configuration is stored.'), true); +$table->data[$i++][1] = html_print_input_text('remote_config', io_safe_output($config['remote_config']), '', 30, 100, true); -$table->data[1][1] = html_print_input_text('remote_config', io_safe_output($config['remote_config']), '', 30, 100, true); +$table->data[$i][0] = __('Phantomjs bin directory').ui_print_help_tip(__('Directory where phantomjs binary file exists and has execution grants.'), true); +$table->data[$i++][1] = html_print_input_text('phantomjs_bin', io_safe_output($config['phantomjs_bin']), '', 30, 100, true); -$table->data[2][0] = __('Phantomjs bin directory').ui_print_help_tip(__('Directory where phantomjs binary file exists and has execution grants.'), true); +$table->data[$i][0] = __('Auto login (hash) password'); +$table->data[$i++][1] = html_print_input_password('loginhash_pwd', io_output_password($config['loginhash_pwd']), '', 15, 15, true); -$table->data[2][1] = html_print_input_text('phantomjs_bin', io_safe_output($config['phantomjs_bin']), '', 30, 100, true); - -$table->data[6][0] = __('Auto login (hash) password'); -$table->data[6][1] = html_print_input_password('loginhash_pwd', io_output_password($config['loginhash_pwd']), '', 15, 15, true); - -$table->data[9][0] = __('Time source'); +$table->data[$i][0] = __('Time source'); $sources['system'] = __('System'); $sources['sql'] = __('Database'); -$table->data[9][1] = html_print_select($sources, 'timesource', $config['timesource'], '', '', '', true); +$table->data[$i++][1] = html_print_select($sources, 'timesource', $config['timesource'], '', '', '', true); -$table->data[10][0] = __('Automatic check for updates'); -$table->data[10][1] = html_print_checkbox_switch('autoupdate', 1, $config['autoupdate'], true); +$table->data[$i][0] = __('Automatic check for updates'); +$table->data[$i++][1] = html_print_checkbox_switch('autoupdate', 1, $config['autoupdate'], true); echo "'; -$table->data[11][0] = __('Enforce https'); -$table->data[11][1] = html_print_checkbox_switch_extended('https', 1, $config['https'], false, '', '', true); +$table->data[$i][0] = __('Enforce https'); +$table->data[$i++][1] = html_print_checkbox_switch_extended('https', 1, $config['https'], false, '', '', true); -$table->data[12][0] = __('Use cert of SSL'); -$table->data[12][1] = html_print_checkbox_switch_extended('use_cert', 1, $config['use_cert'], false, '', '', true); +$table->data[$i][0] = __('Use cert of SSL'); +$table->data[$i++][1] = html_print_checkbox_switch_extended('use_cert', 1, $config['use_cert'], false, '', '', true); -$table->rowstyle[13] = 'display: none;'; -$table->data[13][0] = __('Path of SSL Cert.').ui_print_help_tip(__('Path where you put your cert and name of this cert. Remember your cert only in .pem extension.'), true); -$table->data[13][1] = html_print_input_text('cert_path', io_safe_output($config['cert_path']), '', 50, 255, true); +$table->rowstyle[$i] = 'display: none;'; +$table->rowid[$i] = 'ssl-path-tr'; +$table->data[$i][0] = __('Path of SSL Cert.').ui_print_help_tip(__('Path where you put your cert and name of this cert. Remember your cert only in .pem extension.'), true); +$table->data[$i++][1] = html_print_input_text('cert_path', io_safe_output($config['cert_path']), '', 50, 255, true); -$table->data[14][0] = __('Attachment store').ui_print_help_tip(__('Directory where temporary data is stored.'), true); -$table->data[14][1] = html_print_input_text('attachment_store', io_safe_output($config['attachment_store']), '', 50, 255, true); +$table->data[$i][0] = __('Attachment store').ui_print_help_tip(__('Directory where temporary data is stored.'), true); +$table->data[$i++][1] = html_print_input_text('attachment_store', io_safe_output($config['attachment_store']), '', 50, 255, true); -$table->data[15][0] = __('IP list with API access'); +$table->data[$i][0] = __('IP list with API access'); if (isset($_POST['list_ACL_IPs_for_API'])) { $list_ACL_IPs_for_API = get_parameter_post('list_ACL_IPs_for_API'); } else { $list_ACL_IPs_for_API = get_parameter_get('list_ACL_IPs_for_API', implode("\n", $config['list_ACL_IPs_for_API'])); } -$table->data[15][1] = html_print_textarea('list_ACL_IPs_for_API', 2, 25, $list_ACL_IPs_for_API, 'style="height: 50px; width: 300px"', true); +$table->data[$i++][1] = html_print_textarea('list_ACL_IPs_for_API', 2, 25, $list_ACL_IPs_for_API, 'style="height: 50px; width: 300px"', true); -$table->data[16][0] = __('API password').ui_print_help_tip(__('Please be careful if you put a password put https access.'), true); -$table->data[16][1] = html_print_input_password('api_password', io_output_password($config['api_password']), '', 25, 255, true); +$table->data[$i][0] = __('API password').ui_print_help_tip(__('Please be careful if you put a password put https access.'), true); +$table->data[$i++][1] = html_print_input_password('api_password', io_output_password($config['api_password']), '', 25, 255, true); -$table->data[17][0] = __('Enable GIS features'); -$table->data[17][1] = html_print_checkbox_switch('activate_gis', 1, $config['activate_gis'], true); +$table->data[$i][0] = __('Enable GIS features'); +$table->data[$i++][1] = html_print_checkbox_switch('activate_gis', 1, $config['activate_gis'], true); -$table->data[19][0] = __('Enable Netflow'); +$table->data[$i][0] = __('Enable Netflow'); $rbt_disabled = false; if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { $rbt_disabled = true; - $table->data[19][0] .= ui_print_help_tip(__('Not supported in Windows systems'), true); + $table->data[$i][0] .= ui_print_help_tip(__('Not supported in Windows systems'), true); } -$table->data[19][1] = html_print_checkbox_switch_extended('activate_netflow', 1, $config['activate_netflow'], $rbt_disabled, '', '', true); +$table->data[$i++][1] = html_print_checkbox_switch_extended('activate_netflow', 1, $config['activate_netflow'], $rbt_disabled, '', '', true); -$table->data[21][0] = __('Enable Network Traffic Analyzer'); -$table->data[21][1] = html_print_switch( +$table->data[$i][0] = __('Enable Network Traffic Analyzer'); +$table->data[$i++][1] = html_print_switch( [ 'name' => 'activate_nta', 'value' => $config['activate_nta'], @@ -177,11 +195,11 @@ foreach ($timezones as $timezone) { } } -$table->data[23][0] = __('Timezone setup').' '.ui_print_help_tip( +$table->data[$i][0] = __('Timezone setup').' '.ui_print_help_tip( __('Must have the same time zone as the system or database to avoid mismatches of time.'), true ); -$table->data[23][1] = html_print_input_text_extended( +$table->data[$i][1] = html_print_input_text_extended( 'timezone_text', $config['timezone'], 'text-timezone_text', @@ -193,47 +211,63 @@ $table->data[23][1] = html_print_input_text_extended( 'readonly', true ); -$table->data[23][1] .= ''.html_print_image('images/pencil.png', true, ['title' => __('Change timezone')]).''; -$table->data[23][1] .= '  '.html_print_select($zone_name, 'zone', $zone_selected, 'show_timezone();', '', '', true); -$table->data[23][1] .= '  '.html_print_select($timezone_n, 'timezone', $config['timezone'], '', '', '', true); +$table->data[$i][1] .= ''.html_print_image('images/pencil.png', true, ['title' => __('Change timezone')]).''; +$table->data[$i][1] .= '  '.html_print_select($zone_name, 'zone', $zone_selected, 'show_timezone();', '', '', true); +$table->data[$i++][1] .= '  '.html_print_select($timezone_n, 'timezone', $config['timezone'], '', '', '', true); $sounds = get_sounds(); -$table->data[24][0] = __('Sound for Alert fired'); -$table->data[24][1] = html_print_select($sounds, 'sound_alert', $config['sound_alert'], 'replaySound(\'alert\');', '', '', true); -$table->data[24][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_alert', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; -$table->data[24][1] .= '
'; +$table->data[$i][0] = __('Sound for Alert fired'); +$table->data[$i][1] = html_print_select($sounds, 'sound_alert', $config['sound_alert'], 'replaySound(\'alert\');', '', '', true); +$table->data[$i][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_alert', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; +$table->data[$i++][1] .= '
'; -$table->data[25][0] = __('Sound for Monitor critical'); -$table->data[25][1] = html_print_select($sounds, 'sound_critical', $config['sound_critical'], 'replaySound(\'critical\');', '', '', true); -$table->data[25][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_critical', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; -$table->data[25][1] .= '
'; +$table->data[$i][0] = __('Sound for Monitor critical'); +$table->data[$i][1] = html_print_select($sounds, 'sound_critical', $config['sound_critical'], 'replaySound(\'critical\');', '', '', true); +$table->data[$i][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_critical', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; +$table->data[$i++][1] .= '
'; -$table->data[26][0] = __('Sound for Monitor warning'); -$table->data[26][1] = html_print_select($sounds, 'sound_warning', $config['sound_warning'], 'replaySound(\'warning\');', '', '', true); -$table->data[26][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_warning', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; -$table->data[26][1] .= '
'; +$table->data[$i][0] = __('Sound for Monitor warning'); +$table->data[$i][1] = html_print_select($sounds, 'sound_warning', $config['sound_warning'], 'replaySound(\'warning\');', '', '', true); +$table->data[$i][1] .= ' '.html_print_image('images/control_play_col.png', true, ['id' => 'button_sound_warning', 'style' => 'vertical-align: middle;', 'width' => '16', 'title' => __('Play sound')]).''; +$table->data[$i++][1] .= '
'; -$table->data[28][0] = __('Public URL'); -$table->data[28][0] .= ui_print_help_tip( +$table->data[$i][0] = __('Public URL'); +$table->data[$i][0] .= ui_print_help_tip( __('Set this value when your %s across inverse proxy or for example with mod_proxy of Apache.', get_product_name()).' '.__('Without the index.php such as http://domain/console_url/'), true ); -$table->data[28][1] = html_print_input_text('public_url', $config['public_url'], '', 40, 255, true); +$table->data[$i++][1] = html_print_input_text('public_url', $config['public_url'], '', 40, 255, true); -$table->data[29][0] = __('Referer security'); -$table->data[29][0] .= ui_print_help_tip(__("If enabled, actively checks if the user comes from %s's URL", get_product_name()), true); -$table->data[29][1] = html_print_checkbox_switch('referer_security', 1, $config['referer_security'], true); +$table->data[$i][0] = __('Force use Public URL'); +$table->data[$i][0] .= ui_print_help_tip(__('Force using defined public URL).', get_product_name()), true); +$table->data[$i++][1] = html_print_switch( + [ + 'name' => 'force_public_url', + 'value' => $config['force_public_url'], + ] +); -$table->data[30][0] = __('Event storm protection'); -$table->data[30][0] .= ui_print_help_tip(__('If set to yes no events or alerts will be generated, but agents will continue receiving data.'), true); -$table->data[30][1] = html_print_checkbox_switch('event_storm_protection', 1, $config['event_storm_protection'], true); +echo "'; + +$table->data[$i][0] = __('Public URL host exclusions'); +$table->data[$i++][1] = html_print_textarea('public_url_exclusions', 2, 25, $config['public_url_exclusions'], 'style="height: 50px; width: 300px"', true); + +$table->data[$i][0] = __('Referer security'); +$table->data[$i][0] .= ui_print_help_tip(__("If enabled, actively checks if the user comes from %s's URL", get_product_name()), true); +$table->data[$i++][1] = html_print_checkbox_switch('referer_security', 1, $config['referer_security'], true); + +$table->data[$i][0] = __('Event storm protection'); +$table->data[$i][0] .= ui_print_help_tip(__('If set to yes no events or alerts will be generated, but agents will continue receiving data.'), true); +$table->data[$i++][1] = html_print_checkbox_switch('event_storm_protection', 1, $config['event_storm_protection'], true); -$table->data[31][0] = __('Command Snapshot').ui_print_help_tip(__('The string modules with several lines show as command output'), true); -$table->data[31][1] = html_print_checkbox_switch('command_snapshot', 1, $config['command_snapshot'], true); +$table->data[$i][0] = __('Command Snapshot').ui_print_help_tip(__('The string modules with several lines show as command output'), true); +$table->data[$i++][1] = html_print_checkbox_switch('command_snapshot', 1, $config['command_snapshot'], true); -$table->data[32][0] = __('Server logs directory').ui_print_help_tip(__('Directory where the server logs are stored.'), true); -$table->data[32][1] = html_print_input_text( +$table->data[$i][0] = __('Server logs directory').ui_print_help_tip(__('Directory where the server logs are stored.'), true); +$table->data[$i++][1] = html_print_input_text( 'server_log_dir', $config['server_log_dir'], '', @@ -242,8 +276,8 @@ $table->data[32][1] = html_print_input_text( true ); -$table->data[33][0] = __('Log size limit in system logs viewer extension').ui_print_help_tip(__('Max size (in bytes) for the logs to be shown.'), true); -$table->data[33][1] = html_print_input_text( +$table->data[$i][0] = __('Log size limit in system logs viewer extension').ui_print_help_tip(__('Max size (in bytes) for the logs to be shown.'), true); +$table->data[$i++][1] = html_print_input_text( 'max_log_size', $config['max_log_size'], '', @@ -257,8 +291,8 @@ $modes_tutorial = [ 'on_demand' => __('On demand'), 'expert' => __('Expert'), ]; -$table->data['tutorial_mode'][0] = __('Tutorial mode').ui_print_help_tip(__("Configuration of our clippy, 'full mode' show the icon in the header and the contextual helps and it is noise, 'on demand' it is equal to full but it is not noise and 'expert' the icons in the header and the context is not."), true); -$table->data['tutorial_mode'][1] = html_print_select( +$table->data[$i][0] = __('Tutorial mode').ui_print_help_tip(__("Configuration of our clippy, 'full mode' show the icon in the header and the contextual helps and it is noise, 'on demand' it is equal to full but it is not noise and 'expert' the icons in the header and the context is not."), true); +$table->data[$i++][1] = html_print_select( $modes_tutorial, 'tutorial_mode', $config['tutorial_mode'], @@ -269,11 +303,11 @@ $table->data['tutorial_mode'][1] = html_print_select( ); $config['past_planned_downtimes'] = isset($config['past_planned_downtimes']) ? $config['past_planned_downtimes'] : 1; -$table->data[34][0] = __('Allow create planned downtimes in the past').ui_print_help_tip(__('The planned downtimes created in the past will affect the SLA reports'), true); -$table->data[34][1] = html_print_checkbox_switch('past_planned_downtimes', 1, $config['past_planned_downtimes'], true); +$table->data[$i][0] = __('Allow create planned downtimes in the past').ui_print_help_tip(__('The planned downtimes created in the past will affect the SLA reports'), true); +$table->data[$i++][1] = html_print_checkbox_switch('past_planned_downtimes', 1, $config['past_planned_downtimes'], true); -$table->data[35][0] = __('Limit for bulk operations').ui_print_help_tip(__('Your PHP environment is set to 1000 max_input_vars. This parameter should have the same value or lower.', ini_get('max_input_vars')), true); -$table->data[35][1] = html_print_input_text( +$table->data[$i][0] = __('Limit for bulk operations').ui_print_help_tip(__('Your PHP environment is set to 1000 max_input_vars. This parameter should have the same value or lower.', ini_get('max_input_vars')), true); +$table->data[$i++][1] = html_print_input_text( 'limit_parameters_massive', $config['limit_parameters_massive'], '', @@ -282,17 +316,17 @@ $table->data[35][1] = html_print_input_text( true ); -$table->data[36][0] = __('Include agents manually disabled'); -$table->data[36][1] = html_print_checkbox_switch('include_agents', 1, $config['include_agents'], true); +$table->data[$i][0] = __('Include agents manually disabled'); +$table->data[$i++][1] = html_print_checkbox_switch('include_agents', 1, $config['include_agents'], true); -$table->data[37][0] = __('Audit log directory').ui_print_help_tip(__('Directory where audit log is stored.'), true); -$table->data[37][1] = html_print_input_text('auditdir', io_safe_output($config['auditdir']), '', 30, 100, true); +$table->data[$i][0] = __('Audit log directory').ui_print_help_tip(__('Directory where audit log is stored.'), true); +$table->data[$i++][1] = html_print_input_text('auditdir', io_safe_output($config['auditdir']), '', 30, 100, true); -$table->data[38][0] = __('Set alias as name by default in agent creation'); -$table->data[38][1] = html_print_checkbox_switch('alias_as_name', 1, $config['alias_as_name'], true); +$table->data[$i][0] = __('Set alias as name by default in agent creation'); +$table->data[$i++][1] = html_print_checkbox_switch('alias_as_name', 1, $config['alias_as_name'], true); -$table->data[39][0] = __('Unique IP').ui_print_help_tip(__('Set the primary IP address as the unique IP, preventing the same primary IP address from being used in more than one agent'), true); -$table->data[39][1] = html_print_checkbox_switch('unique_ip', 1, $config['unique_ip'], true); +$table->data[$i][0] = __('Unique IP').ui_print_help_tip(__('Set the primary IP address as the unique IP, preventing the same primary IP address from being used in more than one agent'), true); +$table->data[$i++][1] = html_print_checkbox_switch('unique_ip', 1, $config['unique_ip'], true); echo ''; @@ -394,44 +428,50 @@ $(document).ready (function () { }); if ($("input[name=use_cert]").is(':checked')) { - $('#setup_general-13').show(); + $('#ssl-path-tr').show(); } $("input[name=use_cert]").change(function () { if( $(this).is(":checked") ) - $('#setup_general-13').show(); + $('#ssl-path-tr').show(); else - $('#setup_general-13').hide(); + $('#ssl-path-tr').hide(); }); $("input[name=https]").change(function (){ if($("input[name=https]").prop('checked')) { - $("#dialog").css({'display': 'inline', 'font-weight': 'bold'}).dialog({ + $("#dialog").dialog({ modal: true, - buttons:{ - "": function(){ - $(this).dialog("close"); + width: 500, + buttons:[ + { + class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-next', + text: "", + click: function(){ + $(this).dialog("close"); + } } - } + ] + }); + } + }) + + $("input[name=force_public_url]").change(function (){ + if($("input[name=force_public_url]").prop('checked')) { + $("#force_public_url_dialog").dialog({ + modal: true, + width: 500, + buttons: [ + { + class: 'ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-next', + text: "", + click: function(){ + $(this).dialog("close"); + } + } + ] }); } }) }); -data[$row][1] = html_print_select( $table_styles->data[$row][1] .= ' '.html_print_button(__('View'), 'status_set_preview', false, '', 'class="sub camera logo_preview"', true); $row++; +// Divs to show icon status Colours (Default) +$icon_unknown_ball = ui_print_status_image(STATUS_AGENT_UNKNOWN_BALL, '', true); +$icon_unknown = ui_print_status_image(STATUS_AGENT_UNKNOWN, '', true); +$icon_ok_ball = ui_print_status_image(STATUS_AGENT_OK_BALL, '', true); +$icon_ok = ui_print_status_image(STATUS_AGENT_OK, '', true); +$icon_warning_ball = ui_print_status_image(STATUS_AGENT_WARNING_BALL, '', true); +$icon_warning = ui_print_status_image(STATUS_AGENT_WARNING, '', true); +$icon_bad_ball = ui_print_status_image(STATUS_AGENT_CRITICAL_BALL, '', true); +$icon_bad = ui_print_status_image(STATUS_AGENT_CRITICAL, '', true); +// End - Divs to show icon status Colours (Default) $table_styles->data[$row][0] = __('Login background').ui_print_help_tip(__('You can place your custom images into the folder images/backgrounds/'), true); $backgrounds_list_jpg = list_files('images/backgrounds', 'jpg', 1, 0); $backgrounds_list_gif = list_files('images/backgrounds', 'gif', 1, 0); @@ -1113,15 +1123,6 @@ $row++; - $table_other->data[$row][0] = __('Show QR Code icon in the header'); - $table_other->data[$row][1] = html_print_checkbox_switch( - 'show_qr_code_header', - 1, - $config['show_qr_code_header'], - true - ); - $row++; - $table_other->data[$row][0] = __('Custom graphviz directory').ui_print_help_tip(__('Custom directory where the graphviz binaries are stored.'), true); $table_other->data[$row][1] = html_print_input_text( 'graphviz_bin_dir', @@ -1504,7 +1505,7 @@ $(document).ready (function () { .prop('checked'); display_custom_report_front(custom_report,$(this).parent().parent().parent().parent().parent().attr('id')); }); - $(".databox.filters").css('margin-bottom','-10px'); + $(".databox.filters").css('margin-bottom','0px'); }); // Change the favicon preview when is changed @@ -1644,6 +1645,17 @@ $("#button-status_set_preview").click (function (e) { $icon_bad_ball = $(""); $icon_bad = $(""); + if(icon_dir == 'default'){ + $icon_unknown_ball = ''; + $icon_unknown = ''; + $icon_ok_ball = ''; + $icon_ok = ''; + $icon_warning_ball = ''; + $icon_warning = ''; + $icon_bad_ball = ''; + $icon_bad = ''; + } + try { $dialog .hide() diff --git a/pandora_console/godmode/snmpconsole/snmp_alert.php b/pandora_console/godmode/snmpconsole/snmp_alert.php index a2a1b8b811..66651d6522 100755 --- a/pandora_console/godmode/snmpconsole/snmp_alert.php +++ b/pandora_console/godmode/snmpconsole/snmp_alert.php @@ -1275,7 +1275,7 @@ if ($create_alert || $update_alert) { $table->align[7] = 'left'; $table->head[8] = __('Action'); - $table->size[8] = '90px'; + $table->size[8] = '120px'; $table->align[8] = 'left'; $table->head[9] = html_print_checkbox('all_delete_box', '1', false, true); diff --git a/pandora_console/godmode/snmpconsole/snmp_filters.php b/pandora_console/godmode/snmpconsole/snmp_filters.php index 0d8e1e9480..252373b15a 100644 --- a/pandora_console/godmode/snmpconsole/snmp_filters.php +++ b/pandora_console/godmode/snmpconsole/snmp_filters.php @@ -100,7 +100,15 @@ if ($update_filter > -2) { 'filter' => $filter, 'unified_filters_id' => $new_unified_id, ]; + if ($values['description'] == '') { + $result = false; + $msg = __('Description is empty'); + } else if ($values['filter'] == '') { + $result = false; + $msg = __('Filter is empty'); + } else { $result = db_process_sql_insert('tsnmp_filter', $values); + } } else { for ($i = 0; $i < $index_post; $i++) { $filter = get_parameter('filter_'.$i); @@ -109,12 +117,28 @@ if ($update_filter > -2) { 'filter' => $filter, 'unified_filters_id' => $new_unified_id, ]; - $result = db_process_sql_insert('tsnmp_filter', $values); + if ($values['filter'] != '' && $values['description'] != '') { + $result = db_process_sql_insert('tsnmp_filter', $values); + } + } + + if ($result === null) { + if ($values['description'] != '') { + $result = false; + $msg = __('Filters are empty'); + } else { + $result = false; + $msg = __('Description is empty'); + } } } if ($result === false) { - ui_print_error_message(__('There was a problem creating the filter')); + if (!isset($msg)) { + $msg = __('There was a problem creating the filter'); + } + + ui_print_error_message($msg); } else { ui_print_success_message(__('Successfully created')); } @@ -215,8 +239,10 @@ if ($edit_filter > -2) { $result_unified = db_get_all_rows_sql('SELECT DISTINCT(unified_filters_id) FROM tsnmp_filter ORDER BY unified_filters_id ASC'); $aglomerate_result = []; - foreach ($result_unified as $res) { - $aglomerate_result[$res['unified_filters_id']] = db_get_all_rows_sql('SELECT * FROM tsnmp_filter WHERE unified_filters_id = '.$res['unified_filters_id'].' ORDER BY id_snmp_filter ASC'); + if (is_array($result_unified) === true) { + foreach ($result_unified as $res) { + $aglomerate_result[$res['unified_filters_id']] = db_get_all_rows_sql('SELECT * FROM tsnmp_filter WHERE unified_filters_id = '.$res['unified_filters_id'].' ORDER BY id_snmp_filter ASC'); + } } $table = new stdClass(); @@ -282,7 +308,8 @@ if ($edit_filter > -2) { ?> '; + if ($rawjs) { + $output .= $rawjs; + } if ($return === false) { echo $output; @@ -869,10 +664,11 @@ class Wizard $rows = $data['rows']; $js = $data['js']; + $rawjs = $data['js_block']; $cb_function = $data['cb_function']; $cb_args = $data['cb_args']; - $output_head = ''; if ($return === false) { @@ -895,45 +691,47 @@ class Wizard $first_block_printed = false; - foreach ($rows as $row) { - if ($row['new_form_block'] == true) { - if ($first_block_printed === true) { - // If first form block has been placed, then close it before starting a new one. - $output .= '
'; - $output .= '
'; - } else { - $output .= '
'; + if (is_array($rows)) { + foreach ($rows as $row) { + if ($row['new_form_block'] == true) { + if ($first_block_printed === true) { + // If first form block has been placed, then close it before starting a new one. + $output .= '
'; + $output .= '
'; + } else { + $output .= '
'; + } + + $first_block_printed = true; } - $first_block_printed = true; - } + $output .= '
'; - $output .= '
'; + foreach ($row['columns'] as $column) { + $width = isset($column['width']) ? 'width: '.$column['width'].';' : 'width: 100%;'; + $padding_left = isset($column['padding-left']) ? 'padding-left: '.$column['padding-left'].';' : 'padding-left: 0;'; + $padding_right = isset($column['padding-right']) ? 'padding-right: '.$column['padding-right'].';' : 'padding-right: 0;'; + $extra_styles = isset($column['style']) ? $column['style'] : ''; - foreach ($row['columns'] as $column) { - $width = isset($column['width']) ? 'width: '.$column['width'].';' : 'width: 100%;'; - $padding_left = isset($column['padding-left']) ? 'padding-left: '.$column['padding-left'].';' : 'padding-left: 0;'; - $padding_right = isset($column['padding-right']) ? 'padding-right: '.$column['padding-right'].';' : 'padding-right: 0;'; - $extra_styles = isset($column['style']) ? $column['style'] : ''; + $output .= '
'; - $output .= '
'; - - foreach ($column['inputs'] as $input) { - if (is_array($input)) { - if ($input['arguments']['type'] != 'submit') { - $output .= $this->printBlockAsGrid($input, true); + foreach ($column['inputs'] as $input) { + if (is_array($input)) { + if ($input['arguments']['type'] != 'submit') { + $output .= $this->printBlockAsGrid($input, true); + } else { + $output_submit .= $this->printBlockAsGrid($input, true); + } } else { - $output_submit .= $this->printBlockAsGrid($input, true); + $output .= $input; } - } else { - $output .= $input; } + + $output .= '
'; } $output .= '
'; } - - $output .= '
'; } $output .= '
'; @@ -941,6 +739,9 @@ class Wizard $output .= '
    '.$output_submit.'
'; $output .= ''; $output .= ''; + if ($rawjs) { + $output .= $rawjs; + } if ($return === false) { echo $output; @@ -964,10 +765,11 @@ class Wizard $form = $data['form']; $inputs = $data['inputs']; $js = $data['js']; + $rawjs = $data['js_block']; $cb_function = $data['cb_function']; $cb_args = $data['cb_args']; - $output_head = '
'; if ($return === false) { @@ -1001,6 +803,9 @@ class Wizard $output .= '
    '.$output_submit.'
'; $output .= '
'; $output .= ''; + if ($rawjs) { + $output .= $rawjs; + } if ($return === false) { echo $output; @@ -1048,7 +853,7 @@ class Wizard */ public static function printBigButtonsList($list_data) { - echo '
    '; + echo '
      '; array_map('self::printBigButtonElement', $list_data); echo '
    '; } diff --git a/pandora_console/images/arrow_left_green.png b/pandora_console/images/arrow_left_green.png new file mode 100644 index 0000000000..b6aadc9639 Binary files /dev/null and b/pandora_console/images/arrow_left_green.png differ diff --git a/pandora_console/images/console/background/fondo.jpg b/pandora_console/images/console/background/fondo.jpg new file mode 100644 index 0000000000..817ab9d050 Binary files /dev/null and b/pandora_console/images/console/background/fondo.jpg differ diff --git a/pandora_console/images/console/icons/rack_double_server.png b/pandora_console/images/console/icons/rack_double_server.png new file mode 100644 index 0000000000..7ce45ab718 Binary files /dev/null and b/pandora_console/images/console/icons/rack_double_server.png differ diff --git a/pandora_console/images/console/icons/rack_double_server_bad.png b/pandora_console/images/console/icons/rack_double_server_bad.png new file mode 100644 index 0000000000..94ada7ad16 Binary files /dev/null and b/pandora_console/images/console/icons/rack_double_server_bad.png differ diff --git a/pandora_console/images/console/icons/rack_double_server_ok.png b/pandora_console/images/console/icons/rack_double_server_ok.png new file mode 100644 index 0000000000..8a06465a3c Binary files /dev/null and b/pandora_console/images/console/icons/rack_double_server_ok.png differ diff --git a/pandora_console/images/console/icons/rack_double_server_warning.png b/pandora_console/images/console/icons/rack_double_server_warning.png new file mode 100644 index 0000000000..2639b16afd Binary files /dev/null and b/pandora_console/images/console/icons/rack_double_server_warning.png differ diff --git a/pandora_console/images/console/icons/rack_firewall.png b/pandora_console/images/console/icons/rack_firewall.png new file mode 100644 index 0000000000..7635fd6d57 Binary files /dev/null and b/pandora_console/images/console/icons/rack_firewall.png differ diff --git a/pandora_console/images/console/icons/rack_firewall_bad.png b/pandora_console/images/console/icons/rack_firewall_bad.png new file mode 100644 index 0000000000..5c6ea2e2b0 Binary files /dev/null and b/pandora_console/images/console/icons/rack_firewall_bad.png differ diff --git a/pandora_console/images/console/icons/rack_firewall_ok.png b/pandora_console/images/console/icons/rack_firewall_ok.png new file mode 100644 index 0000000000..bb245983a1 Binary files /dev/null and b/pandora_console/images/console/icons/rack_firewall_ok.png differ diff --git a/pandora_console/images/console/icons/rack_firewall_warning.png b/pandora_console/images/console/icons/rack_firewall_warning.png new file mode 100644 index 0000000000..0b2a3150fa Binary files /dev/null and b/pandora_console/images/console/icons/rack_firewall_warning.png differ diff --git a/pandora_console/images/console/icons/rack_frame.png b/pandora_console/images/console/icons/rack_frame.png new file mode 100644 index 0000000000..91baaa7c8a Binary files /dev/null and b/pandora_console/images/console/icons/rack_frame.png differ diff --git a/pandora_console/images/console/icons/rack_frame_bad.png b/pandora_console/images/console/icons/rack_frame_bad.png new file mode 100644 index 0000000000..c6ed4cff03 Binary files /dev/null and b/pandora_console/images/console/icons/rack_frame_bad.png differ diff --git a/pandora_console/images/console/icons/rack_frame_ok.png b/pandora_console/images/console/icons/rack_frame_ok.png new file mode 100644 index 0000000000..4743ff5d88 Binary files /dev/null and b/pandora_console/images/console/icons/rack_frame_ok.png differ diff --git a/pandora_console/images/console/icons/rack_frame_warning.png b/pandora_console/images/console/icons/rack_frame_warning.png new file mode 100644 index 0000000000..a30b937218 Binary files /dev/null and b/pandora_console/images/console/icons/rack_frame_warning.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk.png b/pandora_console/images/console/icons/rack_hard_disk.png new file mode 100644 index 0000000000..f445bd2d62 Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_2.png b/pandora_console/images/console/icons/rack_hard_disk_2.png new file mode 100644 index 0000000000..26f646b2bb Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_2.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_2_bad.png b/pandora_console/images/console/icons/rack_hard_disk_2_bad.png new file mode 100644 index 0000000000..f41143f2bd Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_2_bad.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_2_ok.png b/pandora_console/images/console/icons/rack_hard_disk_2_ok.png new file mode 100644 index 0000000000..2db4df0236 Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_2_ok.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_2_warning.png b/pandora_console/images/console/icons/rack_hard_disk_2_warning.png new file mode 100644 index 0000000000..f0d3c4d28d Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_2_warning.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_bad.png b/pandora_console/images/console/icons/rack_hard_disk_bad.png new file mode 100644 index 0000000000..d1a9d1ac3f Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_bad.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_ok.png b/pandora_console/images/console/icons/rack_hard_disk_ok.png new file mode 100644 index 0000000000..49b7f42aec Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_ok.png differ diff --git a/pandora_console/images/console/icons/rack_hard_disk_warning.png b/pandora_console/images/console/icons/rack_hard_disk_warning.png new file mode 100644 index 0000000000..4be91d1054 Binary files /dev/null and b/pandora_console/images/console/icons/rack_hard_disk_warning.png differ diff --git a/pandora_console/images/console/icons/rack_pdu.png b/pandora_console/images/console/icons/rack_pdu.png new file mode 100644 index 0000000000..4cdefdaae9 Binary files /dev/null and b/pandora_console/images/console/icons/rack_pdu.png differ diff --git a/pandora_console/images/console/icons/rack_pdu_bad.png b/pandora_console/images/console/icons/rack_pdu_bad.png new file mode 100644 index 0000000000..7017cd43ec Binary files /dev/null and b/pandora_console/images/console/icons/rack_pdu_bad.png differ diff --git a/pandora_console/images/console/icons/rack_pdu_ok.png b/pandora_console/images/console/icons/rack_pdu_ok.png new file mode 100644 index 0000000000..2490ad2bc5 Binary files /dev/null and b/pandora_console/images/console/icons/rack_pdu_ok.png differ diff --git a/pandora_console/images/console/icons/rack_pdu_warning.png b/pandora_console/images/console/icons/rack_pdu_warning.png new file mode 100644 index 0000000000..a825c8adfc Binary files /dev/null and b/pandora_console/images/console/icons/rack_pdu_warning.png differ diff --git a/pandora_console/images/console/icons/rack_psa.png b/pandora_console/images/console/icons/rack_psa.png new file mode 100644 index 0000000000..28681104e4 Binary files /dev/null and b/pandora_console/images/console/icons/rack_psa.png differ diff --git a/pandora_console/images/console/icons/rack_psa_bad.png b/pandora_console/images/console/icons/rack_psa_bad.png new file mode 100644 index 0000000000..c777b83b73 Binary files /dev/null and b/pandora_console/images/console/icons/rack_psa_bad.png differ diff --git a/pandora_console/images/console/icons/rack_psa_ok.png b/pandora_console/images/console/icons/rack_psa_ok.png new file mode 100644 index 0000000000..3b66174ab8 Binary files /dev/null and b/pandora_console/images/console/icons/rack_psa_ok.png differ diff --git a/pandora_console/images/console/icons/rack_psa_warning.png b/pandora_console/images/console/icons/rack_psa_warning.png new file mode 100644 index 0000000000..ed4fa00355 Binary files /dev/null and b/pandora_console/images/console/icons/rack_psa_warning.png differ diff --git a/pandora_console/images/console/icons/rack_router.png b/pandora_console/images/console/icons/rack_router.png new file mode 100644 index 0000000000..905d4cf5b3 Binary files /dev/null and b/pandora_console/images/console/icons/rack_router.png differ diff --git a/pandora_console/images/console/icons/rack_router_bad.png b/pandora_console/images/console/icons/rack_router_bad.png new file mode 100644 index 0000000000..2d44cc62af Binary files /dev/null and b/pandora_console/images/console/icons/rack_router_bad.png differ diff --git a/pandora_console/images/console/icons/rack_router_ok.png b/pandora_console/images/console/icons/rack_router_ok.png new file mode 100644 index 0000000000..404ba7d854 Binary files /dev/null and b/pandora_console/images/console/icons/rack_router_ok.png differ diff --git a/pandora_console/images/console/icons/rack_router_warning.png b/pandora_console/images/console/icons/rack_router_warning.png new file mode 100644 index 0000000000..11fe7ebcc8 Binary files /dev/null and b/pandora_console/images/console/icons/rack_router_warning.png differ diff --git a/pandora_console/images/console/icons/rack_server.png b/pandora_console/images/console/icons/rack_server.png new file mode 100644 index 0000000000..007a801146 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server.png differ diff --git a/pandora_console/images/console/icons/rack_server_bad.png b/pandora_console/images/console/icons/rack_server_bad.png new file mode 100644 index 0000000000..afd8e3ba93 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_bad.png differ diff --git a/pandora_console/images/console/icons/rack_server_ok.png b/pandora_console/images/console/icons/rack_server_ok.png new file mode 100644 index 0000000000..1ef4b9e1c2 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_ok.png differ diff --git a/pandora_console/images/console/icons/rack_server_rack.png b/pandora_console/images/console/icons/rack_server_rack.png new file mode 100644 index 0000000000..884b42e668 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_rack.png differ diff --git a/pandora_console/images/console/icons/rack_server_rack_bad.png b/pandora_console/images/console/icons/rack_server_rack_bad.png new file mode 100644 index 0000000000..29e5e4b4ef Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_rack_bad.png differ diff --git a/pandora_console/images/console/icons/rack_server_rack_ok.png b/pandora_console/images/console/icons/rack_server_rack_ok.png new file mode 100644 index 0000000000..2f346bb2d1 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_rack_ok.png differ diff --git a/pandora_console/images/console/icons/rack_server_rack_warning.png b/pandora_console/images/console/icons/rack_server_rack_warning.png new file mode 100644 index 0000000000..a30d308a52 Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_rack_warning.png differ diff --git a/pandora_console/images/console/icons/rack_server_warning.png b/pandora_console/images/console/icons/rack_server_warning.png new file mode 100644 index 0000000000..08faef378b Binary files /dev/null and b/pandora_console/images/console/icons/rack_server_warning.png differ diff --git a/pandora_console/images/console/icons/rack_switch.png b/pandora_console/images/console/icons/rack_switch.png new file mode 100644 index 0000000000..9ac9e73b63 Binary files /dev/null and b/pandora_console/images/console/icons/rack_switch.png differ diff --git a/pandora_console/images/console/icons/rack_switch_bad.png b/pandora_console/images/console/icons/rack_switch_bad.png new file mode 100644 index 0000000000..73c5da7956 Binary files /dev/null and b/pandora_console/images/console/icons/rack_switch_bad.png differ diff --git a/pandora_console/images/console/icons/rack_switch_ok.png b/pandora_console/images/console/icons/rack_switch_ok.png new file mode 100644 index 0000000000..c5177785a4 Binary files /dev/null and b/pandora_console/images/console/icons/rack_switch_ok.png differ diff --git a/pandora_console/images/console/icons/rack_switch_warning.png b/pandora_console/images/console/icons/rack_switch_warning.png new file mode 100644 index 0000000000..188a82ca88 Binary files /dev/null and b/pandora_console/images/console/icons/rack_switch_warning.png differ diff --git a/pandora_console/images/deploy.png b/pandora_console/images/deploy.png new file mode 100644 index 0000000000..1cb28a44fb Binary files /dev/null and b/pandora_console/images/deploy.png differ diff --git a/pandora_console/images/groups_small_white/application_osx.png b/pandora_console/images/groups_small_white/application_osx.png new file mode 100644 index 0000000000..409d9742d2 Binary files /dev/null and b/pandora_console/images/groups_small_white/application_osx.png differ diff --git a/pandora_console/images/groups_small_white/application_osx_terminal.png b/pandora_console/images/groups_small_white/application_osx_terminal.png new file mode 100644 index 0000000000..3deb76aa34 Binary files /dev/null and b/pandora_console/images/groups_small_white/application_osx_terminal.png differ diff --git a/pandora_console/images/groups_small_white/applications.png b/pandora_console/images/groups_small_white/applications.png new file mode 100644 index 0000000000..362ed8b98d Binary files /dev/null and b/pandora_console/images/groups_small_white/applications.png differ diff --git a/pandora_console/images/groups_small_white/bricks.png b/pandora_console/images/groups_small_white/bricks.png new file mode 100644 index 0000000000..b68255b88b Binary files /dev/null and b/pandora_console/images/groups_small_white/bricks.png differ diff --git a/pandora_console/images/groups_small_white/chart_organisation.png b/pandora_console/images/groups_small_white/chart_organisation.png new file mode 100644 index 0000000000..d80fc4f65f Binary files /dev/null and b/pandora_console/images/groups_small_white/chart_organisation.png differ diff --git a/pandora_console/images/groups_small_white/clock.png b/pandora_console/images/groups_small_white/clock.png new file mode 100644 index 0000000000..dc16f55773 Binary files /dev/null and b/pandora_console/images/groups_small_white/clock.png differ diff --git a/pandora_console/images/groups_small_white/computer.png b/pandora_console/images/groups_small_white/computer.png new file mode 100644 index 0000000000..5eab00e255 Binary files /dev/null and b/pandora_console/images/groups_small_white/computer.png differ diff --git a/pandora_console/images/groups_small_white/database.png b/pandora_console/images/groups_small_white/database.png new file mode 100644 index 0000000000..397f3fa5d3 Binary files /dev/null and b/pandora_console/images/groups_small_white/database.png differ diff --git a/pandora_console/images/groups_small_white/database_gear.png b/pandora_console/images/groups_small_white/database_gear.png new file mode 100644 index 0000000000..72a6b63d0f Binary files /dev/null and b/pandora_console/images/groups_small_white/database_gear.png differ diff --git a/pandora_console/images/groups_small_white/drive_network.png b/pandora_console/images/groups_small_white/drive_network.png new file mode 100644 index 0000000000..4e1cd615c6 Binary files /dev/null and b/pandora_console/images/groups_small_white/drive_network.png differ diff --git a/pandora_console/images/groups_small_white/email.png b/pandora_console/images/groups_small_white/email.png new file mode 100644 index 0000000000..496991da88 Binary files /dev/null and b/pandora_console/images/groups_small_white/email.png differ diff --git a/pandora_console/images/groups_small_white/eye.png b/pandora_console/images/groups_small_white/eye.png new file mode 100644 index 0000000000..f5c8a4e940 Binary files /dev/null and b/pandora_console/images/groups_small_white/eye.png differ diff --git a/pandora_console/images/groups_small_white/firewall.png b/pandora_console/images/groups_small_white/firewall.png new file mode 100644 index 0000000000..261adbcb1e Binary files /dev/null and b/pandora_console/images/groups_small_white/firewall.png differ diff --git a/pandora_console/images/groups_small_white/heart.png b/pandora_console/images/groups_small_white/heart.png new file mode 100644 index 0000000000..6bfec0298a Binary files /dev/null and b/pandora_console/images/groups_small_white/heart.png differ diff --git a/pandora_console/images/groups_small_white/house.png b/pandora_console/images/groups_small_white/house.png new file mode 100644 index 0000000000..72ab42dd35 Binary files /dev/null and b/pandora_console/images/groups_small_white/house.png differ diff --git a/pandora_console/images/groups_small_white/images.png b/pandora_console/images/groups_small_white/images.png new file mode 100644 index 0000000000..195c7e222b Binary files /dev/null and b/pandora_console/images/groups_small_white/images.png differ diff --git a/pandora_console/images/groups_small_white/lightning.png b/pandora_console/images/groups_small_white/lightning.png new file mode 100644 index 0000000000..31a0670a68 Binary files /dev/null and b/pandora_console/images/groups_small_white/lightning.png differ diff --git a/pandora_console/images/groups_small_white/lock.png b/pandora_console/images/groups_small_white/lock.png new file mode 100644 index 0000000000..522ff71bd6 Binary files /dev/null and b/pandora_console/images/groups_small_white/lock.png differ diff --git a/pandora_console/images/groups_small_white/network.png b/pandora_console/images/groups_small_white/network.png new file mode 100644 index 0000000000..1a8573a729 Binary files /dev/null and b/pandora_console/images/groups_small_white/network.png differ diff --git a/pandora_console/images/groups_small_white/plugin.png b/pandora_console/images/groups_small_white/plugin.png new file mode 100644 index 0000000000..051ec05d6b Binary files /dev/null and b/pandora_console/images/groups_small_white/plugin.png differ diff --git a/pandora_console/images/groups_small_white/printer.png b/pandora_console/images/groups_small_white/printer.png new file mode 100644 index 0000000000..4187e87a00 Binary files /dev/null and b/pandora_console/images/groups_small_white/printer.png differ diff --git a/pandora_console/images/groups_small_white/server_database.png b/pandora_console/images/groups_small_white/server_database.png new file mode 100644 index 0000000000..864e3cb7cb Binary files /dev/null and b/pandora_console/images/groups_small_white/server_database.png differ diff --git a/pandora_console/images/groups_small_white/transmit.png b/pandora_console/images/groups_small_white/transmit.png new file mode 100644 index 0000000000..d27f5c377d Binary files /dev/null and b/pandora_console/images/groups_small_white/transmit.png differ diff --git a/pandora_console/images/groups_small_white/without_group.png b/pandora_console/images/groups_small_white/without_group.png new file mode 100644 index 0000000000..30915bd101 Binary files /dev/null and b/pandora_console/images/groups_small_white/without_group.png differ diff --git a/pandora_console/images/groups_small_white/world.png b/pandora_console/images/groups_small_white/world.png new file mode 100644 index 0000000000..dcfd04139b Binary files /dev/null and b/pandora_console/images/groups_small_white/world.png differ diff --git a/pandora_console/images/heartbeat_green.gif b/pandora_console/images/heartbeat_green.gif new file mode 100644 index 0000000000..a985013064 Binary files /dev/null and b/pandora_console/images/heartbeat_green.gif differ diff --git a/pandora_console/images/heartbeat_green_black.gif b/pandora_console/images/heartbeat_green_black.gif new file mode 100644 index 0000000000..b365cade3f Binary files /dev/null and b/pandora_console/images/heartbeat_green_black.gif differ diff --git a/pandora_console/images/heartbeat_red.gif b/pandora_console/images/heartbeat_red.gif new file mode 100644 index 0000000000..abc8d83832 Binary files /dev/null and b/pandora_console/images/heartbeat_red.gif differ diff --git a/pandora_console/images/heartbeat_red_black.gif b/pandora_console/images/heartbeat_red_black.gif new file mode 100644 index 0000000000..90fed812db Binary files /dev/null and b/pandora_console/images/heartbeat_red_black.gif differ diff --git a/pandora_console/images/input_deploy.png b/pandora_console/images/input_deploy.png new file mode 100644 index 0000000000..c66f4ddd56 Binary files /dev/null and b/pandora_console/images/input_deploy.png differ diff --git a/pandora_console/images/status_sets/default/module_alertsfired_rounded.png b/pandora_console/images/status_sets/default/module_alertsfired_rounded.png deleted file mode 100644 index 7a9b5ae0cd..0000000000 Binary files a/pandora_console/images/status_sets/default/module_alertsfired_rounded.png and /dev/null differ diff --git a/pandora_console/images/status_sets/default/module_critical_rounded.png b/pandora_console/images/status_sets/default/module_critical_rounded.png deleted file mode 100644 index 7fceda18da..0000000000 Binary files a/pandora_console/images/status_sets/default/module_critical_rounded.png and /dev/null differ diff --git a/pandora_console/images/status_sets/default/module_no_data_rounded.png b/pandora_console/images/status_sets/default/module_no_data_rounded.png deleted file mode 100644 index fd5e433ece..0000000000 Binary files a/pandora_console/images/status_sets/default/module_no_data_rounded.png and /dev/null differ diff --git a/pandora_console/images/status_sets/default/module_ok_rounded.png b/pandora_console/images/status_sets/default/module_ok_rounded.png deleted file mode 100644 index d47f2ef4ff..0000000000 Binary files a/pandora_console/images/status_sets/default/module_ok_rounded.png and /dev/null differ diff --git a/pandora_console/images/status_sets/default/module_unknown_rounded.png b/pandora_console/images/status_sets/default/module_unknown_rounded.png deleted file mode 100644 index 2ec6d98f39..0000000000 Binary files a/pandora_console/images/status_sets/default/module_unknown_rounded.png and /dev/null differ diff --git a/pandora_console/images/status_sets/default/module_warning_rounded.png b/pandora_console/images/status_sets/default/module_warning_rounded.png deleted file mode 100644 index c28924178d..0000000000 Binary files a/pandora_console/images/status_sets/default/module_warning_rounded.png and /dev/null differ diff --git a/pandora_console/images/user_email.png b/pandora_console/images/user_email.png index 095b012a5c..446c90f760 100644 Binary files a/pandora_console/images/user_email.png and b/pandora_console/images/user_email.png differ diff --git a/pandora_console/images/wizard/customnetscan.png b/pandora_console/images/wizard/customnetscan.png index edc036fa39..5ef82eb7d5 100644 Binary files a/pandora_console/images/wizard/customnetscan.png and b/pandora_console/images/wizard/customnetscan.png differ diff --git a/pandora_console/images/wizard/netscan.png b/pandora_console/images/wizard/netscan.png index c90f4ddc5d..66894fb446 100644 Binary files a/pandora_console/images/wizard/netscan.png and b/pandora_console/images/wizard/netscan.png differ diff --git a/pandora_console/images/wizard/netscan_green.png b/pandora_console/images/wizard/netscan_green.png index faeae9b042..c602e96ac5 100644 Binary files a/pandora_console/images/wizard/netscan_green.png and b/pandora_console/images/wizard/netscan_green.png differ diff --git a/pandora_console/images/wizard/tasklist.png b/pandora_console/images/wizard/tasklist.png index 3250311b69..0875145b8a 100644 Binary files a/pandora_console/images/wizard/tasklist.png and b/pandora_console/images/wizard/tasklist.png differ diff --git a/pandora_console/include/ajax/agent.php b/pandora_console/include/ajax/agent.php index 50fe7dc992..698ab7df9b 100644 --- a/pandora_console/include/ajax/agent.php +++ b/pandora_console/include/ajax/agent.php @@ -63,6 +63,7 @@ if ($get_agents_group) { if ($search_agents && (!is_metaconsole() || $force_local)) { $id_agent = (int) get_parameter('id_agent'); $string = (string) get_parameter('q'); + $string = strtoupper($string); // q is what autocomplete plugin gives $id_group = (int) get_parameter('id_group', -1); $addedItems = html_entity_decode((string) get_parameter('add')); @@ -98,11 +99,11 @@ if ($search_agents && (!is_metaconsole() || $force_local)) { $filter_alias = $filter; switch ($config['dbtype']) { case 'mysql': - $filter_alias[] = '(alias LIKE "%'.$string.'%")'; + $filter_alias[] = '(UPPER(alias) LIKE "%'.$string.'%")'; break; case 'postgresql': - $filter_alias[] = '(alias LIKE \'%'.$string.'%\')'; + $filter_alias[] = '(UPPER(alias) LIKE \'%'.$string.'%\')'; break; case 'oracle': @@ -127,11 +128,11 @@ if ($search_agents && (!is_metaconsole() || $force_local)) { $filter_agents = $filter; switch ($config['dbtype']) { case 'mysql': - $filter_agents[] = '(alias NOT LIKE "%'.$string.'%" AND nombre COLLATE utf8_general_ci LIKE "%'.$string.'%")'; + $filter_agents[] = '(UPPER(alias) NOT LIKE "%'.$string.'%" AND UPPER(nombre) COLLATE utf8_general_ci LIKE "%'.$string.'%")'; break; case 'postgresql': - $filter_agents[] = '(alias NOT LIKE \'%'.$string.'%\' AND nombre LIKE \'%'.$string.'%\')'; + $filter_agents[] = '(UPPER(alias) NOT LIKE \'%'.$string.'%\' AND UPPER(nombre) LIKE \'%'.$string.'%\')'; break; case 'oracle': @@ -156,11 +157,11 @@ if ($search_agents && (!is_metaconsole() || $force_local)) { $filter_address = $filter; switch ($config['dbtype']) { case 'mysql': - $filter_address[] = '(alias NOT LIKE "%'.$string.'%" AND nombre COLLATE utf8_general_ci NOT LIKE "%'.$string.'%" AND direccion LIKE "%'.$string.'%")'; + $filter_address[] = '(UPPER(alias) NOT LIKE "%'.$string.'%" AND UPPER(nombre) COLLATE utf8_general_ci NOT LIKE "%'.$string.'%" AND UPPER(direccion) LIKE "%'.$string.'%")'; break; case 'postgresql': - $filter_address[] = '(alias NOT LIKE \'%'.$string.'%\' AND nombre NOT LIKE \'%'.$string.'%\' AND direccion LIKE \'%'.$string.'%\')'; + $filter_address[] = '(UPPER(alias) NOT LIKE \'%'.$string.'%\' AND UPPER(nombre) NOT LIKE \'%'.$string.'%\' AND UPPER(direccion) LIKE \'%'.$string.'%\')'; break; case 'oracle': @@ -185,11 +186,11 @@ if ($search_agents && (!is_metaconsole() || $force_local)) { $filter_description = $filter; switch ($config['dbtype']) { case 'mysql': - $filter_description[] = '(alias NOT LIKE "%'.$string.'%" AND nombre COLLATE utf8_general_ci NOT LIKE "%'.$string.'%" AND direccion NOT LIKE "%'.$string.'%" AND comentarios LIKE "%'.$string.'%")'; + $filter_description[] = '(UPPER(alias) NOT LIKE "%'.$string.'%" AND UPPER(nombre) COLLATE utf8_general_ci NOT LIKE "%'.$string.'%" AND UPPER(direccion) NOT LIKE "%'.$string.'%" AND UPPER(comentarios) LIKE "%'.$string.'%")'; break; case 'postgresql': - $filter_description[] = '(alias NOT LIKE \'%'.$string.'%\' AND nombre NOT LIKE \'%'.$string.'%\' AND direccion NOT LIKE \'%'.$string.'%\' AND comentarios LIKE \'%'.$string.'%\')'; + $filter_description[] = '(UPPER(alias) NOT LIKE \'%'.$string.'%\' AND UPPER(nombre) NOT LIKE \'%'.$string.'%\' AND UPPER(direccion) NOT LIKE \'%'.$string.'%\' AND UPPER(comentarios) LIKE \'%'.$string.'%\')'; break; case 'oracle': diff --git a/pandora_console/include/ajax/alert_list.ajax.php b/pandora_console/include/ajax/alert_list.ajax.php index b8c3705046..3f724b4e58 100644 --- a/pandora_console/include/ajax/alert_list.ajax.php +++ b/pandora_console/include/ajax/alert_list.ajax.php @@ -159,10 +159,10 @@ if ($show_update_action_menu) { $id_action = (int) get_parameter('id_action'); $actions = alerts_get_alert_agent_module_actions($id_alert); - $action_opction = db_get_row( + $action_option = db_get_row( 'talert_template_module_actions', - 'id_alert_template_module', - $id_alert + 'id', + $id_action ); $data .= '
    '; @@ -242,7 +242,7 @@ if ($show_update_action_menu) { $data .= '
'; $data .= html_print_input_text( 'fires_min_ajax', - $action_opction['fires_min'], + $action_option['fires_min'], '', 4, 10, @@ -251,7 +251,7 @@ if ($show_update_action_menu) { $data .= ' '.__('to').' '; $data .= html_print_input_text( 'fires_max_ajax', - $action_opction['fires_max'], + $action_option['fires_max'], '', 4, 10, @@ -266,7 +266,7 @@ if ($show_update_action_menu) { $data .= ''; $data .= html_print_input_text( 'module_action_threshold_ajax', - $action_opction['module_action_threshold'], + $action_option['module_action_threshold'], '', 4, 10, diff --git a/pandora_console/include/ajax/custom_fields.php b/pandora_console/include/ajax/custom_fields.php index 9baacdcdc2..85066675a1 100644 --- a/pandora_console/include/ajax/custom_fields.php +++ b/pandora_console/include/ajax/custom_fields.php @@ -279,7 +279,7 @@ if (check_login()) { 'agent_small', false, true, - false, + true, '[…]', 'font-size:7.5pt;' ); @@ -292,13 +292,14 @@ if (check_login()) { $data[] = [ 'ref' => $referencia, - 'data_custom_field' => $values['name_custom_fields'], + 'data_custom_field' => ui_bbcode_to_html($values['name_custom_fields']), 'server' => $values['server_name'], 'agent' => $agent, 'IP' => $values['direccion'], 'status' => "
".$image_status.'
', 'id_agent' => $values['id_tagente'], 'id_server' => $values['id_tmetaconsole_setup'], + 'status_value' => $values['status'], ]; } diff --git a/pandora_console/include/ajax/events.php b/pandora_console/include/ajax/events.php index b58a3c2386..ad9d59a748 100644 --- a/pandora_console/include/ajax/events.php +++ b/pandora_console/include/ajax/events.php @@ -26,6 +26,9 @@ * ============================================================================ */ +// Begin. +global $config; + require_once 'include/functions_events.php'; require_once 'include/functions_agents.php'; require_once 'include/functions_ui.php'; @@ -35,6 +38,21 @@ require_once 'include/functions.php'; enterprise_include_once('meta/include/functions_events_meta.php'); enterprise_include_once('include/functions_metaconsole.php'); +// Check access. +check_login(); + +if (! check_acl($config['id_user'], 0, 'ER') + && ! check_acl($config['id_user'], 0, 'EW') + && ! check_acl($config['id_user'], 0, 'EM') +) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + include 'general/noaccess.php'; + return; +} + $get_events_details = (bool) get_parameter('get_events_details'); $get_list_events_agents = (bool) get_parameter('get_list_events_agents'); $get_extended_event = (bool) get_parameter('get_extended_event'); @@ -55,6 +73,752 @@ $total_events = (bool) get_parameter('total_events'); $total_event_graph = (bool) get_parameter('total_event_graph'); $graphic_event_group = (bool) get_parameter('graphic_event_group'); $get_table_response_command = (bool) get_parameter('get_table_response_command'); +$save_filter_modal = get_parameter('save_filter_modal', 0); +$load_filter_modal = get_parameter('load_filter_modal', 0); +$get_filter_values = get_parameter('get_filter_values', 0); +$update_event_filter = get_parameter('update_event_filter', 0); +$save_event_filter = get_parameter('save_event_filter', 0); +$in_process_event = get_parameter('in_process_event', 0); +$validate_event = get_parameter('validate_event', 0); +$delete_event = get_parameter('delete_event', 0); +$get_event_filters = get_parameter('get_event_filters', 0); +$get_comments = get_parameter('get_comments', 0); +$get_events_fired = (bool) get_parameter('get_events_fired'); + +if ($get_comments) { + $event = get_parameter('event', false); + $filter = get_parameter('filter', false); + + if ($event === false) { + return __('Failed to retrieve comments'); + } + + if ($filter['group_rep'] == 1) { + $events = events_get_all( + ['te.*'], + // Filter. + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // History. + $filter['history'], + // Return_sql. + false, + // Having. + sprintf( + ' HAVING max_id_evento = %d', + $event['id_evento'] + ) + ); + if ($events !== false) { + $event = $events[0]; + } + } else { + $events = events_get_event( + $event['id_evento'], + false, + $meta, + $history + ); + + if ($events !== false) { + $event = $events[0]; + } + } + + echo events_page_comments($event, true); + + return; +} + +if ($get_event_filters) { + $event_filter = events_get_event_filter_select(); + + echo io_json_mb_encode($event_filter); + return; +} + +// Delete event (filtered or not). +if ($delete_event) { + $filter = get_parameter('filter', []); + $id_evento = get_parameter('id_evento', 0); + $event_rep = get_parameter('event_rep', 0); + + if ($event_rep === 0) { + // Disable group by when there're result is unique. + $filter['group_rep'] = 0; + } + + // Check acl. + if (! check_acl($config['id_user'], 0, 'EM')) { + echo 'unauthorized'; + return; + } + + $r = events_delete($id_evento, $filter); + if ($r === false) { + echo 'Failed'; + } else { + echo $r; + } + + return; +} + +// Validates an event (filtered or not). +if ($validate_event) { + $filter = get_parameter('filter', []); + $id_evento = get_parameter('id_evento', 0); + $event_rep = get_parameter('event_rep', 0); + + if ($event_rep === 0) { + // Disable group by when there're result is unique. + $filter['group_rep'] = 0; + } + + // Check acl. + if (! check_acl($config['id_user'], 0, 'EW')) { + echo 'unauthorized'; + return; + } + + $r = events_update_status($id_evento, EVENT_VALIDATE, $filter); + if ($r === false) { + echo 'Failed'; + } else { + echo $r; + } + + return; +} + +// Sets status to in progress. +if ($in_process_event) { + $filter = get_parameter('filter', []); + $id_evento = get_parameter('id_evento', 0); + $event_rep = get_parameter('event_rep', 0); + + if ($event_rep === 0) { + // Disable group by when there're result is unique. + $filter['group_rep'] = 0; + } + + // Check acl. + if (! check_acl($config['id_user'], 0, 'EW')) { + echo 'unauthorized'; + return; + } + + $r = events_update_status($id_evento, EVENT_PROCESS, $filter); + if ($r === false) { + echo 'Failed'; + } else { + echo $r; + } + + return; +} + +// Saves an event filter. +if ($save_event_filter) { + $values = []; + $values['id_name'] = get_parameter('id_name'); + $values['id_group'] = get_parameter('id_group'); + $values['event_type'] = get_parameter('event_type'); + $values['severity'] = get_parameter('severity'); + $values['status'] = get_parameter('status'); + $values['search'] = get_parameter('search'); + $values['text_agent'] = get_parameter('text_agent'); + $values['id_agent'] = get_parameter('id_agent'); + $values['id_agent_module'] = get_parameter('id_agent_module'); + $values['pagination'] = get_parameter('pagination'); + $values['event_view_hr'] = get_parameter('event_view_hr'); + $values['id_user_ack'] = get_parameter('id_user_ack'); + $values['group_rep'] = get_parameter('group_rep'); + $values['tag_with'] = get_parameter('tag_with', io_json_mb_encode([])); + $values['tag_without'] = get_parameter( + 'tag_without', + io_json_mb_encode([]) + ); + $values['filter_only_alert'] = get_parameter('filter_only_alert'); + $values['id_group_filter'] = get_parameter('id_group_filter'); + $values['date_from'] = get_parameter('date_from'); + $values['date_to'] = get_parameter('date_to'); + $values['source'] = get_parameter('source'); + $values['id_extra'] = get_parameter('id_extra'); + $values['user_comment'] = get_parameter('user_comment'); + + $exists = (bool) db_get_value_filter( + 'id_filter', + 'tevent_filter', + $values + ); + + if ($exists) { + echo 'duplicate'; + } else { + $result = db_process_sql_insert('tevent_filter', $values); + + if ($result === false) { + echo 'error'; + } else { + echo $result; + } + } +} + +if ($update_event_filter) { + $values = []; + $id = get_parameter('id'); + $values['id_group'] = get_parameter('id_group'); + $values['event_type'] = get_parameter('event_type'); + $values['severity'] = get_parameter('severity'); + $values['status'] = get_parameter('status'); + $values['search'] = get_parameter('search'); + $values['text_agent'] = get_parameter('text_agent'); + $values['id_agent'] = get_parameter('id_agent'); + $values['id_agent_module'] = get_parameter('id_agent_module'); + $values['pagination'] = get_parameter('pagination'); + $values['event_view_hr'] = get_parameter('event_view_hr'); + $values['id_user_ack'] = get_parameter('id_user_ack'); + $values['group_rep'] = get_parameter('group_rep'); + $values['tag_with'] = get_parameter('tag_with', io_json_mb_encode([])); + $values['tag_without'] = get_parameter( + 'tag_without', + io_json_mb_encode([]) + ); + $values['filter_only_alert'] = get_parameter('filter_only_alert'); + $values['id_group_filter'] = get_parameter('id_group_filter'); + $values['date_from'] = get_parameter('date_from'); + $values['date_to'] = get_parameter('date_to'); + $values['source'] = get_parameter('source'); + $values['id_extra'] = get_parameter('id_extra'); + $values['user_comment'] = get_parameter('user_comment'); + + if (io_safe_output($values['tag_with']) == '["0"]') { + $values['tag_with'] = '[]'; + } + + if (io_safe_output($values['tag_without']) == '["0"]') { + $values['tag_without'] = '[]'; + } + + $result = db_process_sql_update( + 'tevent_filter', + $values, + ['id_filter' => $id] + ); + + if ($result === false) { + echo 'error'; + } else { + echo 'ok'; + } +} + +// Get db values of a single filter. +if ($get_filter_values) { + $id_filter = get_parameter('id'); + + $event_filter = events_get_event_filter($id_filter); + + if ($event_filter === false) { + $event_filter = [ + 'status' => EVENT_NO_VALIDATED, + 'event_view_hr' => $config['event_view_hr'], + 'group_rep' => 1, + 'tag_with' => [], + 'tag_without' => [], + 'history' => false, + ]; + } + + $event_filter['search'] = io_safe_output($event_filter['search']); + $event_filter['id_name'] = io_safe_output($event_filter['id_name']); + $event_filter['tag_with'] = base64_encode( + io_safe_output($event_filter['tag_with']) + ); + $event_filter['tag_without'] = base64_encode( + io_safe_output($event_filter['tag_without']) + ); + + echo io_json_mb_encode($event_filter); +} + +if ($load_filter_modal) { + $current = get_parameter('current_filter', ''); + $filters = events_get_event_filter_select(); + $user_groups_array = users_get_groups_for_select( + $config['id_user'], + $access, + true, + true, + false + ); + + echo '
'; + $table = new StdClass; + $table->id = 'load_filter_form'; + $table->width = '100%'; + $table->cellspacing = 4; + $table->cellpadding = 4; + $table->class = 'databox'; + if (is_metaconsole()) { + $table->cellspacing = 0; + $table->cellpadding = 0; + $table->class = 'databox filters'; + } + + $table->styleTable = 'font-weight: bold; color: #555; text-align:left;'; + if (!is_metaconsole()) { + $table->style[0] = 'width: 50%; width:50%;'; + } + + $data = []; + $table->rowid[3] = 'update_filter_row1'; + $data[0] = __('Load filter').$jump; + $data[0] .= html_print_select( + $filters, + 'filter_id', + $current, + '', + __('None'), + 0, + true + ); + $data[1] = html_print_submit_button( + __('Load filter'), + 'load_filter', + false, + 'class="sub upd" onclick="load_form_filter();"', + true + ); + $table->data[] = $data; + $table->rowclass[] = ''; + + html_print_table($table); + echo '
'; + ?> + + '; + if (check_acl($config['id_user'], 0, 'EW') + || check_acl($config['id_user'], 0, 'EM') + ) { + echo '
'; + $table = new StdClass; + $table->id = 'save_filter_form'; + $table->width = '100%'; + $table->cellspacing = 4; + $table->cellpadding = 4; + $table->class = 'databox'; + if (is_metaconsole()) { + $table->class = 'databox filters'; + $table->cellspacing = 0; + $table->cellpadding = 0; + } + + $table->styleTable = 'font-weight: bold; text-align:left;'; + if (!is_metaconsole()) { + $table->style[0] = 'width: 50%; width:50%;'; + } + + $data = []; + $table->rowid[0] = 'update_save_selector'; + $data[0] = html_print_radio_button( + 'filter_mode', + 'new', + '', + true, + true + ).__('New filter').''; + + $data[1] = html_print_radio_button( + 'filter_mode', + 'update', + '', + false, + true + ).__('Update filter').''; + + $table->data[] = $data; + $table->rowclass[] = ''; + + $data = []; + $table->rowid[1] = 'save_filter_row1'; + $data[0] = __('Filter name').$jump; + $data[0] .= html_print_input_text('id_name', '', '', 15, 255, true); + if (is_metaconsole()) { + $data[1] = __('Save in Group').$jump; + } else { + $data[1] = __('Filter group').$jump; + } + + $user_groups_array = users_get_groups_for_select( + $config['id_user'], + 'EW', + users_can_manage_group_all(), + true + ); + + $data[1] .= html_print_select( + $user_groups_array, + 'id_group_filter', + $id_group_filter, + '', + '', + 0, + true, + false, + false, + 'w130' + ); + + $table->data[] = $data; + $table->rowclass[] = ''; + + $data = []; + $table->rowid[2] = 'save_filter_row2'; + + $table->data[] = $data; + $table->rowclass[] = ''; + + $data = []; + $table->rowid[3] = 'update_filter_row1'; + $data[0] = __('Overwrite filter').$jump; + // Fix : Only admin user can see filters of group ALL for update. + $_filters_update = events_get_event_filter_select(false); + + $data[0] .= html_print_select( + $_filters_update, + 'overwrite_filter', + '', + '', + '', + 0, + true + ); + $data[1] = html_print_submit_button( + __('Update filter'), + 'update_filter', + false, + 'class="sub upd" onclick="save_update_filter();"', + true + ); + + $table->data[] = $data; + $table->rowclass[] = ''; + + html_print_table($table); + echo '
'; + echo html_print_submit_button( + __('Save filter'), + 'save_filter', + false, + 'class="sub upd" style="float:right;" onclick="save_new_filter();"', + true + ); + echo '
'; + } else { + include 'general/noaccess.php'; + } + + echo ''; + ?> + + "; + $tabs = "'; @@ -498,7 +1274,7 @@ if ($get_extended_event) { $childrens_ids ))) ) { - $responses = events_page_responses($event, $childrens_ids); + $responses = events_page_responses($event); } else { $responses = ''; } @@ -514,12 +1290,14 @@ if ($get_extended_event) { $details = events_page_details($event, $server); + if ($meta) { + metaconsole_restore_db(); + } + if (events_has_extended_info($event['id_evento']) === true) { $related = events_page_related($event, $server); } - // Juanma (09/05/2014) Fix: Needs to reconnect to node, in previous funct - // node connection was lost. if ($meta) { $server = metaconsole_get_connection_by_id($server_id); metaconsole_connect($server); @@ -535,7 +1313,7 @@ if ($get_extended_event) { $general = events_page_general($event); - $comments = events_page_comments($event, $childrens_ids); + $comments = '
'; $notifications = ''; $notifications .= ''; @@ -546,6 +1324,18 @@ if ($get_extended_event) { $loading = ''; + $i = 0; + $tab['general'] = $i++; + $tab['details'] = $i++; + if (!empty($related)) { + $tab['related'] = $i++; + } + + $tab['custom_fields'] = $i++; + $tab['comments'] = $i++; + $tab['responses'] = $i++; + $tab['custom_data'] = $i++; + $out = '
'.$tabs.$notifications.$loading.$general.$details.$related.$custom_fields.$comments.$responses.$custom_data.html_print_input_hidden('id_event', $event['id_evento']).'
'; $js = ' diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 1b5a114287..07cd4f492e 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -32,6 +32,7 @@ require_once $config['homedir'].'/include/functions_db.php'; require_once $config['homedir'].'/include/functions_io.php'; require_once $config['homedir'].'/include/functions_notifications.php'; require_once $config['homedir'].'/include/functions_servers.php'; +require_once $config['homedir'].'/include/functions_update_manager.php'; // Enterprise includes. enterprise_include_once('include/functions_metaconsole.php'); @@ -1262,6 +1263,7 @@ class ConsoleSupervisor $PHPdisable_functions = ini_get('disable_functions'); $PHPupload_max_filesize_min = config_return_in_bytes('800M'); $PHPmemory_limit_min = config_return_in_bytes('500M'); + $PHPSerialize_precision = ini_get('serialize_precision'); // PhantomJS status. $result_ejecution = exec($config['phantomjs_bin'].'/phantomjs --version'); @@ -1437,6 +1439,30 @@ class ConsoleSupervisor } else { $this->cleanNotifications('NOTIF.PHP.VERSION'); } + + if ($PHPSerialize_precision != -1) { + $url = 'https://www.php.net/manual/en/ini.core.php#ini.serialize-precision'; + if ($config['language'] == 'es') { + $url = 'https://www.php.net/manual/es/ini.core.php#ini.serialize-precision'; + } + + $this->notify( + [ + 'type' => 'NOTIF.PHP.SERIALIZE_PRECISION', + 'title' => sprintf( + __("Not recommended '%s' value in PHP configuration"), + 'serialze_precision' + ), 'message' => sprintf( + __('Recommended value is: %s'), + sprintf('-1') + ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator'), + 'url' => $url, + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.SERIALIZE_PRECISION'); + } + } @@ -1940,6 +1966,7 @@ class ConsoleSupervisor public function checkUpdateManagerRegistration() { global $config; + include_once $config['homedir'].'/include/functions_update_manager.php'; $login = get_parameter('login', false); if (update_manager_verify_registration() === false) { @@ -1974,7 +2001,7 @@ class ConsoleSupervisor 'id_user', $config['id_user'] ); - if (license_free() === true + if (!$config['disabled_newsletter'] && $newsletter != 1 && $login === false ) { @@ -2244,6 +2271,7 @@ class ConsoleSupervisor public function getUMMessages() { global $config; + include_once $config['homedir'].'/include/functions_update_manager.php'; if (update_manager_verify_registration() === false) { // Console not subscribed. @@ -2261,8 +2289,6 @@ class ConsoleSupervisor $future = (time() + 2 * SECONDS_1HOUR); config_update_value('last_um_check', $future); - include_once $config['homedir'].'/include/functions_update_manager.php'; - $params = [ 'pandora_uid' => $config['pandora_uid'], 'timezone' => $config['timezone'], diff --git a/pandora_console/include/class/NetworkMap.class.php b/pandora_console/include/class/NetworkMap.class.php index 7bf232e068..0011167308 100644 --- a/pandora_console/include/class/NetworkMap.class.php +++ b/pandora_console/include/class/NetworkMap.class.php @@ -2845,6 +2845,7 @@ class NetworkMap html_print_table($table, true), __('Node Details'), __('Node Details'), + '', false, true ); @@ -2897,6 +2898,7 @@ class NetworkMap html_print_table($table, true), __('Node Details'), __('Node Details'), + '', false, true ); @@ -2922,6 +2924,7 @@ class NetworkMap html_print_table($table, true), __('Interface Information (SNMP)'), __('Interface Information (SNMP)'), + '', true, true ); @@ -2996,6 +2999,7 @@ class NetworkMap html_print_table($table, true), __('Node options'), __('Node options'), + '', true, true ); @@ -3056,6 +3060,7 @@ class NetworkMap html_print_table($table, true), __('Relations'), __('Relations'), + '', true, true ); @@ -3165,6 +3170,7 @@ class NetworkMap $add_agent_node_html, __('Add agent node'), __('Add agent node'), + '', false, true ); @@ -3216,6 +3222,7 @@ class NetworkMap $add_agent_node_html, __('Add agent node (filter by group)'), __('Add agent node'), + '', true, true ); @@ -3256,6 +3263,7 @@ class NetworkMap $add_agent_node_html, __('Add fictional point'), __('Add agent node'), + '', true, true ); diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php index eaf3c55fea..251fde0d73 100644 --- a/pandora_console/include/class/TreeService.class.php +++ b/pandora_console/include/class/TreeService.class.php @@ -72,6 +72,8 @@ class TreeService extends Tree protected function getFirstLevel() { + global $config; + $processed_items = $this->getProcessedServices(); $ids = array_keys($processed_items); @@ -212,26 +214,37 @@ class TreeService extends Tree foreach ($data_modules as $key => $module) { switch ($module['estado']) { case '0': - $data_modules[$key]['statusImageHTML'] = 'NORMAL status.'; + $module_status = 'ok'; + $module_title = 'NORMAL'; break; case '1': - $data_modules[$key]['statusImageHTML'] = 'CRITICAL status.'; + $module_status = 'critical'; + $module_title = 'CRITICAL'; break; case '2': - $data_modules[$key]['statusImageHTML'] = 'WARNING status.'; + $module_status = 'warning'; + $module_title = 'WARNING'; + break; + + case '3': + $module_status = 'down'; + $module_title = 'UNKNOWN'; break; case '4': - $data_modules[$key]['statusImageHTML'] = 'UNKNOWN status.'; + $module_status = 'no_data'; + $module_title = 'NOT INITIALIZED'; break; default: - // code... + $module_status = 'down'; + $module_title = 'UNKNOWN'; break; } + $data_modules[$key]['statusImageHTML'] = ''.$module_title.' status.'; $data_modules[$key]['showEventsBtn'] = 1; $data_modules[$key]['eventModule'] = $module['id_agente_modulo']; } diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 3bbde1736a..9deb7fa7b7 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,8 +20,8 @@ /** * Pandora build version and version */ -$build_version = 'PC190605'; -$pandora_version = 'v7.0NG.735'; +$build_version = 'PC190906'; +$pandora_version = 'v7.0NG.738'; // Do not overwrite default timezone set if defined. $script_tz = @date_default_timezone_get(); diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index 7266e9eff4..c512c33c8f 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -39,10 +39,11 @@ define('TIME_FORMAT', 'H:i:s'); define('TIME_FORMAT_JS', 'HH:mm:ss'); // Events state constants. +define('EVENT_ALL', -1); define('EVENT_NEW', 0); define('EVENT_VALIDATE', 1); define('EVENT_PROCESS', 2); - +define('EVENT_NO_VALIDATED', 3); // Agents disabled status. @@ -65,7 +66,7 @@ define('ERR_NODATA', -70000); define('ERR_CONNECTION', -80000); define('ERR_DISABLED', -90000); define('ERR_WRONG', -100000); -define('ERR_WRONG_NAME', -100001); +define('ERR_WRONG_MR', -100001); define('ERR_WRONG_PARAMETERS', -100002); define('ERR_ACL', -110000); define('ERR_AUTH', -120000); @@ -137,19 +138,19 @@ switch ($config['dbtype']) { // Color constants. -define('COL_CRITICAL', '#FC4444'); -define('COL_WARNING', '#FAD403'); +define('COL_CRITICAL', '#e63c52'); +define('COL_WARNING', '#f3b200'); define('COL_WARNING_DARK', '#FFB900'); -define('COL_NORMAL', '#80BA27'); -define('COL_NOTINIT', '#3BA0FF'); +define('COL_NORMAL', '#82b92e'); +define('COL_NOTINIT', '#4a83f3'); define('COL_UNKNOWN', '#B2B2B2'); define('COL_DOWNTIME', '#976DB1'); define('COL_IGNORED', '#DDD'); -define('COL_ALERTFIRED', '#FFA631'); -define('COL_MINOR', '#F099A2'); +define('COL_ALERTFIRED', '#F36201'); +define('COL_MINOR', '#B2B2B2'); define('COL_MAJOR', '#C97A4A'); define('COL_INFORMATIONAL', '#E4E4E4'); -define('COL_MAINTENANCE', '#3BA0FF'); +define('COL_MAINTENANCE', '#4a83f3'); define('COL_GRAPH1', '#C397F2'); define('COL_GRAPH2', '#FFE66C'); @@ -354,6 +355,12 @@ define('MODULE_PREDICTION_CLUSTER', 5); define('MODULE_PREDICTION_CLUSTER_AA', 6); define('MODULE_PREDICTION_CLUSTER_AP', 7); +// Type of Webserver Modules. +define('MODULE_WEBSERVER_CHECK_LATENCY', 30); +define('MODULE_WEBSERVER_CHECK_SERVER_RESPONSE', 31); +define('MODULE_WEBSERVER_RETRIEVE_NUMERIC_DATA', 32); +define('MODULE_WEBSERVER_RETRIEVE_STRING_DATA', 33); + // SNMP CONSTANTS. define('SNMP_DIR_MIBS', 'attachment/mibs'); @@ -526,14 +533,6 @@ define('NODE_MODULE', 1); define('NODE_PANDORA', 2); define('NODE_GENERIC', 3); -// SAML attributes constants. -define('SAML_ROLE_AND_TAG', 'eduPersonEntitlement'); -define('SAML_USER_DESC', 'commonName'); -define('SAML_ID_USER_IN_PANDORA', 'eduPersonTargetedId'); -define('SAML_GROUP_IN_PANDORA', 'schacHomeOrganization'); -define('SAML_MAIL_IN_PANDORA', 'mail'); -define('SAML_DEFAULT_PROFILES_AND_TAGS_FORM', 'urn:mace:rediris.es:entitlement:monitoring:'); - // Other constants. define('STATUS_OK', 0); define('STATUS_ERROR', 1); @@ -589,6 +588,8 @@ define('DISCOVERY_APP_MYSQL', 4); define('DISCOVERY_APP_ORACLE', 5); define('DISCOVERY_CLOUD_AWS_EC2', 6); define('DISCOVERY_CLOUD_AWS_RDS', 7); +define('DISCOVERY_CLOUD_AZURE_COMPUTE', 8); +define('DISCOVERY_DEPLOY_AGENTS', 9); // Discovery types matching definition. @@ -601,6 +602,7 @@ define('DISCOVERY_SCRIPT_IPAM_RECON', 3); define('DISCOVERY_SCRIPT_IPMI_RECON', 4); // Discovery task descriptions. +define('CLOUDWIZARD_AZURE_DESCRIPTION', 'Discovery.Cloud.Azure.Compute'); define('CLOUDWIZARD_AWS_DESCRIPTION', 'Discovery.Cloud.AWS.EC2'); define('CLOUDWIZARD_VMWARE_DESCRIPTION', 'Discovery.App.VMware'); diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index f299153da6..b1027bc4af 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -902,6 +902,47 @@ function set_cookie($name, $value) } +/** + * Returns database ORDER clause from datatables AJAX call. + * + * @param boolean $as_array Return as array or as string. + * + * @return string Order or empty. + */ +function get_datatable_order($as_array=false) +{ + $order = get_parameter('order'); + + if (is_array($order)) { + $column = $order[0]['column']; + $direction = $order[0]['dir']; + } + + if (!isset($column) || !isset($direction)) { + return ''; + } + + $columns = get_parameter('columns'); + + if (is_array($columns)) { + $column_name = $columns[$column]['data']; + } + + if (!isset($column_name)) { + return ''; + } + + if ($as_array) { + return [ + 'direction' => $direction, + 'field' => $column_name, + ]; + } + + return $column_name.' '.$direction; +} + + /** * Get a parameter from a request. * @@ -1392,6 +1433,11 @@ function enterprise_installed() { $return = false; + // Load enterprise extensions. + if (defined('DESTDIR')) { + return $return; + } + if (defined('PANDORA_ENTERPRISE')) { if (PANDORA_ENTERPRISE) { $return = true; @@ -1444,7 +1490,7 @@ function enterprise_include($filename) { global $config; - // Load enterprise extensions + // Load enterprise extensions. if (defined('DESTDIR')) { $destdir = DESTDIR; } else { @@ -1470,11 +1516,24 @@ function enterprise_include($filename) } +/** + * Includes a file from enterprise section. + * + * @param string $filename Target file. + * + * @return mixed Result code. + */ function enterprise_include_once($filename) { global $config; - // Load enterprise extensions + // Load enterprise extensions. + if (defined('DESTDIR')) { + $destdir = DESTDIR; + } else { + $destdir = ''; + } + $filepath = realpath($config['homedir'].'/'.ENTERPRISE_DIR.'/'.$filename); if ($filepath === false) { @@ -1574,6 +1633,11 @@ function safe_sql_string($string) } +/** + * Verifies if current Pandora FMS installation is a Metaconsole. + * + * @return boolean True metaconsole installation, false if not. + */ function is_metaconsole() { global $config; @@ -1581,6 +1645,18 @@ function is_metaconsole() } +/** + * Check if current Pandora FMS installation has joined a Metaconsole env. + * + * @return boolean True joined, false if not. + */ +function has_metaconsole() +{ + global $config; + return (bool) $config['node_metaconsole'] && (bool) $config['metaconsole_node_id']; +} + + /** * @brief Check if there is management operations are allowed in current context * (node // meta) @@ -1760,6 +1836,52 @@ function array_key_to_offset($array, $key) } +/** + * Undocumented function + * + * @param array $arguments Following format: + * [ + * 'ip_target' + * 'snmp_version' + * 'snmp_community' + * 'snmp3_auth_user' + * 'snmp3_security_level' + * 'snmp3_auth_method' + * 'snmp3_auth_pass' + * 'snmp3_privacy_method' + * 'snmp3_privacy_pass' + * 'quick_print' + * 'base_oid' + * 'snmp_port' + * 'server_to_exec' + * 'extra_arguments' + * 'format' + * ] + * + * @return array SNMP result. + */ +function get_h_snmpwalk(array $arguments) +{ + return get_snmpwalk( + $arguments['ip_target'], + $arguments['snmp_version'], + isset($arguments['snmp_community']) ? $arguments['snmp_community'] : '', + isset($arguments['snmp3_auth_user']) ? $arguments['snmp3_auth_user'] : '', + isset($arguments['snmp3_security_level']) ? $arguments['snmp3_security_level'] : '', + isset($arguments['snmp3_auth_method']) ? $arguments['snmp3_auth_method'] : '', + isset($arguments['snmp3_auth_pass']) ? $arguments['snmp3_auth_pass'] : '', + isset($arguments['snmp3_privacy_method']) ? $arguments['snmp3_privacy_method'] : '', + isset($arguments['snmp3_privacy_pass']) ? $arguments['snmp3_privacy_pass'] : '', + isset($arguments['quick_print']) ? $arguments['quick_print'] : 0, + isset($arguments['base_oid']) ? $arguments['base_oid'] : '', + isset($arguments['snmp_port']) ? $arguments['snmp_port'] : '', + isset($arguments['server_to_exec']) ? $arguments['server_to_exec'] : 0, + isset($arguments['extra_arguments']) ? $arguments['extra_arguments'] : '', + isset($arguments['format']) ? $arguments['format'] : '-Oa' + ); +} + + /** * Make a snmpwalk and return it. * @@ -1880,11 +2002,16 @@ function get_snmpwalk( exec($command_str, $output, $rc); } - // Parse the output of snmpwalk + // Parse the output of snmpwalk. $snmpwalk = []; foreach ($output as $line) { - // Separate the OID from the value - $full_oid = explode(' = ', $line); + // Separate the OID from the value. + if (strpos($format, 'q') === false) { + $full_oid = explode(' = ', $line, 2); + } else { + $full_oid = explode(' ', $line, 2); + } + if (isset($full_oid[1])) { $snmpwalk[$full_oid[0]] = $full_oid[1]; } @@ -2557,7 +2684,7 @@ function can_user_access_node() $userinfo = get_user_info($config['id_user']); - if (defined('METACONSOLE')) { + if (is_metaconsole()) { return $userinfo['is_admin'] == 1 ? 1 : $userinfo['metaconsole_access_node']; } else { return 1; @@ -2725,6 +2852,8 @@ function print_audit_csv($data) global $config; global $graphic_type; + $divider = html_entity_decode($config['csv_divider']); + if (!$data) { echo __('No data found to export'); return 0; @@ -2742,9 +2871,9 @@ function print_audit_csv($data) // BOM print pack('C*', 0xEF, 0xBB, 0xBF); - echo __('User').';'.__('Action').';'.__('Date').';'.__('Source IP').';'.__('Comments')."\n"; + echo __('User').$divider.__('Action').$divider.__('Date').$divider.__('Source IP').$divider.__('Comments')."\n"; foreach ($data as $line) { - echo io_safe_output($line['id_usuario']).';'.io_safe_output($line['accion']).';'.date($config['date_format'], $line['utimestamp']).';'.$line['ip_origen'].';'.io_safe_output($line['descripcion'])."\n"; + echo io_safe_output($line['id_usuario']).$divider.io_safe_output($line['accion']).$divider.io_safe_output(date($config['date_format'], $line['utimestamp'])).$divider.$line['ip_origen'].$divider.io_safe_output($line['descripcion'])."\n"; } exit; @@ -5286,3 +5415,27 @@ function get_help_info($section_name) // hd($result); return $result; } + + +if (!function_exists('getallheaders')) { + + + /** + * Fix for php-fpm + * + * @return array + */ + function getallheaders() + { + $headers = []; + foreach ($_SERVER as $name => $value) { + if (substr($name, 0, 5) == 'HTTP_') { + $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; + } + } + + return $headers; + } + + +} diff --git a/pandora_console/include/functions_agents.php b/pandora_console/include/functions_agents.php index fd5e922e32..fdcce4457a 100644 --- a/pandora_console/include/functions_agents.php +++ b/pandora_console/include/functions_agents.php @@ -1513,29 +1513,30 @@ function agents_get_name($id_agent, $case='none') * Get alias of an agent (cached function). * * @param integer $id_agent Agent id. - * @param string $case Case (upper, lower, none) + * @param string $case Case (upper, lower, none). * * @return string Alias of the given agent. */ function agents_get_alias($id_agent, $case='none') { global $config; - // Prepare cache + // Prepare cache. static $cache = []; if (empty($case)) { $case = 'none'; } - // Check cache + // Check cache. if (isset($cache[$case][$id_agent])) { return $cache[$case][$id_agent]; } - if ($config['dbconnection_cache'] == null && is_metaconsole()) { - $alias = (string) db_get_value('alias', 'tmetaconsole_agent', 'id_tagente', (int) $id_agent); - } else { - $alias = (string) db_get_value('alias', 'tagente', 'id_agente', (int) $id_agent); - } + $alias = (string) db_get_value( + 'alias', + 'tagente', + 'id_agente', + (int) $id_agent + ); switch ($case) { case 'upper': @@ -1545,6 +1546,10 @@ function agents_get_alias($id_agent, $case='none') case 'lower': $alias = mb_strtolower($alias, 'UTF-8'); break; + + default: + // Not posible. + break; } $cache[$case][$id_agent] = $alias; @@ -1554,7 +1559,13 @@ function agents_get_alias($id_agent, $case='none') function agents_get_alias_by_name($name, $case='none') { - $alias = (string) db_get_value('alias', 'tagente', 'nombre', $name); + if (is_metaconsole()) { + $table = 'tmetaconsole_agent'; + } else { + $table = 'tagente'; + } + + $alias = (string) db_get_value('alias', $table, 'nombre', $name); switch ($case) { case 'upper': @@ -1614,9 +1625,9 @@ function agents_get_interval($id_agent) * * @param Agent object. * - * @return The interval value and status of last contact + * @return The interval value and status of last contact or True /False */ -function agents_get_interval_status($agent) +function agents_get_interval_status($agent, $return_html=true) { $return = ''; $last_time = time_w_fixed_tz($agent['ultimo_contacto']); @@ -1624,9 +1635,18 @@ function agents_get_interval_status($agent) $diferencia = ($now - $last_time); $time = ui_print_timestamp($last_time, true, ['style' => 'font-size:6.5pt']); $min_interval = modules_get_agentmodule_mininterval_no_async($agent['id_agente']); - $return = $time; + if ($return_html) { + $return = $time; + } else { + $return = true; + } + if ($diferencia > ($min_interval['min_interval'] * 2) && $min_interval['num_interval'] > 0) { - $return = ''.$time.''; + if ($return_html) { + $return = ''.$time.''; + } else { + $return = false; + } } return $return; @@ -3367,3 +3387,46 @@ function agents_get_image_status($status) return $image_status; } + + +/** + * Animation GIF to show agent's status. + * + * @return string HTML code with heartbeat image. + */ +function agents_get_status_animation($up=true) +{ + global $config; + + // Gif with black background or white background + if ($config['style'] === 'pandora_black') { + $heartbeat_green = 'images/heartbeat_green_black.gif'; + $heartbeat_red = 'images/heartbeat_red_black.gif'; + } else { + $heartbeat_green = 'images/heartbeat_green.gif'; + $heartbeat_red = 'images/heartbeat_red.gif'; + } + + switch ($up) { + case true: + default: + return html_print_image( + $heartbeat_green, + true, + [ + 'width' => '170', + 'height' => '40', + ] + ); + + case false: + return html_print_image( + $heartbeat_red, + true, + [ + 'width' => '170', + 'height' => '40', + ] + ); + } +} diff --git a/pandora_console/include/functions_alerts.php b/pandora_console/include/functions_alerts.php index 011acafae9..cc449b3445 100644 --- a/pandora_console/include/functions_alerts.php +++ b/pandora_console/include/functions_alerts.php @@ -1783,12 +1783,14 @@ function alerts_validate_alert_agent_module($id_alert_agent_module, $noACLs=fals ['id' => $id] ); + $template_name = io_safe_output(db_get_value('name', 'talert_templates', 'id', $alert['id_alert_template'])); + $module_name = io_safe_output(db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $alert['id_agent_module'])); if ($result > 0) { // Update fired alert count on the agent db_process_sql(sprintf('UPDATE tagente SET update_alert_count=1 WHERE id_agente = %d', $agent_id)); events_create_event( - 'Manual validation of alert for '.alerts_get_alert_template_description($alert['id_alert_template']), + 'Manual validation of alert '.$template_name.' assigned to '.$module_name.'', $group_id, $agent_id, 1, @@ -1914,7 +1916,6 @@ function alerts_get_agents_with_alert_template($id_alert_template, $id_group, $f $filter[] = 'tagente_modulo.id_agente_modulo = talert_template_modules.id_agent_module'; $filter[] = 'tagente_modulo.id_agente = tagente.id_agente'; $filter['id_alert_template'] = $id_alert_template; - $filter['tagente_modulo.disabled'] = '<> 1'; $filter['delete_pending'] = '<> 1'; if (empty($id_agents)) { @@ -2491,7 +2492,7 @@ function alerts_get_action_escalation($action) $escalation[$action['fires_max']] = 1; } else if ($action['fires_min'] < $action['fires_max']) { for ($i = 1; $i <= $action['fires_max']; $i++) { - if ($i <= $action['fires_min']) { + if ($i < $action['fires_min']) { $escalation[$i] = 0; } else { $escalation[$i] = 1; diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php index 3c6cdbf595..899add9ec0 100644 --- a/pandora_console/include/functions_api.php +++ b/pandora_console/include/functions_api.php @@ -7494,63 +7494,62 @@ function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3) /** - * Remove an agent from a policy. + * Remove an agent from a policy by agent id. * * @param $id Id of the policy - * @param $id2 Id of the agent policy - * @param $trash1 - * @param $trash2 + * @param $thrash1 Don't use. + * @param $other + * @param $thrash2 Don't use. * * Example: * api.php?op=set&op2=remove_agent_from_policy&apipass=1234&user=admin&pass=pandora&id=11&id2=2 */ -function api_set_remove_agent_from_policy($id, $id2, $thrash2, $thrash3) +function api_set_remove_agent_from_policy_by_id($id, $thrash1, $other, $thrash2) { - global $config; - - if (!check_acl($config['id_user'], 0, 'AW')) { - returnError('forbidden', 'string'); - return; - } - if ($id == '' || !$id) { returnError('error_parameter', __('Error deleting agent from policy. Policy cannot be left blank.')); return; } - if ($id2 == '' || !$id2) { + if ($other['data'][0] == '' || !$other['data'][0]) { returnError('error_parameter', __('Error deleting agent from policy. Agent cannot be left blank.')); return; } - $policy = policies_get_policy($id, false, false); - $agent = db_get_row_filter('tagente', ['id_agente' => $id2]); - $policy_agent = db_get_row_filter('tpolicy_agents', ['id_policy' => $id, 'id_agent' => $id2]); - - if (empty($policy)) { - returnError('error_policy', __('This policy does not exist.')); + // Require node id if is metaconsole + if (is_metaconsole() && $other['data'][1] == '') { + returnError('error_add_agent_policy', __('Error deleting agent from policy. Node ID cannot be left blank.')); return; } - if (empty($agent)) { - returnError('error_agent', __('This agent does not exist.')); + return remove_agent_from_policy($id, false, [$other['data'][0], $other['data'][1]]); +} + + +/** + * Remove an agent from a policy by agent name. + * + * @param $id Id of the policy + * @param $thrash1 Don't use. + * @param $other + * @param $thrash2 Don't use. + * + * Example: + * api.php?op=set&op2=remove_agent_from_policy&apipass=1234&user=admin&pass=pandora&id=11&id2=2 + */ +function api_set_remove_agent_from_policy_by_name($id, $thrash1, $other, $thrash2) +{ + if ($id == '' || !$id) { + returnError('error_parameter', __('Error deleting agent from policy. Policy cannot be left blank.')); return; } - if (empty($policy_agent)) { - returnError('error_policy_agent', __('This agent does not exist in this policy.')); + if ($other['data'][0] == '' || !$other['data'][0]) { + returnError('error_add_agent_policy', __('Error adding agent to policy. Agent name cannot be left blank.')); return; } - $return = policies_change_delete_pending_agent($policy_agent['id']); - $data = __('Successfully added to delete pending id agent %d to id policy %d.', $id2, $id); - - if ($return === false) { - returnError('error_delete_policy_agent', 'Could not be deleted id agent %d from id policy %d', $id2, $id); - } else { - returnData('string', ['type' => 'string', 'data' => $data]); - } - + return remove_agent_from_policy($id, true, [$other['data'][0]]); } @@ -11519,7 +11518,7 @@ function api_set_create_event($id, $trash1, $other, $returnType) if ($other['data'][18] != '') { $values['id_extra'] = $other['data'][18]; - $sql_validation = 'SELECT id_evento FROM tevento where estado=0 and id_extra ="'.$other['data'][18].'";'; + $sql_validation = 'SELECT id_evento FROM tevento where estado IN (0,2) and id_extra ="'.$other['data'][18].'";'; $validation = db_get_all_rows_sql($sql_validation); if ($validation) { foreach ($validation as $val) { @@ -14209,28 +14208,6 @@ function api_get_all_event_filters($thrash1, $thrash2, $other, $thrash3) } -// -// AUX FUNCTIONS -// -function util_api_check_agent_and_print_error($id_agent, $returnType, $access='AR', $force_meta=false) -{ - global $config; - - $check_agent = agents_check_access_agent($id_agent, $access, $force_meta); - if ($check_agent === true) { - return true; - } - - if ($check_agent === false || !check_acl($config['id_user'], 0, $access)) { - returnError('forbidden', $returnType); - } else if ($check_agent === null) { - returnError('id_not_found', $returnType); - } - - return false; -} - - function api_get_user_info($thrash1, $thrash2, $other, $returnType) { $separator = ';'; @@ -15047,3 +15024,95 @@ function api_set_add_permission_user_to_group($thrash1, $thrash2, $other, $retur returnData($returnType, $data, ';'); } + + +// AUXILIARY FUNCTIONS + + +/** + * Auxiliary function to remove an agent from a policy. Used from API methods api_set_remove_agent_from_policy_by_id and api_set_remove_agent_from_policy_by_name. + * + * @param int ID of targeted policy. + * @param boolean If true it will look for the agent we are targeting at based on its agent name, otherwise by agent id. + * @param array Array containing agent's name or agent's id (and node id in case we are on metaconsole). + */ +function remove_agent_from_policy($id_policy, $use_agent_name, $params) +{ + global $config; + + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } + + $id_node = 0; + $agent_table = 'tagente'; + + if ($use_agent_name === false) { + $id_agent = $params[0]; + } else { + $id_agent = db_get_value_filter('id_agente', 'tagente', ['nombre' => $params[0]]); + } + + $agent = db_get_row_filter('tagente', ['id_agente' => $id_agent]); + + if (is_metaconsole()) { + if ($use_agent_name === false) { + $id_node = $params[1]; + $id_agent = $params[0]; + } else { + $id_node = db_get_value_filter('id_tmetaconsole_setup', 'tmetaconsole_agent', ['nombre' => $params[0]]); + $id_agent = db_get_value_filter('id_tagente', 'tmetaconsole_agent', ['nombre' => $params[0]]); + } + + $agent = db_get_row_filter('tmetaconsole_agent', ['id_tagente' => $id_agent, 'id_tmetaconsole_setup' => $id_node]); + } + + $policy = policies_get_policy($id_policy, false, false); + + $policy_agent = (is_metaconsole()) ? db_get_row_filter('tpolicy_agents', ['id_policy' => $id_policy, 'id_agent' => $id_agent, 'id_node' => $id_node]) : db_get_row_filter('tpolicy_agents', ['id_policy' => $id_policy, 'id_agent' => $id_agent]); + + if (empty($policy)) { + returnError('error_policy', __('This policy does not exist.')); + return; + } + + if (empty($agent)) { + returnError('error_agent', __('This agent does not exist.')); + return; + } + + if (empty($policy_agent)) { + returnError('error_policy_agent', __('This agent does not exist in this policy.')); + return; + } + + $return = policies_change_delete_pending_agent($policy_agent['id']); + $data = __('Successfully added to delete pending id agent %d to id policy %d.', $id_agent, $id_policy); + + if ($return === false) { + returnError('error_delete_policy_agent', 'Could not be deleted id agent %d from id policy %d', $id_agent, $id_policy); + } else { + returnData('string', ['type' => 'string', 'data' => $data]); + } + +} + + +function util_api_check_agent_and_print_error($id_agent, $returnType, $access='AR', $force_meta=false) +{ + global $config; + + $check_agent = agents_check_access_agent($id_agent, $access, $force_meta); + if ($check_agent === true) { + return true; + } + + if ($check_agent === false || !check_acl($config['id_user'], 0, $access)) { + returnError('forbidden', $returnType); + } else if ($check_agent === null) { + returnError('id_not_found', $returnType); + } + + return false; +} diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 1b5af44a21..bc5e64190d 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -180,7 +180,7 @@ function config_update_config() $error_update[] = __('Automatic check for updates'); } - if (!config_update_value('cert_path', (bool) get_parameter('cert_path'))) { + if (!config_update_value('cert_path', get_parameter('cert_path'))) { $error_update[] = __('SSL cert path'); } @@ -266,6 +266,14 @@ function config_update_config() $error_update[] = __('Public URL'); } + if (!config_update_value('force_public_url', get_parameter_switch('force_public_url'))) { + $error_update[] = __('Force use Public URL'); + } + + if (!config_update_value('public_url_exclusions', get_parameter('public_url_exclusions'))) { + $error_update[] = __('Public URL host exclusions'); + } + if (!config_update_value('referer_security', get_parameter('referer_security'))) { $error_update[] = __('Referer security'); } @@ -423,6 +431,10 @@ function config_update_config() $error_update[] = __('Enable Update Manager'); } + if (!config_update_value('disabled_newsletter', get_parameter('disabled_newsletter'))) { + $error_update[] = __('Disabled newsletter'); + } + if (!config_update_value('ipam_ocuppied_critical_treshold', get_parameter('ipam_ocuppied_critical_treshold'))) { $error_update[] = __('Ipam Ocuppied Manager Critical'); } @@ -652,6 +664,42 @@ function config_update_config() $error_update[] = __('Saml path'); } + if (!config_update_value('saml_source', get_parameter('saml_source'))) { + $error_update[] = __('Saml source'); + } + + if (!config_update_value('saml_user_id', get_parameter('saml_user_id'))) { + $error_update[] = __('Saml user id parameter'); + } + + if (!config_update_value('saml_mail', get_parameter('saml_mail'))) { + $error_update[] = __('Saml mail parameter'); + } + + if (!config_update_value('saml_group_name', get_parameter('saml_group_name'))) { + $error_update[] = __('Saml group name parameter'); + } + + if (!config_update_value('saml_attr_type', (bool) get_parameter('saml_attr_type'))) { + $error_update[] = __('Saml attr type parameter'); + } + + if (!config_update_value('saml_profiles_and_tags', get_parameter('saml_profiles_and_tags'))) { + $error_update[] = __('Saml profiles and tags parameter'); + } + + if (!config_update_value('saml_profile', get_parameter('saml_profile'))) { + $error_update[] = __('Saml profile parameters'); + } + + if (!config_update_value('saml_tag', get_parameter('saml_tag'))) { + $error_update[] = __('Saml tag parameter'); + } + + if (!config_update_value('saml_profile_tag_separator', get_parameter('saml_profile_tag_separator'))) { + $error_update[] = __('Saml profile and tag separator'); + } + if (!config_update_value('double_auth_enabled', get_parameter('double_auth_enabled'))) { $error_update[] = __('Double authentication'); } @@ -1687,6 +1735,10 @@ function config_process_config() config_update_value('enable_update_manager', 1); } + if (!isset($config['disabled_newsletter'])) { + config_update_value('disabled_newsletter', 0); + } + if (!isset($config['ipam_ocuppied_critical_treshold'])) { config_update_value('ipam_ocuppied_critical_treshold', 90); } @@ -2167,9 +2219,9 @@ function config_process_config() if (!isset($config['ad_adv_perms'])) { config_update_value('ad_adv_perms', ''); } else { + $temp_ad_adv_perms = []; if (!json_decode(io_safe_output($config['ad_adv_perms']))) { - $temp_ad_adv_perms = []; - if (!isset($config['ad_adv_perms']) && $config['ad_adv_perms'] != '') { + if ($config['ad_adv_perms'] != '') { $perms = explode(';', io_safe_output($config['ad_adv_perms'])); foreach ($perms as $ad_adv_perm) { if (preg_match('/[\[\]]/', $ad_adv_perm)) { @@ -2232,22 +2284,26 @@ function config_process_config() if (!empty($new_ad_adv_perms)) { $temp_ad_adv_perms = json_encode($new_ad_adv_perms); } + } else { + $temp_ad_adv_perms = ''; } - - config_update_value('ad_adv_perms', $temp_ad_adv_perms); + } else { + $temp_ad_adv_perms = $config['ad_adv_perms']; } + + config_update_value('ad_adv_perms', $temp_ad_adv_perms); } if (!isset($config['ldap_adv_perms'])) { config_update_value('ldap_adv_perms', ''); } else { + $temp_ldap_adv_perms = []; if (!json_decode(io_safe_output($config['ldap_adv_perms']))) { - $temp_ldap_adv_perms = []; - if (!isset($config['ad_adv_perms']) && $config['ldap_adv_perms'] != '') { + if ($config['ldap_adv_perms'] != '') { $perms = explode(';', io_safe_output($config['ldap_adv_perms'])); - foreach ($perms as $ad_adv_perm) { - if (preg_match('/[\[\]]/', $ad_adv_perm)) { - $all_data = explode(',', io_safe_output($ad_adv_perm)); + foreach ($perms as $ldap_adv_perm) { + if (preg_match('/[\[\]]/', $ldap_adv_perm)) { + $all_data = explode(',', io_safe_output($ldap_adv_perm)); $profile = $all_data[0]; $group_pnd = $all_data[1]; $groups_ad = str_replace(['[', ']'], '', $all_data[2]); @@ -2277,7 +2333,7 @@ function config_process_config() 'groups_ldap' => $groups_ldap, ]; } else { - $all_data = explode(',', io_safe_output($ad_adv_perm)); + $all_data = explode(',', io_safe_output($ldap_adv_perm)); $profile = $all_data[0]; $group_pnd = $all_data[1]; $groups_ad = $all_data[2]; @@ -2306,10 +2362,14 @@ function config_process_config() if (!empty($new_ldap_adv_perms)) { $temp_ldap_adv_perms = json_encode($new_ldap_adv_perms); } + } else { + $temp_ldap_adv_perms = ''; } - - config_update_value('ldap_adv_perms', $temp_ldap_adv_perms); + } else { + $temp_ldap_adv_perms = $config['ldap_adv_perms']; } + + config_update_value('ldap_adv_perms', $temp_ldap_adv_perms); } if (!isset($config['rpandora_server'])) { @@ -2356,6 +2416,42 @@ function config_process_config() config_update_value('saml_path', '/opt/'); } + if (!isset($config['saml_source'])) { + config_update_value('saml_source', ''); + } + + if (!isset($config['saml_user_id'])) { + config_update_value('saml_user_id', ''); + } + + if (!isset($config['saml_mail'])) { + config_update_value('saml_mail', ''); + } + + if (!isset($config['saml_group_name'])) { + config_update_value('saml_group_name', ''); + } + + if (!isset($config['saml_attr_type'])) { + config_update_value('saml_attr_type', false); + } + + if (!isset($config['saml_profiles_and_tags'])) { + config_update_value('saml_profiles_and_tags', ''); + } + + if (!isset($config['saml_profile'])) { + config_update_value('saml_profile', ''); + } + + if (!isset($config['saml_tag'])) { + config_update_value('saml_tag', ''); + } + + if (!isset($config['saml_profile_tag_separator'])) { + config_update_value('saml_profile_tag_separator', ''); + } + if (!isset($config['autoupdate'])) { config_update_value('autoupdate', 1); } @@ -2871,7 +2967,17 @@ function config_prepare_session() // Reset the expiration time upon page load //session_name() is default name of session PHPSESSID. if (isset($_COOKIE[session_name()])) { - setcookie(session_name(), $_COOKIE[session_name()], (time() + $sessionCookieExpireTime), '/'); + $update_cookie = true; + if (is_ajax()) { + // Avoid session upadte while processing ajax responses - notifications. + if (get_parameter('check_new_notifications', false)) { + $update_cookie = false; + } + } + + if ($update_cookie === true) { + setcookie(session_name(), $_COOKIE[session_name()], (time() + $sessionCookieExpireTime), '/'); + } } ini_set('post_max_size', $config['max_file_size']); diff --git a/pandora_console/include/functions_credential_store.php b/pandora_console/include/functions_credential_store.php new file mode 100644 index 0000000000..1b64bba116 --- /dev/null +++ b/pandora_console/include/functions_credential_store.php @@ -0,0 +1,445 @@ + 0) { + $propagate = db_get_value( + 'propagate', + 'tgrupo', + 'id_grupo', + $filter['filter_id_group'] + ); + + if (!$propagate) { + $sql_filters[] = sprintf( + ' AND cs.id_group = %d ', + $filter['filter_id_group'] + ); + } else { + $groups = [ $filter['filter_id_group'] ]; + $childrens = groups_get_childrens($id_group, null, true); + if (!empty($childrens)) { + foreach ($childrens as $child) { + $groups[] = (int) $child['id_grupo']; + } + } + + $filter['filter_id_group'] = $groups; + $sql_filters[] = sprintf( + ' AND cs.id_group IN (%s) ', + join(',', $filter['filter_id_group']) + ); + } + } + + if (isset($filter['group_list']) && is_array($filter['group_list'])) { + $sql_filters[] = sprintf( + ' AND cs.id_group IN (%s) ', + join(',', $filter['group_list']) + ); + } + + if (isset($order)) { + $dir = 'asc'; + if ($order == 'desc') { + $dir = 'desc'; + }; + + if (in_array( + $sort_field, + [ + 'group', + 'identifier', + 'product', + 'username', + 'options', + ] + ) + ) { + $order_by = sprintf( + 'ORDER BY `%s` %s', + $sort_field, + $dir + ); + } + } + + if (isset($limit) && $limit > 0 + && isset($offset) && $offset >= 0 + ) { + $pagination = sprintf( + ' LIMIT %d OFFSET %d ', + $limit, + $offset + ); + } + + $sql = sprintf( + 'SELECT %s + FROM tcredential_store cs + LEFT JOIN tgrupo tg + ON tg.id_grupo = cs.id_group + WHERE 1=1 + %s + %s + %s', + join(',', $fields), + join(' ', $sql_filters), + $order_by, + $pagination + ); + + if ($count) { + $sql = sprintf('SELECT count(*) as n FROM ( %s ) tt', $sql); + + return db_get_value_sql($sql); + } + + return db_get_all_rows_sql($sql); +} + + +/** + * Retrieves target key from keystore or false in case of error. + * + * @param string $identifier Key identifier. + * + * @return array Key or false if error. + */ +function get_key($identifier) +{ + return db_get_row_filter( + 'tcredential_store', + [ 'identifier' => $identifier ] + ); +} + + +/** + * Minor function to dump json message as ajax response. + * + * @param string $type Type: result || error. + * @param string $msg Message. + * @param boolean $delete Deletion messages. + * + * @return void + */ +function ajax_msg($type, $msg, $delete=false) +{ + $msg_err = 'Failed while saving: %s'; + $msg_ok = 'Successfully saved into keystore '; + + if ($delete) { + $msg_err = 'Failed while removing: %s'; + $msg_ok = 'Successfully deleted '; + } + + if ($type == 'error') { + echo json_encode( + [ + $type => ui_print_error_message( + __( + $msg_err, + $msg + ), + '', + true + ), + ] + ); + } else { + echo json_encode( + [ + $type => ui_print_success_message( + __( + $msg_ok, + $msg + ), + '', + true + ), + ] + ); + } + + exit; +} + + +/** + * Generates inputs for new/update forms. + * + * @param array $values Values or null. + * + * @return string Inputs. + */ +function print_inputs($values=null) +{ + if (!is_array($values)) { + $values = []; + } + + $return = ''; + $return .= html_print_input( + [ + 'label' => __('Identifier'), + 'name' => 'identifier', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['identifier'], + 'disabled' => (bool) $values['identifier'], + 'return' => true, + 'script' => 'alert(\'puta\')', + ] + ); + $return .= html_print_input( + [ + 'label' => __('Group'), + 'name' => 'id_group', + 'id' => 'id_group', + 'input_class' => 'flex-row', + 'type' => 'select_groups', + 'selected' => $values['id_group'], + 'return' => true, + 'class' => 'w50p', + ] + ); + $return .= html_print_input( + [ + 'label' => __('Product'), + 'name' => 'product', + 'input_class' => 'flex-row', + 'type' => 'select', + 'script' => 'calculate_inputs()', + 'fields' => [ + 'CUSTOM' => __('Custom'), + 'AWS' => __('Aws'), + 'AZURE' => __('Azure'), + // 'GOOGLE' => __('Google'), + ], + 'selected' => $values['product'], + 'disabled' => (bool) $values['product'], + 'return' => true, + ] + ); + $user_label = __('Username'); + $pass_label = __('Password'); + $extra_1_label = __('Extra'); + $extra_2_label = __('Extra (2)'); + $extra1 = true; + $extra2 = true; + + // Remember to update credential_store.php also. + switch ($values['product']) { + case 'AWS': + $user_label = __('Access key ID'); + $pass_label = __('Secret access key'); + $extra1 = false; + $extra2 = false; + break; + + case 'AZURE': + $user_label = __('Account ID'); + $pass_label = __('Application secret'); + $extra_1_label = __('Tenant or domain name'); + $extra_2_label = __('Subscription id'); + break; + + case 'GOOGLE': + // Need further investigation. + case 'CUSTOM': + $user_label = __('Account ID'); + $pass_label = __('Password'); + $extra1 = false; + $extra2 = false; + default: + // Use defaults. + break; + } + + $return .= html_print_input( + [ + 'label' => $user_label, + 'name' => 'username', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['username'], + 'return' => true, + ] + ); + $return .= html_print_input( + [ + 'label' => $pass_label, + 'name' => 'password', + 'input_class' => 'flex-row', + 'type' => 'password', + 'value' => $values['password'], + 'return' => true, + ] + ); + if ($extra1) { + $return .= html_print_input( + [ + 'label' => $extra_1_label, + 'name' => 'extra_1', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['extra_1'], + 'return' => true, + ] + ); + } + + if ($extra2) { + $return .= html_print_input( + [ + 'label' => $extra_2_label, + 'name' => 'extra_2', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['extra_2'], + 'return' => true, + 'display' => $extra2, + ] + ); + } + + return $return; +} + + +/** + * Retrieve all identifiers available for current user. + * + * @param string $product Target product. + * + * @return array Of account identifiers. + */ +function credentials_list_accounts($product) +{ + global $config; + + check_login(); + + include_once $config['homedir'].'/include/functions_users.php'; + + static $user_groups; + + if (!isset($user_groups)) { + $user_groups = users_get_groups( + $config['id_user'], + 'AR' + ); + + // Always add group 'ALL' because 'ALL' group credentials + // must be available for all users. + if (is_array($user_groups)) { + $user_groups = ([0] + array_keys($user_groups)); + } else { + $user_groups = [0]; + } + } + + $creds = credentials_get_all( + ['identifier'], + [ + 'product' => $product, + 'group_list' => $user_groups, + ] + ); + + if ($creds === false) { + return []; + } + + $ret = array_reduce( + $creds, + function ($carry, $item) { + $carry[$item['identifier']] = $item['identifier']; + return $carry; + } + ); + + return $ret; +} diff --git a/pandora_console/include/functions_custom_fields.php b/pandora_console/include/functions_custom_fields.php index 9570098766..d1f661e874 100644 --- a/pandora_console/include/functions_custom_fields.php +++ b/pandora_console/include/functions_custom_fields.php @@ -188,10 +188,16 @@ function get_custom_fields_data($custom_field_name) } $array_result = []; - if (isset($result_meta) && is_array($result_meta)) { + if (isset($result_meta) === true + && is_array($result_meta) === true + ) { foreach ($result_meta as $result) { - foreach ($result as $k => $v) { - $array_result[$v['description']] = $v['description']; + if (isset($result) === true + && is_array($result) === true + ) { + foreach ($result as $k => $v) { + $array_result[$v['description']] = $v['description']; + } } } } @@ -385,9 +391,13 @@ function agent_counters_custom_fields($filters) // Filter custom data. $custom_data_and = ''; - if (!in_array(-1, $filters['id_custom_fields_data'])) { - $custom_data_array = implode("', '", $filters['id_custom_fields_data']); - $custom_data_and = "AND tcd.description IN ('".$custom_data_array."')"; + if (isset($filters['id_custom_fields_data']) === true + && is_array($filters['id_custom_fields_data']) === true + ) { + if (!in_array(-1, $filters['id_custom_fields_data'])) { + $custom_data_array = implode("', '", $filters['id_custom_fields_data']); + $custom_data_and = "AND tcd.description IN ('".$custom_data_array."')"; + } } // Filter custom name. @@ -693,3 +703,123 @@ function print_counters_cfv( $html_result .= ''; return $html_result; } + + +/** + * Function for export a csv file from Custom Fields View + * + * @param array $filters Status counters for agents and modules. + * @param array $id_status Agent status. + * @param array $module_status Module status. + * + * @return array Returns the data that will be saved in the csv file + */ +function export_custom_fields_csv($filters, $id_status, $module_status) +{ + $data = agent_counters_custom_fields($filters); + $indexed_descriptions = $data['indexed_descriptions']; + + // Table temporary for save array in table + // by order and search custom_field data. + $table_temporary = 'CREATE TEMPORARY TABLE temp_custom_fields ( + id_server int(10), + id_agent int(10), + name_custom_fields varchar(2048), + critical_count int, + warning_count int, + unknown_count int, + notinit_count int, + normal_count int, + total_count int, + `status` int(2), + KEY `data_index_temp_1` (`id_server`, `id_agent`) + )'; + db_process_sql($table_temporary); + + // Insert values array in table temporary. + $values_insert = []; + foreach ($indexed_descriptions as $key => $value) { + $values_insert[] = '('.$value['id_server'].', '.$value['id_agente'].", '".$value['description']."', '".$value['critical_count']."', '".$value['warning_count']."', '".$value['unknown_count']."', '".$value['notinit_count']."', '".$value['normal_count']."', '".$value['total_count']."', ".$value['status'].')'; + } + + $values_insert_implode = implode(',', $values_insert); + $query_insert = 'INSERT INTO temp_custom_fields VALUES '.$values_insert_implode; + db_process_sql($query_insert); + + // Search for status module. + $status_agent_search = ''; + if (isset($id_status) === true && is_array($id_status) === true) { + if (in_array(-1, $id_status) === false) { + if (in_array(AGENT_MODULE_STATUS_NOT_NORMAL, $id_status) === false) { + $status_agent_search = ' AND temp.status IN ('.implode(',', $id_status).')'; + } else { + // Not normal statuses. + $status_agent_search = ' AND temp.status IN (1,2,3,4,5)'; + } + } + } + + // Search for status module. + $status_module_search = ''; + if (isset($module_status) === true && is_array($module_status) === true) { + if (in_array(-1, $module_status) === false) { + if (in_array(AGENT_MODULE_STATUS_NOT_NORMAL, $module_status) === false) { + if (count($module_status) > 0) { + $status_module_search = ' AND ( '; + foreach ($module_status as $key => $value) { + $status_module_search .= ($key != 0) ? ' OR (' : ' ('; + switch ($value) { + default: + case AGENT_STATUS_NORMAL: + $status_module_search .= ' temp.normal_count > 0) '; + break; + case AGENT_STATUS_CRITICAL: + $status_module_search .= ' temp.critical_count > 0) '; + break; + + case AGENT_STATUS_WARNING: + $status_module_search .= ' temp.warning_count > 0) '; + break; + + case AGENT_STATUS_UNKNOWN: + $status_module_search .= ' temp.unknown_count > 0) '; + break; + + case AGENT_STATUS_NOT_INIT: + $status_module_search .= ' temp.notinit_count > 0) '; + break; + } + } + + $status_module_search .= ' ) '; + } + } else { + // Not normal. + $status_module_search = ' AND ( temp.critical_count > 0 OR temp.warning_count > 0 OR temp.unknown_count > 0 AND temp.notinit_count > 0 )'; + } + } + } + + // Query all fields result. + $query = sprintf( + 'SELECT + temp.name_custom_fields, + tma.alias, + tma.direccion, + tma.server_name, + temp.status + FROM tmetaconsole_agent tma + INNER JOIN temp_custom_fields temp + ON temp.id_agent = tma.id_tagente + AND temp.id_server = tma.id_tmetaconsole_setup + WHERE tma.disabled = 0 + %s + %s + ', + $status_agent_search, + $status_module_search + ); + + $result = db_get_all_rows_sql($query); + return $result; +} diff --git a/pandora_console/include/functions_custom_graphs.php b/pandora_console/include/functions_custom_graphs.php index f98084f808..4a1c5df11c 100644 --- a/pandora_console/include/functions_custom_graphs.php +++ b/pandora_console/include/functions_custom_graphs.php @@ -184,7 +184,7 @@ function custom_graphs_search($id_group, $search) FROM tgraph_source WHERE id_graph = '.$graph['id_graph'].'' ); - + $graphs[$graph['id_graph']]['id_graph'] = $graph['id_graph']; $graphs[$graph['id_graph']]['graphs_count'] = $graphsCount; $graphs[$graph['id_graph']]['name'] = $graph['name']; $graphs[$graph['id_graph']]['description'] = $graph['description']; diff --git a/pandora_console/include/functions_db.php b/pandora_console/include/functions_db.php index 2061ab215c..3efbf59628 100644 --- a/pandora_console/include/functions_db.php +++ b/pandora_console/include/functions_db.php @@ -2023,3 +2023,58 @@ function db_check_minor_relase_available_to_um($package, $ent, $offline) return false; } } + + +/** + * Tries to get a lock with current name. + * + * @param string $lockname Lock name. + * @param integer $expiration_time Expiration time. + * + * @return integer 1 - lock OK, able to continue executing + * 0 - already locked by another process. + * NULL: something really bad happened + */ +function db_get_lock($lockname, $expiration_time=86400) +{ + $lock_status = db_get_value_sql( + sprintf( + 'SELECT IS_FREE_LOCK("%s")', + $lockname + ) + ); + + if ($lock_status == 1) { + $lock_status = db_get_value_sql( + sprintf( + 'SELECT GET_LOCK("%s", %d)', + $lockname, + $expiration_time + ) + ); + + return $lock_status; + } + + return 0; +} + + +/** + * Release a previously defined lock. + * + * @param string $lockname Lock name. + * + * @return integer 1 Lock released. + * 0 cannot release (not owned). + * NULL lock does not exist. + */ +function db_release_lock($lockname) +{ + return db_get_value_sql( + sprintf( + 'SELECT RELEASE_LOCK("%s")', + $lockname + ) + ); +} diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index 3feceb847b..ffb36aa3ae 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -25,13 +25,154 @@ * GNU General Public License for more details. * ============================================================================ */ +global $config; require_once $config['homedir'].'/include/functions_ui.php'; require_once $config['homedir'].'/include/functions_tags.php'; require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/functions_reporting.php'; +enterprise_include_once('include/functions_metaconsole.php'); enterprise_include_once('meta/include/functions_events_meta.php'); enterprise_include_once('meta/include/functions_agents_meta.php'); enterprise_include_once('meta/include/functions_modules_meta.php'); +enterprise_include_once('meta/include/functions_events_meta.php'); + + +/** + * Translates a numeric value module_status into descriptive text. + * + * @param integer $status Module status. + * + * @return string Descriptive text. + */ +function events_translate_module_status($status) +{ + switch ($status) { + case AGENT_MODULE_STATUS_NORMAL: + return __('NORMAL'); + + case AGENT_MODULE_STATUS_CRITICAL_BAD: + return __('CRITICAL'); + + case AGENT_MODULE_STATUS_NO_DATA: + return __('NOT INIT'); + + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + case AGENT_MODULE_STATUS_NORMAL_ALERT: + case AGENT_MODULE_STATUS_WARNING_ALERT: + return __('ALERT'); + + case AGENT_MODULE_STATUS_WARNING: + return __('WARNING'); + + default: + return __('UNKNOWN'); + } +} + + +/** + * Translates a numeric value event_type into descriptive text. + * + * @param integer $event_type Event type. + * + * @return string Descriptive text. + */ +function events_translate_event_type($event_type) +{ + // Event type prepared. + switch ($event_type) { + case EVENTS_ALERT_FIRED: + case EVENTS_ALERT_RECOVERED: + case EVENTS_ALERT_CEASED: + case EVENTS_ALERT_MANUAL_VALIDATION: + return __('ALERT'); + + case EVENTS_RECON_HOST_DETECTED: + case EVENTS_SYSTEM: + case EVENTS_ERROR: + case EVENTS_NEW_AGENT: + case EVENTS_CONFIGURATION_CHANGE: + return __('SYSTEM'); + + case EVENTS_GOING_UP_WARNING: + case EVENTS_GOING_DOWN_WARNING: + return __('WARNING'); + + case EVENTS_GOING_DOWN_NORMAL: + case EVENTS_GOING_UP_NORMAL: + return __('NORMAL'); + + case EVENTS_GOING_DOWN_CRITICAL: + case EVENTS_GOING_UP_CRITICAL: + return __('CRITICAL'); + + case EVENTS_UNKNOWN: + case EVENTS_GOING_UNKNOWN: + default: + return __('UNKNOWN'); + } +} + + +/** + * Translates a numeric value event_status into descriptive text. + * + * @param integer $status Event status. + * + * @return string Descriptive text. + */ +function events_translate_event_status($status) +{ + switch ($status) { + case EVENT_STATUS_NEW: + default: + return __('NEW'); + + case EVENT_STATUS_INPROCESS: + return __('IN PROCESS'); + + case EVENT_STATUS_VALIDATED: + return __('VALIDATED'); + } +} + + +/** + * Translates a numeric value criticity into descriptive text. + * + * @param integer $criticity Event criticity. + * + * @return string Descriptive text. + */ +function events_translate_event_criticity($criticity) +{ + switch ($criticity) { + case EVENT_CRIT_CRITICAL: + return __('CRITICAL'); + + case EVENT_CRIT_MAINTENANCE: + return __('MAINTENANCE'); + + case EVENT_CRIT_INFORMATIONAL: + return __('INFORMATIONAL'); + + case EVENT_CRIT_MAJOR: + return __('MAJOR'); + + case EVENT_CRIT_MINOR: + return __('MINOR'); + + case EVENT_CRIT_NORMAL: + return __('NORMAL'); + + case EVENT_CRIT_WARNING: + return __('WARNING'); + + default: + return __('UNKNOWN'); + } +} /** @@ -69,6 +210,1133 @@ function events_get_all_fields() } +/** + * Same as events_get_column_names but retrieving only one result. + * + * @param string $field Raw field name. + * + * @return string Traduction. + */ +function events_get_column_name($field, $table_alias=false) +{ + switch ($field) { + case 'id_evento': + return __('Event Id'); + + case 'evento': + return __('Event Name'); + + case 'id_agente': + return __('Agent ID'); + + case 'agent_name': + return __('Agent name'); + + case 'agent_alias': + return __('Agent alias'); + + case 'id_usuario': + return __('User'); + + case 'id_grupo': + return __('Group'); + + case 'estado': + return __('Status'); + + case 'timestamp': + return __('Timestamp'); + + case 'event_type': + return __('Event Type'); + + case 'id_agentmodule': + return __('Module Name'); + + case 'id_alert_am': + return __('Alert'); + + case 'criticity': + return __('Severity'); + + case 'user_comment': + return __('Comment'); + + case 'tags': + return __('Tags'); + + case 'source': + return __('Source'); + + case 'id_extra': + return __('Extra Id'); + + case 'owner_user': + return __('Owner'); + + case 'ack_utimestamp': + return __('ACK Timestamp'); + + case 'instructions': + return __('Instructions'); + + case 'server_name': + return __('Server Name'); + + case 'data': + return __('Data'); + + case 'module_status': + return __('Module Status'); + + case 'options': + return __('Options'); + + case 'mini_severity': + if ($table_alias === true) { + return 'S'; + } else { + return __('Severity mini'); + } + + default: + return __($field); + } +} + + +/** + * Return column names from fields selected. + * + * @param array $fields Array of fields. + * + * @return array Names array. + */ +function events_get_column_names($fields, $table_alias=false) +{ + if (!isset($fields) || !is_array($fields)) { + return []; + } + + $names = []; + foreach ($fields as $f) { + if (is_array($f)) { + $name = []; + $name['text'] = events_get_column_name($f['text'], $table_alias); + $name['class'] = $f['class']; + $name['style'] = $f['style']; + $name['extra'] = $f['extra']; + $name['id'] = $f['id']; + $names[] = $name; + } else { + $names[] = events_get_column_name($f, $table_alias); + } + } + + return $names; + +} + + +/** + * Validates all events matching target filter. + * + * @param integer $id_evento Master event. + * @param array $filter Optional. Filter options. + * @param boolean $history Apply on historical table. + * + * @return integer Events validated or false if error. + */ +function events_delete($id_evento, $filter=null, $history=false) +{ + if (!isset($id_evento) || $id_evento <= 0) { + return false; + } + + if (!isset($filter) || !is_array($filter)) { + $filter = ['group_rep' => 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $delete_sql = sprintf( + 'DELETE FROM %s + WHERE id_evento = %d', + $table, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + + $target_ids = db_get_all_rows_sql( + sprintf( + 'SELECT tu.id_evento FROM %s tu INNER JOIN ( %s ) tf + ON tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $table, + $sql, + $id_evento + ) + ); + + // Try to avoid deadlock while updating full set. + if ($target_ids !== false && count($target_ids) > 0) { + $target_ids = array_reduce( + $target_ids, + function ($carry, $item) { + $carry[] = $item['id_evento']; + return $carry; + } + ); + + $delete_sql = sprintf( + 'DELETE FROM %s WHERE id_evento IN (%s)', + $table, + join(', ', $target_ids) + ); + } + break; + } + + return db_process_sql($delete_sql); +} + + +/** + * Retrieves all events related to matching one. + * + * @param integer $id_evento Master event (max_id_evento). + * @param array $filter Filters. + * @param boolean $count Count results or get results. + * @param boolean $history Apply on historical table. + * + * @return array Events or false in case of error. + */ +function events_get_related_events( + $id_evento, + $filter=null, + $count=false, + $history=false +) { + global $config; + + if (!isset($id_evento) || $id_evento <= 0) { + return false; + } + + if (!isset($filter) || !is_array($filter)) { + $filter = ['group_rep' => 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + $select = '*'; + if ($count === true) { + $select = 'count(*) as n'; + }; + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $related_sql = sprintf( + 'SELECT %s FROM %s + WHERE id_evento = %d', + $select, + $table, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + $related_sql = sprintf( + 'SELECT %s FROM %s tu INNER JOIN ( %s ) tf + WHERE tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $select, + $table, + $sql, + $id_evento + ); + break; + } + + if ($count === true) { + $r = db_get_all_rows_sql($related_sql); + + return $r[0]['n']; + } + + return db_get_all_rows_sql($related_sql); + +} + + +/** + * Validates all events matching target filter. + * + * @param integer $id_evento Master event. + * @param integer $status Target status. + * @param array $filter Optional. Filter options. + * @param boolean $history Apply on historical table. + * + * @return integer Events validated or false if error. + */ +function events_update_status($id_evento, $status, $filter=null, $history=false) +{ + global $config; + + if (!$status) { + error_log('No hay estado'); + return false; + } + + if (!isset($id_evento) || $id_evento <= 0) { + error_log('No hay id_evento'); + return false; + } + + if (!isset($filter) || !is_array($filter)) { + $filter = ['group_rep' => 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $update_sql = sprintf( + 'UPDATE %s + SET estado = %d + WHERE id_evento = %d', + $table, + $status, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + + $target_ids = db_get_all_rows_sql( + sprintf( + 'SELECT tu.id_evento FROM %s tu INNER JOIN ( %s ) tf + ON tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $table, + $sql, + $id_evento + ) + ); + + // Try to avoid deadlock while updating full set. + if ($target_ids !== false && count($target_ids) > 0) { + $target_ids = array_reduce( + $target_ids, + function ($carry, $item) { + $carry[] = $item['id_evento']; + return $carry; + } + ); + + $update_sql = sprintf( + 'UPDATE %s + SET estado = %d, + ack_utimestamp = %d, + id_usuario = "%s" + WHERE id_evento IN (%s)', + $table, + $status, + time(), + $config['id_user'], + join(',', $target_ids) + ); + } + break; + } + + return db_process_sql($update_sql); +} + + +/** + * Retrieve all events filtered. + * + * @param array $fields Fields to retrieve. + * @param array $filter Filters to be applied. + * @param integer $offset Offset (pagination). + * @param integer $limit Limit (pagination). + * @param string $order Sort order. + * @param string $sort_field Sort field. + * @param boolean $history Apply on historical table. + * @param boolean $return_sql Return SQL (true) or execute it (false). + * @param string $having Having filter. + * + * @return array Events. + * @throws Exception On error. + */ +function events_get_all( + $fields, + array $filter, + $offset=null, + $limit=null, + $order=null, + $sort_field=null, + $history=false, + $return_sql=false, + $having='' +) { + global $config; + + $user_is_admin = users_is_admin(); + + if (!is_array($filter)) { + error_log('[events_get_all] Filter must be an array.'); + throw new Exception('[events_get_all] Filter must be an array.'); + } + + $count = false; + if (!is_array($fields) && $fields == 'count') { + $fields = ['te.*']; + $count = true; + } else if (!is_array($fields)) { + error_log('[events_get_all] Fields must be an array or "count".'); + throw new Exception('[events_get_all] Fields must be an array or "count".'); + } + + if (isset($filter['date_from']) + && !empty($filter['date_from']) + && $filter['date_from'] != '0000-00-00' + ) { + $date_from = $filter['date_from']; + } + + if (isset($filter['time_from'])) { + $time_from = $filter['time_from']; + } + + if (isset($date_from)) { + if (!isset($time_from)) { + $time_from = '00:00:00'; + } + + $from = $date_from.' '.$time_from; + $sql_filters[] = sprintf( + ' AND te.utimestamp >= %d', + strtotime($from) + ); + } + + if (isset($filter['date_to']) + && !empty($filter['date_to']) + && $filter['date_to'] != '0000-00-00' + ) { + $date_to = $filter['date_to']; + } + + if (isset($filter['time_to'])) { + $time_to = $filter['time_to']; + } + + if (isset($date_to)) { + if (!isset($time_to)) { + $time_to = '23:59:59'; + } + + $to = $date_to.' '.$time_to; + $sql_filters[] = sprintf( + ' AND te.utimestamp <= %d', + strtotime($to) + ); + } + + if (!isset($from)) { + if (isset($filter['event_view_hr']) && ($filter['event_view_hr'] > 0)) { + $sql_filters[] = sprintf( + ' AND utimestamp > UNIX_TIMESTAMP(now() - INTERVAL %d HOUR) ', + $filter['event_view_hr'] + ); + } + } + + if (isset($filter['id_agent']) && $filter['id_agent'] > 0) { + $sql_filters[] = sprintf( + ' AND te.id_agente = %d ', + $filter['id_agent'] + ); + } + + if (!empty($filter['event_type']) && $filter['event_type'] != 'all') { + if ($filter['event_type'] == 'warning' + || $filter['event_type'] == 'critical' + || $filter['event_type'] == 'normal' + ) { + $sql_filters[] = ' AND event_type LIKE "%'.$filter['event_type'].'%"'; + } else if ($filter['event_type'] == 'not_normal') { + $sql_filters[] = ' AND (event_type LIKE "%warning%" + OR event_type LIKE "%critical%" + OR event_type LIKE "%unknown%")'; + } else { + $sql_filters[] = ' AND event_type = "'.$filter['event_type'].'"'; + } + } + + if (isset($filter['severity']) && $filter['severity'] > 0) { + switch ($filter['severity']) { + case EVENT_CRIT_MAINTENANCE: + case EVENT_CRIT_INFORMATIONAL: + case EVENT_CRIT_NORMAL: + case EVENT_CRIT_MINOR: + case EVENT_CRIT_WARNING: + case EVENT_CRIT_MAJOR: + case EVENT_CRIT_CRITICAL: + default: + $sql_filters[] = sprintf( + ' AND criticity = %d ', + $filter['severity'] + ); + break; + + case EVENT_CRIT_WARNING_OR_CRITICAL: + $sql_filters[] = sprintf( + ' AND (criticity = %d OR criticity = %d)', + EVENT_CRIT_WARNING, + EVENT_CRIT_CRITICAL + ); + break; + + case EVENT_CRIT_NOT_NORMAL: + $sql_filters[] = sprintf( + ' AND criticity != %d', + EVENT_CRIT_NORMAL + ); + break; + + case EVENT_CRIT_OR_NORMAL: + $sql_filters[] = sprintf( + ' AND (criticity = %d OR criticity = %d)', + EVENT_CRIT_NORMAL, + EVENT_CRIT_CRITICAL + ); + break; + } + } + + $groups = $filter['id_group_filter']; + if (isset($groups) && $groups > 0) { + $propagate = db_get_value( + 'propagate', + 'tgrupo', + 'id_grupo', + $groups + ); + + if (!$propagate) { + $sql_filters[] = sprintf( + ' AND (te.id_grupo = %d OR tasg.id_group = %d)', + $groups + ); + } else { + $children = groups_get_children($groups); + $_groups = [ $groups ]; + if (!empty($children)) { + foreach ($children as $child) { + $_groups[] = (int) $child['id_grupo']; + } + } + + $groups = $_groups; + + $sql_filters[] = sprintf( + ' AND (te.id_grupo IN (%s) OR tasg.id_group IN (%s))', + join(',', $groups), + join(',', $groups) + ); + } + } + + // Skip system messages if user is not PM. + if (!check_acl($config['id_user'], 0, 'PM')) { + $sql_filters[] = ' AND te.id_grupo != 0 '; + } + + if (isset($filter['status'])) { + switch ($filter['status']) { + case EVENT_ALL: + default: + // Do not filter. + break; + + case EVENT_NEW: + case EVENT_VALIDATE: + case EVENT_PROCESS: + $sql_filters[] = sprintf( + ' AND estado = %d', + $filter['status'] + ); + break; + + case EVENT_NO_VALIDATED: + $sql_filters[] = sprintf( + ' AND (estado = %d OR estado = %d)', + EVENT_NEW, + EVENT_PROCESS + ); + break; + } + } + + if (!$user_is_admin) { + $ER_groups = users_get_groups($config['id_user'], 'ER', false); + $EM_groups = users_get_groups($config['id_user'], 'EM', false, true); + $EW_groups = users_get_groups($config['id_user'], 'EW', false, true); + } + + if (!$user_is_admin && !users_can_manage_group_all('ER')) { + // Get groups where user have ER grants. + $sql_filters[] = sprintf( + ' AND (te.id_grupo IN ( %s ) OR tasg.id_group IN (%s))', + join(', ', array_keys($ER_groups)), + join(', ', array_keys($ER_groups)) + ); + } + + $table = events_get_events_table(is_metaconsole(), $history); + $tevento = sprintf( + ' %s te', + $table + ); + + // Prepare agent join sql filters. + $agent_join_filters = []; + $tagente_table = 'tagente'; + $tagente_field = 'id_agente'; + $conditionMetaconsole = ''; + if (is_metaconsole()) { + $tagente_table = 'tmetaconsole_agent'; + $tagente_field = 'id_tagente'; + $conditionMetaconsole = ' AND ta.id_tmetaconsole_setup = te.server_id '; + } + + // Agent alias. + if (!empty($filter['agent_alias'])) { + $agent_join_filters[] = sprintf( + ' AND ta.alias = "%s" ', + $filter['agent_alias'] + ); + } + + // Free search. + if (!empty($filter['search'])) { + if (isset($config['dbconnection']->server_version) + && $config['dbconnection']->server_version > 50600 + ) { + // Use "from_base64" requires mysql 5.6 or greater. + $custom_data_search = 'from_base64(te.custom_data)'; + } else { + // Custom data is JSON encoded base64, if 5.6 or lower, + // user is condemned to use plain search. + $custom_data_search = 'te.custom_data'; + } + + $sql_filters[] = vsprintf( + ' AND (lower(ta.alias) like lower("%%%s%%") + OR te.id_evento like "%%%s%%" + OR lower(te.evento) like lower("%%%s%%") + OR lower(te.user_comment) like lower("%%%s%%") + OR lower(te.id_extra) like lower("%%%s%%") + OR lower(te.source) like lower("%%%s%%") + OR lower('.$custom_data_search.') like lower("%%%s%%") )', + array_fill(0, 7, $filter['search']) + ); + } + + // Id extra. + if (!empty($filter['id_extra'])) { + $sql_filters[] = sprintf( + ' AND lower(te.id_extra) like lower("%%%s%%") ', + $filter['id_extra'] + ); + } + + // User comment. + if (!empty($filter['user_comment'])) { + $sql_filters[] = sprintf( + ' AND lower(te.user_comment) like lower("%%%s%%") ', + $filter['user_comment'] + ); + } + + // Source. + if (!empty($filter['source'])) { + $sql_filters[] = sprintf( + ' AND lower(te.source) like lower("%%%s%%") ', + $filter['source'] + ); + } + + // Validated or in process by. + if (!empty($filter['id_user_ack'])) { + $sql_filters[] = sprintf( + ' AND te.id_usuario like lower("%%%s%%") ', + $filter['id_user_ack'] + ); + } + + $tag_names = []; + // With following tags. + if (!empty($filter['tag_with'])) { + $tag_with = base64_decode($filter['tag_with']); + $tags = json_decode($tag_with, true); + if (is_array($tags) && !in_array('0', $tags)) { + if (!$user_is_admin) { + $user_tags = array_flip(tags_get_tags_for_module_search()); + if ($user_tags != null) { + foreach ($tags as $id_tag) { + // User cannot filter with those tags. + if (!array_search($id_tag, $user_tags)) { + return false; + } + } + } + } + + foreach ($tags as $id_tag) { + if (!isset($tags_names[$id_tag])) { + $tags_names[$id_tag] = tags_get_name($id_tag); + } + + $_tmp .= ' AND ( '; + $_tmp .= sprintf( + ' tags LIKE "%s" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%s,%%" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%%,%s" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%%,%s,%%" ', + $tags_names[$id_tag] + ); + + $_tmp .= ') '; + } + + $sql_filters[] = $_tmp; + } + } + + // Without following tags. + if (!empty($filter['tag_without'])) { + $tag_without = base64_decode($filter['tag_without']); + $tags = json_decode($tag_without, true); + if (is_array($tags) && !in_array('0', $tags)) { + foreach ($tags as $id_tag) { + if (!isset($tags_names[$id_tag])) { + $tags_names[$id_tag] = tags_get_name($id_tag); + } + + $_tmp .= sprintf( + ' AND tags NOT LIKE "%s" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%s,%%" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%%,%s" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%%,%s,%%" ', + $tags_names[$id_tag] + ); + } + + $sql_filters[] = $_tmp; + } + } + + // Filter/ Only alerts. + if (isset($filter['filter_only_alert'])) { + if ($filter['filter_only_alert'] == 0) { + $sql_filters[] = ' AND event_type NOT LIKE "%alert%"'; + } else if ($filter['filter_only_alert'] == 1) { + $sql_filters[] = ' AND event_type LIKE "%alert%"'; + } + } + + // TAgs ACLS. + if (check_acl($config['id_user'], 0, 'ER')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $ER_groups, + // Access. + 'ER', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } else if (check_acl($config['id_user'], 0, 'EW')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $EW_groups, + // Access. + 'EW', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } else if (check_acl($config['id_user'], 0, 'EM')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $EM_groups, + // Access. + 'EM', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } + + if (($tags_acls_condition != ERR_WRONG_PARAMETERS) + && ($tags_acls_condition != ERR_ACL) + ) { + $sql_filters[] = $tags_acls_condition; + } + + // Module search. + $agentmodule_join = 'LEFT JOIN tagente_modulo am ON te.id_agentmodule = am.id_agente_modulo'; + if (is_metaconsole()) { + $agentmodule_join = ''; + } else if (!empty($filter['module_search'])) { + $agentmodule_join = 'INNER JOIN tagente_modulo am ON te.id_agentmodule = am.id_agente_modulo'; + $sql_filters[] = sprintf( + ' AND am.nombre = "%s" ', + $filter['module_search'] + ); + } + + // Order. + $order_by = ''; + if (isset($order, $sort_field)) { + $order_by = events_get_sql_order($sort_field, $order); + } + + // Pagination. + $pagination = ''; + if (isset($limit, $offset) && $limit > 0) { + $pagination = sprintf(' LIMIT %d OFFSET %d', $limit, $offset); + } + + $extra = ''; + if (is_metaconsole()) { + $extra = ', server_id'; + } + + // Group by. + $group_by = 'GROUP BY '; + $tagente_join = 'LEFT'; + switch ($filter['group_rep']) { + case '0': + default: + // All events. + $group_by = ''; + break; + + case '1': + // Group by events. + $group_by .= 'te.estado, te.evento, te.id_agente, te.id_agentmodule'; + $group_by .= $extra; + break; + + case '2': + // Group by agents. + $tagente_join = 'INNER'; + // $group_by .= 'te.id_agente, te.event_type'; + // $group_by .= $extra; + $group_by = ''; + $order_by = events_get_sql_order('id_agente', 'asc'); + if (isset($order, $sort_field)) { + $order_by .= ','.events_get_sql_order( + $sort_field, + $order, + 0, + true + ); + } + break; + } + + $tgrupo_join = 'LEFT'; + $tgrupo_join_filters = []; + if (isset($groups) + && (is_array($groups) + || $groups > 0) + ) { + $tgrupo_join = 'INNER'; + if (is_array($groups)) { + $tgrupo_join_filters[] = sprintf( + ' AND (tg.id_grupo IN (%s) OR tasg.id_group IN (%s))', + join(', ', $groups), + join(', ', $groups) + ); + } else { + $tgrupo_join_filters[] = sprintf( + ' AND (tg.id_grupo = %s OR tasg.id_group = %s)', + $groups, + $groups + ); + } + } + + $server_join = ''; + if (is_metaconsole()) { + $server_join = ' LEFT JOIN tmetaconsole_setup ts + ON ts.id = te.server_id'; + if (!empty($filter['server_id'])) { + $server_join = sprintf( + ' INNER JOIN tmetaconsole_setup ts + ON ts.id = te.server_id AND ts.id= %d', + $filter['server_id'] + ); + } + } + + // Secondary groups. + db_process_sql('SET group_concat_max_len = 9999999'); + $event_lj = events_get_secondary_groups_left_join($table); + + $group_selects = ''; + if ($group_by != '') { + $group_selects = ',COUNT(id_evento) AS event_rep + ,GROUP_CONCAT(DISTINCT user_comment SEPARATOR "
") AS comments, + MAX(utimestamp) as timestamp_last, + MIN(utimestamp) as timestamp_first, + MAX(id_evento) as max_id_evento'; + + if ($count === false) { + $idx = array_search('te.user_comment', $fields); + if ($idx !== false) { + unset($fields[$idx]); + } + } + } + + $sql = sprintf( + 'SELECT %s + %s + FROM %s + %s + %s + %s JOIN %s ta + ON ta.%s = te.id_agente + %s + %s + %s JOIN tgrupo tg + ON te.id_grupo = tg.id_grupo + %s + %s + WHERE 1=1 + %s + %s + %s + %s + %s + ', + join(',', $fields), + $group_selects, + $tevento, + $event_lj, + $agentmodule_join, + $tagente_join, + $tagente_table, + $tagente_field, + $conditionMetaconsole, + join(' ', $agent_join_filters), + $tgrupo_join, + join(' ', $tgrupo_join_filters), + $server_join, + join(' ', $sql_filters), + $group_by, + $order_by, + $pagination, + $having + ); + + if (!$user_is_admin) { + // XXX: Confirm there's no extra grants unhandled!. + $can_manage = '0 as user_can_manage'; + if (!empty($EM_groups)) { + $can_manage = sprintf( + '(tbase.id_grupo IN (%s)) as user_can_manage', + join(', ', array_keys($EM_groups)) + ); + } + + $can_write = '0 as user_can_write'; + if (!empty($EW_groups)) { + $can_write = sprintf( + '(tbase.id_grupo IN (%s)) as user_can_write', + join(', ', array_keys($EW_groups)) + ); + } + + $sql = sprintf( + 'SELECT + tbase.*, + %s, + %s + FROM + (', + $can_manage, + $can_write + ).$sql.') tbase'; + } else { + $sql = 'SELECT + tbase.*, + 1 as user_can_manage, + 1 as user_can_write + FROM + ('.$sql.') tbase'; + } + + if ($count) { + $sql = 'SELECT count(*) as nitems FROM ('.$sql.') tt'; + } + + if ($return_sql) { + return $sql; + } + + return db_get_all_rows_sql($sql); +} + + /** * Get all rows of events from the database, that * pass the filter, and can get only some fields. @@ -192,7 +1460,7 @@ function events_get_events_no_grouped( /** * Return all events matching sql_post grouped. * - * @param [type] $sql_post Sql_post. + * @param string $sql_post Sql_post. * @param integer $offset Offset. * @param integer $pagination Pagination. * @param boolean $meta Meta. @@ -213,7 +1481,7 @@ function events_get_events_grouped( $total=false, $history_db=false, $order='down', - $sort_field='timestamp' + $sort_field='utimestamp' ) { global $config; @@ -431,7 +1699,7 @@ function events_change_status( $ack_user = $config['id_user']; } else { $acl_utimestamp = 0; - $ack_user = ''; + $ack_user = $config['id_user']; } switch ($new_status) { @@ -1034,7 +2302,7 @@ function events_print_event_table( } $table->head[$i] = __('Timestamp'); - $table->headstyle[$i] = 'width: 120px;'; + $table->headstyle[$i] = 'width: 150px;'; $table->style[$i++] = 'word-break: break-word;'; $table->head[$i] = __('Status'); @@ -1130,10 +2398,10 @@ function events_print_event_table( } $events_table = html_print_table($table, true); - $out = '
'; - $out .= $events_table; + $out = $events_table; if (!$tactical_view) { + $out .= '
'; if ($agent_id != 0) { $out .= ''; $out .= '
'; @@ -1149,9 +2417,9 @@ function events_print_event_table( '.__('Event graph by agent').''.grafico_eventos_grupo(180, 60).''; $out .= '
'; } - } - $out .= '
'; + $out .= '
'; + } unset($table); @@ -1901,7 +3169,7 @@ function events_get_event_filter_select($manage=true) } else { $user_groups = users_get_groups( $config['id_user'], - 'EW', + 'ER', users_can_manage_group_all(), true ); @@ -1914,7 +3182,7 @@ function events_get_event_filter_select($manage=true) $sql = ' SELECT id_filter, id_name FROM tevent_filter - WHERE id_group_filter IN ('.implode(',', array_keys($user_groups)).')'; + WHERE id_group_filter IN (0, '.implode(',', array_keys($user_groups)).')'; $event_filters = db_get_all_rows_sql($sql); @@ -1946,6 +3214,7 @@ function events_page_responses($event, $childrens_ids=[]) // // Responses. // + $table_responses = new StdClass(); $table_responses->cellspacing = 2; $table_responses->cellpadding = 2; $table_responses->id = 'responses_table'; @@ -2618,7 +3887,7 @@ function events_page_details($event, $server='') global $config; // If server is provided, get the hash parameters. - if (!empty($server) && defined('METACONSOLE')) { + if (!empty($server) && is_metaconsole()) { $hashdata = metaconsole_get_server_hashdata($server); $hashstring = '&loginhash=auto&loginhash_data='.$hashdata.'&loginhash_user='.str_rot13($config['id_user']); $serverstring = $server['server_url'].'/'; @@ -2895,7 +4164,7 @@ function events_page_details($event, $server='') $data = []; $data[0] = __('Instructions'); - $data[1] = events_display_instructions($event['event_type'], $event, true); + $data[1] = html_entity_decode(events_display_instructions($event['event_type'], $event, true)); $table_details->data[] = $data; $data = []; @@ -2920,10 +4189,6 @@ function events_page_details($event, $server='') $details = '
'.html_print_table($table_details, true).'
'; - if (!empty($server) && defined('METACONSOLE')) { - metaconsole_restore_db(); - } - return $details; } @@ -3141,6 +4406,8 @@ function events_page_general($event) $data[1] = $user_owner; } + $table_general->cellclass[3][1] = 'general_owner'; + $table_general->data[] = $data; $data = []; @@ -3208,6 +4475,8 @@ function events_page_general($event) $data[1] = ''.__('N/A').''; } + $table_general->cellclass[7][1] = 'general_status'; + $table_general->data[] = $data; $data = []; @@ -3255,10 +4524,14 @@ function events_page_general($event) $table_general->data[] = $data; $table_data = $table_general->data; - $table_data_total = count($table_data); + if (is_array($table_data)) { + $table_data_total = count($table_data); + } else { + $table_data_total = -1; + } for ($i = 0; $i <= $table_data_total; $i++) { - if (count($table_data[$i]) == 2) { + if (is_array($table_data[$i]) && count($table_data[$i]) == 2) { $table_general->colspan[$i][1] = 2; $table_general->style[2] = 'text-align:center; width:10%;'; } @@ -3273,109 +4546,126 @@ function events_page_general($event) /** * Generate 'comments' page for event viewer. * - * @param array $event Event. - * @param array $childrens_ids Children ids. + * @param array $event Event. * * @return string HTML. */ -function events_page_comments($event, $childrens_ids=[]) +function events_page_comments($event, $ajax=false) { // Comments. global $config; + $comments = ''; + + $comments = $event['user_comment']; + if (isset($event['comments'])) { + $comments = explode('
', $event['comments']); + } + $table_comments = new stdClass; $table_comments->width = '100%'; $table_comments->data = []; $table_comments->head = []; $table_comments->class = 'table_modal_alternate'; - $event_comments = $event['user_comment']; - $event_comments = str_replace(["\n", ' '], '
', $event_comments); + $comments = str_replace(["\n", ' '], '
', $comments); - // If comments are not stored in json, the format is old. - $event_comments_array = json_decode($event_comments, true); + if (is_array($comments)) { + foreach ($comments as $comm) { + if (empty($comm)) { + continue; + } - // Show the comments more recent first. - if (is_array($event_comments_array)) { - $event_comments_array = array_reverse($event_comments_array); - } - - if (empty($event_comments_array)) { - $comments_format = 'old'; + $comments_array[] = json_decode(io_safe_output($comm), true); + } } else { - $comments_format = 'new'; + // If comments are not stored in json, the format is old. + $comments_array = json_decode(io_safe_output($comments), true); } - switch ($comments_format) { - case 'new': - if (empty($event_comments_array)) { - $table_comments->style[0] = 'text-align:center;'; - $table_comments->colspan[0][0] = 2; - $data = []; - $data[0] = __('There are no comments'); - $table_comments->data[] = $data; - } + foreach ($comments_array as $comm) { + // Show the comments more recent first. + if (is_array($comm)) { + $comm = array_reverse($comm); + } - if (isset($event_comments_array) === true - && is_array($event_comments_array) === true - ) { - foreach ($event_comments_array as $c) { - $data[0] = ''.$c['action'].' by '.$c['id_user'].''; - $data[0] .= '

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

[', $row_text); - $row_text = preg_replace('/[\[|\]]/', '', $row_text); - break; - - case 1: - $row_text = preg_replace("/[\r\n|\r|\n]/", '
', io_safe_output(strip_tags($c))); - break; - - default: - // Ignore. - break; - } - - $data[$col] = $row_text; - - $col++; - - if ($col == 2) { - $col = 0; - $table_comments->data[] = $data; + switch ($comments_format) { + case 'new': + if (empty($comm)) { + $table_comments->style[0] = 'text-align:center;'; + $table_comments->colspan[0][0] = 2; $data = []; + $data[0] = __('There are no comments'); + $table_comments->data[] = $data; } - } - if (count($comments_array) == 1 && $comments_array[0] == '') { - $table_comments->style[0] = 'text-align:center;'; - $table_comments->colspan[0][0] = 2; + if (isset($comm) === true + && is_array($comm) === true + ) { + foreach ($comm as $c) { + $data[0] = ''.$c['action'].' by '.$c['id_user'].''; + $data[0] .= '

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

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

'; + $comments_form .= '
'; + $comments_form .= html_print_button( + __('Add comment'), + 'comment_button', + false, + 'event_comment();', + 'class="sub next"', + true + ); + $comments_form .= '

'; } else { $comments_form = ui_print_message( __('If event replication is ongoing, it won\'t be possible to enter comments here. This option is only to allow local pandora users to see comments, but not to operate with them. The operation, when event replication is enabled, must be done only in the Metaconsole.') ); } - $comments = '
'.$comments_form.html_print_table($table_comments, true).'
'; + if ($ajax) { + return $comments_form.html_print_table($table_comments, true); + } - return $comments; + return '
'.$comments_form.html_print_table($table_comments, true).'
'; } @@ -3551,10 +4860,6 @@ function events_get_count_events_by_agent( $tagente = 'tagente'; $tevento = 'tevento'; - if ($dbmeta) { - $tagente = 'tmetaconsole_agent'; - $tevento = 'tmetaconsole_event'; - } $sql = sprintf( 'SELECT id_agente, @@ -3564,7 +4869,7 @@ function events_get_count_events_by_agent( COUNT(*) AS count FROM %s t3 WHERE utimestamp > %d AND utimestamp <= %d - AND id_grupo IN (%s) %s + AND id_grupo IN (%s) GROUP BY id_agente', $tagente, $tevento, @@ -3731,9 +5036,6 @@ function events_get_count_events_validated_by_user( } $tevento = 'tevento'; - if ($dbmeta) { - $tevento = 'tmetaconsole_event'; - } $sql = sprintf( 'SELECT id_usuario, @@ -3909,9 +5211,6 @@ function events_get_count_events_by_criticity( } $tevento = 'tevento'; - if ($dbmeta) { - $tevento = 'tmetaconsole_event'; - } $sql = sprintf( 'SELECT criticity, @@ -4117,9 +5416,6 @@ function events_get_count_events_validated( } $tevento = 'tevento'; - if ($dbmeta) { - $tevento = 'tmetaconsole_event'; - } $sql = sprintf('SELECT estado, COUNT(*) AS count FROM %s WHERE %s %s GROUP BY estado', $tevento, $sql_filter, $sql_where); @@ -4551,7 +5847,7 @@ function events_list_events_grouped_agents($sql) $sql = sprintf( 'SELECT * FROM %s LEFT JOIN tagent_secondary_group - ON tagent_secondary_group.id_agent = tevento.id_agente + ON tagent_secondary_group.id_agent = id_agente WHERE %s', $table, $sql @@ -5248,13 +6544,14 @@ function events_list_events_grouped_agents($sql) /** * Retrieves SQL for custom order. * - * @param string $sort_field Field. - * @param string $sort Order. - * @param integer $group_rep Group field. + * @param string $sort_field Field. + * @param string $sort Order. + * @param integer $group_rep Group field. + * @param boolean $only-fields Return only fields. * * @return string SQL. */ -function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep=0) +function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep=0, $only_fields=false) { $sort_field_translated = $sort_field; switch ($sort_field) { @@ -5303,11 +6600,19 @@ function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep= break; default: - // Ignore. + $sort_field_translated = $sort_field; break; } - $dir = ($sort == 'up') ? 'ASC' : 'DESC'; + if (strtolower($sort) != 'asc' && strtolower($sort) != 'desc') { + $dir = ($sort == 'up') ? 'ASC' : 'DESC'; + } else { + $dir = $sort; + } + + if ($only_fields) { + return $sort_field_translated.' '.$dir; + } return 'ORDER BY '.$sort_field_translated.' '.$dir; } @@ -5322,10 +6627,6 @@ function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep= */ function events_get_secondary_groups_left_join($table) { - if (users_is_admin()) { - return ''; - } - if ($table == 'tevento') { return 'LEFT JOIN tagent_secondary_group tasg ON te.id_agente = tasg.id_agent'; } diff --git a/pandora_console/include/functions_graph.php b/pandora_console/include/functions_graph.php index cde59c52bb..d0e844c3bf 100644 --- a/pandora_console/include/functions_graph.php +++ b/pandora_console/include/functions_graph.php @@ -1277,12 +1277,34 @@ function graphic_combined_module( array_push($modules, $source['id_agent_module']); array_push($weights, $source['weight']); if ($source['label'] != '' || $params_combined['labels']) { - $item['type'] = 'custom_graph'; - $item['id_agent'] = agents_get_module_id( + $id_agent = agents_get_module_id( $source['id_agent_module'] ); - $item['id_agent_module'] = $source['id_agent_module']; - $labels[$source['id_agent_module']] = ($source['label'] != '') ? reporting_label_macro($item, $source['label']) : reporting_label_macro($item, $params_combined['labels']); + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $source['id_agent_module'] + ); + + $module_description = modules_get_agentmodule_descripcion( + $source['id_agent_module'] + ); + + $items_label = [ + 'type' => 'custom_graph', + 'id_agent' => $id_agent, + 'id_agent_module' => $source['id_agent_module'], + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + + $labels[$source['id_agent_module']] = ($source['label'] != '') ? reporting_label_macro($items_label, $source['label']) : reporting_label_macro($item, $params_combined['labels']); } } } @@ -2161,7 +2183,7 @@ function graphic_combined_module( $graph_values = $temp; if (!$params['vconsole']) { - $width = 1024; + $width = $width; $height = 500; } @@ -2286,6 +2308,7 @@ function combined_graph_summatory_average( } $count++; + $count_data_array_reverse--; } if ($summatory && isset($array_sum_reverse) @@ -2343,14 +2366,21 @@ function graphic_agentaccess( $date = get_system_time(); $datelimit = ($date - $period); $data_array = []; + $interval = agents_get_interval($id_agent); $data = db_get_all_rows_sql( - "SELECT count(*) as data, min(utimestamp) as utimestamp - FROM tagent_access - WHERE id_agent = $id_agent - AND utimestamp > $datelimit - AND utimestamp < $date - GROUP by ROUND(utimestamp / 1800)" + sprintf( + 'SELECT utimestamp, count(*) as data + FROM tagent_access + WHERE id_agent = %d + AND utimestamp > %d + AND utimestamp < %d + GROUP BY ROUND(utimestamp/%d)', + $id_agent, + $datelimit, + $date, + $interval + ) ); if (isset($data) && is_array($data)) { @@ -2532,13 +2562,13 @@ function graph_agent_status($id_agent=false, $width=300, $height=200, $return=fa } // $colors = array(COL_CRITICAL, COL_WARNING, COL_NORMAL, COL_UNKNOWN); - $colors[__('Critical')] = COL_CRITICAL; - $colors[__('Warning')] = COL_WARNING; - $colors[__('Normal')] = COL_NORMAL; - $colors[__('Unknown')] = COL_UNKNOWN; + $colors['Critical'] = COL_CRITICAL; + $colors['Warning'] = COL_WARNING; + $colors['Normal'] = COL_NORMAL; + $colors['Unknown'] = COL_UNKNOWN; if ($show_not_init) { - $colors[__('Not init')] = COL_NOTINIT; + $colors['Not init'] = COL_NOTINIT; } if (array_sum($data) == 0) { @@ -3222,7 +3252,7 @@ function graph_events_validated($width=300, $height=200, $extra_filters=[], $met $config['fontpath'], $config['font_size'], 1, - false, + 'bottom', $colors ); } @@ -3523,7 +3553,9 @@ function grafico_eventos_usuario($width, $height) '', $water_mark, $config['fontpath'], - $config['font_size'] + $config['font_size'], + 1, + 'bottom' ); } diff --git a/pandora_console/include/functions_groups.php b/pandora_console/include/functions_groups.php index 8fe37c0e48..a1448e37f2 100644 --- a/pandora_console/include/functions_groups.php +++ b/pandora_console/include/functions_groups.php @@ -298,6 +298,52 @@ function groups_get_childrens_ids($parent, $groups=null) /** + * Return a array of id_group of children of given parent. + * + * @param integer $parent The id_grupo parent to search its children. + * @param array $ignorePropagate Ignore propagate. + */ +function groups_get_children($parent, $ignorePropagate=false) +{ + static $groups; + + if (empty($groups)) { + $groups = db_get_all_rows_in_table('tgrupo'); + $groups = array_reduce( + $groups, + function ($carry, $item) { + $carry[$item['id_grupo']] = $item; + return $carry; + } + ); + } + + $return = []; + foreach ($groups as $key => $g) { + if ($g['id_grupo'] == 0) { + continue; + } + + if ($ignorePropagate || $parent == 0 || $groups[$parent]['propagate']) { + if ($g['parent'] == $parent) { + $return += [$g['id_grupo'] => $g]; + if ($g['propagate'] || $ignorePropagate) { + $return += groups_get_children( + $g['id_grupo'], + $ignorePropagate + ); + } + } + } + } + + return $return; +} + + +/** + * XXX: This is not working. Expects 'propagate' on CHILD not on PARENT!!! + * * Return a array of id_group of childrens (to branches down) * * @param integer $parent The id_group parent to search the childrens. diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 010845caf6..08d60dbb6e 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -77,8 +77,7 @@ function html_debug_print($var, $file='', $oneline=false) fprintf($f, '%s', $output); fclose($f); } else { - echo '
'.date('Y/m/d H:i:s').' ('.gettype($var).') '.$more_info.'
'; - echo '
';
+        echo '
'.date('Y/m/d H:i:s').' ('.gettype($var).') '.$more_info."\n";
         print_r($var);
         echo '
'; } @@ -1233,7 +1232,7 @@ function html_print_extended_select_for_cron($hour='*', $minute='*', $mday='*', * * @return string HTML code if return parameter is true. */ -function html_print_input_text_extended($name, $value, $id, $alt, $size, $maxlength, $disabled, $script, $attributes, $return=false, $password=false, $function='') +function html_print_input_text_extended($name, $value, $id, $alt, $size, $maxlength, $disabled, $script, $attributes, $return=false, $password=false, $function='', $autocomplete='off') { static $idcounter = 0; @@ -1241,7 +1240,9 @@ function html_print_input_text_extended($name, $value, $id, $alt, $size, $maxlen $maxlength = 255; } - if ($size == 0) { + if ($size === false) { + $size = ''; + } else if ($size == 0) { $size = 10; } @@ -1283,7 +1284,7 @@ function html_print_input_text_extended($name, $value, $id, $alt, $size, $maxlen 'autocomplete', ]; - $output = ''.html_print_image('images/sort_up.png', true).''.''.html_print_image('images/sort_down.png', true).''; + $out = ' '; + $out .= html_print_image('images/sort_up_black.png', true); + $out .= ''; + $out .= html_print_image('images/sort_down_black.png', true).''; } @@ -3052,4 +3064,295 @@ function html_print_link_with_params($text, $params=[], $type='text', $style='') $html .= ''; return $html; -} \ No newline at end of file +} + + +/** + * Print input using functions html lib. + * + * @param array $data Input definition. + * @param string $wrapper Wrapper 'div' or 'li'. + * @param boolean $input_only Return or print only input or also label. + * + * @return string HTML code for desired input. + */ +function html_print_input($data, $wrapper='div', $input_only=false) +{ + if (is_array($data) === false) { + return ''; + } + + $output = ''; + + if ($data['label'] && $input_only === false) { + $output = '<'.$wrapper.' id="'.$wrapper.'-'.$data['name'].'" '; + $output .= ' class="'.$data['input_class'].'">'; + $output .= ''; + + if (!$data['return']) { + echo $output; + } + } + + switch ($data['type']) { + case 'text': + $output .= html_print_input_text( + $data['name'], + $data['value'], + ((isset($data['alt']) === true) ? $data['alt'] : ''), + ((isset($data['size']) === true) ? $data['size'] : 50), + ((isset($data['maxlength']) === true) ? $data['maxlength'] : 255), + ((isset($data['return']) === true) ? $data['return'] : true), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['required']) === true) ? $data['required'] : false), + ((isset($data['function']) === true) ? $data['function'] : ''), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['onChange']) === true) ? $data['onChange'] : ''), + ((isset($data['autocomplete']) === true) ? $data['autocomplete'] : '') + ); + break; + + case 'image': + $output .= html_print_input_image( + $data['name'], + $data['src'], + $data['value'], + ((isset($data['style']) === true) ? $data['style'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['options']) === true) ? $data['options'] : false) + ); + break; + + case 'text_extended': + $output .= html_print_input_text_extended( + $data['name'], + $data['value'], + $data['id'], + $data['alt'], + $data['size'], + $data['maxlength'], + $data['disabled'], + $data['script'], + $data['attributes'], + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['password']) === true) ? $data['password'] : false), + ((isset($data['function']) === true) ? $data['function'] : '') + ); + break; + + case 'password': + $output .= html_print_input_password( + $data['name'], + $data['value'], + ((isset($data['alt']) === true) ? $data['alt'] : ''), + ((isset($data['size']) === true) ? $data['size'] : 50), + ((isset($data['maxlength']) === true) ? $data['maxlength'] : 255), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['required']) === true) ? $data['required'] : false), + ((isset($data['class']) === true) ? $data['class'] : '') + ); + break; + + case 'text': + $output .= html_print_input_text( + $data['name'], + $data['value'], + ((isset($data['alt']) === true) ? $data['alt'] : ''), + ((isset($data['size']) === true) ? $data['size'] : 50), + ((isset($data['maxlength']) === true) ? $data['maxlength'] : 255), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['required']) === true) ? $data['required'] : false), + ((isset($data['function']) === true) ? $data['function'] : ''), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['onChange']) === true) ? $data['onChange'] : ''), + ((isset($data['autocomplete']) === true) ? $data['autocomplete'] : '') + ); + break; + + case 'hidden': + $output .= html_print_input_hidden( + $data['name'], + $data['value'], + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['class']) === true) ? $data['class'] : false) + ); + break; + + case 'hidden_extended': + $output .= html_print_input_hidden_extended( + $data['name'], + $data['value'], + $data['id'], + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['class']) === true) ? $data['class'] : false) + ); + break; + + case 'color': + $output .= html_print_input_color( + $data['name'], + $data['value'], + ((isset($data['class']) === true) ? $data['class'] : false), + ((isset($data['return']) === true) ? $data['return'] : false) + ); + break; + + case 'file': + $output .= html_print_input_file( + $data['name'], + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['options']) === true) ? $data['options'] : false) + ); + break; + + case 'select': + $output .= html_print_select( + $data['fields'], + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : 0), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['option_style']) === true) ? $data['option_style'] : false), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['modal']) === true) ? $data['modal'] : false), + ((isset($data['message']) === true) ? $data['message'] : ''), + ((isset($data['select_all']) === true) ? $data['select_all'] : false) + ); + break; + + case 'select_from_sql': + $output .= html_print_select_from_sql( + $data['sql'], + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : '0'), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT) + ); + break; + + case 'select_groups': + $output .= html_print_select_groups( + ((isset($data['id_user']) === true) ? $data['id_user'] : false), + ((isset($data['privilege']) === true) ? $data['privilege'] : 'AR'), + ((isset($data['returnAllGroup']) === true) ? $data['returnAllGroup'] : true), + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : 0), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['option_style']) === true) ? $data['option_style'] : false), + ((isset($data['id_group']) === true) ? $data['id_group'] : false), + ((isset($data['keys_field']) === true) ? $data['keys_field'] : 'id_grupo'), + ((isset($data['strict_user']) === true) ? $data['strict_user'] : false), + ((isset($data['delete_groups']) === true) ? $data['delete_groups'] : false), + ((isset($data['include_groups']) === true) ? $data['include_groups'] : false), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['simple_multiple_options']) === true) ? $data['simple_multiple_options'] : false) + ); + break; + + case 'submit': + $output .= '<'.$wrapper.' class="action-buttons" style="width: 100%">'.html_print_submit_button( + ((isset($data['label']) === true) ? $data['label'] : 'OK'), + ((isset($data['name']) === true) ? $data['name'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['attributes']) === true) ? $data['attributes'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false) + ).''; + break; + + case 'checkbox': + $output .= html_print_checkbox( + $data['name'], + $data['value'], + ((isset($data['checked']) === true) ? $data['checked'] : false), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['disabled_hidden']) === true) ? $data['disabled_hidden'] : false) + ); + break; + + case 'switch': + $output .= html_print_switch($data); + break; + + case 'interval': + $output .= html_print_extended_select_for_time( + $data['name'], + $data['value'], + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : 0), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['style']) === true) ? $data['selected'] : false), + ((isset($data['unique']) === true) ? $data['unique'] : false) + ); + break; + + case 'textarea': + $output .= html_print_textarea( + $data['name'], + $data['rows'], + $data['columns'], + ((isset($data['value']) === true) ? $data['value'] : ''), + ((isset($data['attributes']) === true) ? $data['attributes'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['class']) === true) ? $data['class'] : '') + ); + break; + + case 'button': + $output .= html_print_button( + ((isset($data['label']) === true) ? $data['label'] : 'OK'), + ((isset($data['name']) === true) ? $data['name'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['attributes']) === true) ? $data['attributes'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['imageButton']) === true) ? $data['imageButton'] : false), + ((isset($data['modal']) === true) ? $data['modal'] : false), + ((isset($data['message']) === true) ? $data['message'] : '') + ); + break; + + default: + // Ignore. + break; + } + + if ($data['label'] && $input_only === false) { + $output .= ''; + if (!$data['return']) { + echo ''; + } + } + + return $output; +} diff --git a/pandora_console/include/functions_menu.php b/pandora_console/include/functions_menu.php index 0dbe1049bc..98191d231f 100644 --- a/pandora_console/include/functions_menu.php +++ b/pandora_console/include/functions_menu.php @@ -50,6 +50,15 @@ function menu_print_menu(&$menu) $sec = (string) get_parameter('sec'); $sec2 = (string) get_parameter('sec2'); + if ($sec2 == 'operation/agentes/ver_agente') { + $sec2 = 'godmode/agentes/configurar_agente'; + } else if ($sec2 == 'godmode/servers/discovery') { + $wiz = (string) get_parameter('wiz'); + $sec2 = 'godmode/servers/discovery&wiz='.$wiz; + } else { + $sec2 = (string) get_parameter('sec2'); + } + $menu_selected = false; $allsec2 = explode('sec2=', $_SERVER['REQUEST_URI']); @@ -87,7 +96,7 @@ function menu_print_menu(&$menu) // ~ if (enterprise_hook ('enterprise_acl', array ($config['id_user'], $mainsec)) == false) // ~ continue; if (! isset($main['id'])) { - $id = 'menu_'.++$idcounter; + $id = 'menu_'.(++$idcounter); } else { $id = $main['id']; } @@ -405,9 +414,9 @@ function menu_print_menu(&$menu) $padding_top = ( $length >= 18) ? 6 : 12; if ($config['menu_type'] == 'classic') { - $output .= ''; + $output .= '
'.$main['text'].'
'; } else { - $output .= ''; + $output .= '
'.$main['text'].'
'; } // Add the notification ball if defined diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index 1bc54c9c89..e0212a9478 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -383,7 +383,7 @@ function messages_get_count( } $sql = sprintf( - 'SELECT count(*) as "n" FROM ( + 'SELECT count(distinct id_mensaje) as "n" FROM ( SELECT tm.*, utimestamp_read > 0 as "read" diff --git a/pandora_console/include/functions_modules.php b/pandora_console/include/functions_modules.php index b9ed8e41d5..fbee2a5331 100755 --- a/pandora_console/include/functions_modules.php +++ b/pandora_console/include/functions_modules.php @@ -566,11 +566,11 @@ function modules_update_agent_module( /** * Creates a module in an agent. * - * @param int Agent id. - * @param int Module name id. - * @param array Extra values for the module. - * @param bool Disable the ACL checking, for default false. - * @param mixed Array with tag's ids or false. + * @param integer $id_agent Agent id. + * @param integer $name Module name id. + * @param array $values Extra values for the module. + * @param boolean $disableACL Disable the ACL checking, for default false. + * @param mixed $tags Array with tag's ids or false. * * @return New module id if the module was created. False if not. */ @@ -584,7 +584,9 @@ function modules_create_agent_module( global $config; if (!$disableACL) { - if (!users_is_admin() && (empty($id_agent) || ! users_access_to_agent($id_agent, 'AW'))) { + if (!users_is_admin() && (empty($id_agent) + || !users_access_to_agent($id_agent, 'AW')) + ) { return false; } } @@ -593,7 +595,7 @@ function modules_create_agent_module( return ERR_INCOMPLETE; } - // Check for non valid characters in module name + // Check for non valid characters in module name. if (mb_ereg_match('[\xc2\xa1\xc2\xbf\xc3\xb7\xc2\xba\xc2\xaa]', io_safe_output($name)) !== false) { return ERR_GENERIC; } @@ -605,23 +607,33 @@ function modules_create_agent_module( $values['nombre'] = $name; $values['id_agente'] = (int) $id_agent; - $exists = (bool) db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['nombre' => $name, 'id_agente' => (int) $id_agent]); + $exists = (bool) db_get_value_filter( + 'id_agente_modulo', + 'tagente_modulo', + [ + 'nombre' => $name, + 'id_agente' => (int) $id_agent, + ] + ); if ($exists) { return ERR_EXIST; } - // Encrypt passwords + // Encrypt passwords. if (isset($values['plugin_pass'])) { $values['plugin_pass'] = io_input_password($values['plugin_pass']); } - // Encrypt SNMPv3 passwords - if (isset($values['id_tipo_modulo']) && ($values['id_tipo_modulo'] >= 15 && $values['id_tipo_modulo'] <= 18) + // Encrypt SNMPv3 passwords. + if (isset($values['id_tipo_modulo']) && ($values['id_tipo_modulo'] >= 15 + && $values['id_tipo_modulo'] <= 18) && isset($values['tcp_send']) && ($values['tcp_send'] == 3) && isset($values['custom_string_2']) ) { - $values['custom_string_2'] = io_input_password($values['custom_string_2']); + $values['custom_string_2'] = io_input_password( + $values['custom_string_2'] + ); } $id_agent_module = db_process_sql_insert('tagente_modulo', $values); @@ -645,25 +657,33 @@ function modules_create_agent_module( } if (isset($values['id_tipo_modulo']) - && ($values['id_tipo_modulo'] == 21 || $values['id_tipo_modulo'] == 22 || $values['id_tipo_modulo'] == 23) + && ($values['id_tipo_modulo'] == 21 + || $values['id_tipo_modulo'] == 22 + || $values['id_tipo_modulo'] == 23) ) { - // Async modules start in normal status + // Async modules start in normal status. $status = AGENT_MODULE_STATUS_NORMAL; } else { - // Sync modules start in unknown status + // Sync modules start in unknown status. $status = AGENT_MODULE_STATUS_NO_DATA; } + // Condition for cron modules. Don't touch. + $time = 0; + if (empty($values['interval']) === false) { + $time = (time() - (int) $values['interval']); + } + $result = db_process_sql_insert( 'tagente_estado', [ 'id_agente_modulo' => $id_agent_module, - 'datos' => 0, + 'datos' => '', 'timestamp' => '01-01-1970 00:00:00', 'estado' => $status, 'known_status' => $status, 'id_agente' => (int) $id_agent, - 'utimestamp' => (time() - (int) $values['interval']), + 'utimestamp' => $time, 'status_changes' => 0, 'last_status' => $status, 'last_known_status' => $status, @@ -680,12 +700,20 @@ function modules_create_agent_module( return ERR_DB; } - // Update module status count if the module is not created disabled + // Update module status count if the module is not created disabled. if (!isset($values['disabled']) || $values['disabled'] == 0) { if ($status == 0) { - db_process_sql('UPDATE tagente SET total_count=total_count+1, normal_count=normal_count+1 WHERE id_agente='.(int) $id_agent); + db_process_sql( + 'UPDATE tagente + SET total_count=total_count+1, normal_count=normal_count+1 + WHERE id_agente='.(int) $id_agent + ); } else { - db_process_sql('UPDATE tagente SET total_count=total_count+1, notinit_count=notinit_count+1 WHERE id_agente='.(int) $id_agent); + db_process_sql( + 'UPDATE tagente + SET total_count=total_count+1, notinit_count=notinit_count+1 + WHERE id_agente='.(int) $id_agent + ); } } @@ -2230,6 +2258,7 @@ function modules_get_agentmodule_data( 'module_name' => $values[$key]['module_name'], 'agent_id' => $values[$key]['agent_id'], 'agent_name' => $values[$key]['agent_name'], + 'module_type' => $values[$key]['module_type'], ]; } @@ -2307,32 +2336,67 @@ function modules_get_color_status($status) return COL_UNKNOWN; } - switch ($status) { - case AGENT_MODULE_STATUS_NORMAL: - case AGENT_STATUS_NORMAL: + switch ((string) $status) { + case (string) AGENT_MODULE_STATUS_NORMAL: + case (string) AGENT_STATUS_NORMAL: + case STATUS_MODULE_OK: + case STATUS_AGENT_OK: + case STATUS_ALERT_NOT_FIRED: + case STATUS_SERVER_OK: + case STATUS_MODULE_OK_BALL: + case STATUS_AGENT_OK_BALL: + case STATUS_ALERT_NOT_FIRED_BALL: return COL_NORMAL; case AGENT_MODULE_STATUS_NOT_INIT: case AGENT_STATUS_NOT_INIT: + case STATUS_MODULE_NO_DATA: + case STATUS_AGENT_NOT_INIT: + case STATUS_AGENT_NO_DATA: + case STATUS_MODULE_NO_DATA_BALL: + case STATUS_AGENT_NO_DATA_BALL: + case STATUS_AGENT_NO_MONITORS_BALL: return COL_NOTINIT; case AGENT_MODULE_STATUS_CRITICAL_BAD: case AGENT_STATUS_CRITICAL: + case STATUS_MODULE_CRITICAL: + case STATUS_AGENT_CRITICAL: + case STATUS_MODULE_CRITICAL_BALL: + case STATUS_AGENT_CRITICAL_BALL: return COL_CRITICAL; case AGENT_MODULE_STATUS_WARNING: case AGENT_STATUS_WARNING: + case STATUS_MODULE_WARNING: + case STATUS_AGENT_WARNING: + case STATUS_MODULE_WARNING_BALL: + case STATUS_AGENT_WARNING_BALL: return COL_WARNING; case AGENT_MODULE_STATUS_CRITICAL_ALERT: case AGENT_MODULE_STATUS_WARNING_ALERT: case AGENT_STATUS_ALERT_FIRED: + case STATUS_ALERT_FIRED: + case STATUS_ALERT_FIRED_BALL: return COL_ALERTFIRED; case AGENT_MODULE_STATUS_UNKNOWN: case AGENT_STATUS_UNKNOWN: + case STATUS_MODULE_UNKNOWN: + case STATUS_AGENT_UNKNOWN: + case STATUS_AGENT_DOWN: + case STATUS_ALERT_DISABLED: + case STATUS_MODULE_UNKNOWN_BALL: + case STATUS_AGENT_UNKNOWN_BALL: + case STATUS_AGENT_DOWN_BALL: + case STATUS_ALERT_DISABLED_BALL: return COL_UNKNOWN; + case STATUS_SERVER_DOWN: + case STATUS_SERVER_DOWN_BALL: + return '#444'; + default: // Ignored. break; @@ -2595,7 +2659,7 @@ function modules_get_relations($params=[]) } $sql = 'SELECT DISTINCT tmr.id, tmr.module_a, tmr.module_b, - tmr.disable_update + tmr.disable_update, tmr.type FROM tmodule_relationship tmr, tagente_modulo tam, tagente ta, @@ -2698,11 +2762,13 @@ function modules_relation_exists($id_module, $id_module_other=false) /** * Change the 'disabled_update' value of a relation row. * - * @param int Relation id. + * @param integer $id_module_a Id agent module a. + * @param integer $id_module_b Id agent module b. + * @param string $type Type direct or failover. * * @return boolean True if the 'disabled_update' changes to 1, false otherwise. */ -function modules_add_relation($id_module_a, $id_module_b) +function modules_add_relation($id_module_a, $id_module_b, $type='direct') { $result = false; @@ -2710,6 +2776,7 @@ function modules_add_relation($id_module_a, $id_module_b) $values = [ 'module_a' => $id_module_a, 'module_b' => $id_module_b, + 'type' => $type, ]; $result = db_process_sql_insert('tmodule_relationship', $values); } diff --git a/pandora_console/include/functions_netflow.php b/pandora_console/include/functions_netflow.php index 69aa0a1608..f1febb5c41 100644 --- a/pandora_console/include/functions_netflow.php +++ b/pandora_console/include/functions_netflow.php @@ -35,8 +35,8 @@ define('NETFLOW_RES_LOWD', 6); define('NETFLOW_RES_MEDD', 12); define('NETFLOW_RES_HID', 24); define('NETFLOW_RES_ULTRAD', 30); -define('NETFLOW_RES_HOURLY', 'hourly'); -define('NETFLOW_RES_DAILY', 'daily'); +define('NETFLOW_RES_HOURLY', -1); +define('NETFLOW_RES_DAILY', -2); define('NETFLOW_MAX_DATA_CIRCULAR_MESH', 10000); @@ -473,7 +473,7 @@ function netflow_get_data( // Put all points into an array. $intervals = [($start_date - $multiplier_time)]; - while ((end($intervals) < $end_date) === true) { + while (($next = (end($intervals) + $multiplier_time) < $end_date) === true) { $intervals[] = (end($intervals) + $multiplier_time); } diff --git a/pandora_console/include/functions_networkmap.php b/pandora_console/include/functions_networkmap.php index af11deb541..e4fb19e814 100644 --- a/pandora_console/include/functions_networkmap.php +++ b/pandora_console/include/functions_networkmap.php @@ -450,14 +450,26 @@ function networkmap_generate_dot( $nodes[$node_count] = $module; } } else { - $have_relations_a = db_get_value('id', 'tmodule_relationship', 'module_a', $module['id_agente_modulo']); - $have_relations_b = db_get_value('id', 'tmodule_relationship', 'module_b', $module['id_agente_modulo']); + $sql_a = sprintf( + 'SELECT id + FROM tmodule_relationship + WHERE module_a = %d AND type = "direct"', + $module['id_agente_modulo'] + ); + $sql_b = sprintf( + 'SELECT id + FROM tmodule_relationship + WHERE module_b = %d AND type = "direct"', + $module['id_agente_modulo'] + ); + $have_relations_a = db_get_value_sql($sql_a); + $have_relations_b = db_get_value_sql($sql_b); if ($have_relations_a || $have_relations_b) { - // Save node parent information to define edges later + // Save node parent information to define edges later. $parents[$node_count] = $module['parent'] = $agent['id_node']; - // Add node + // Add node. $nodes[$node_count] = $module; } } @@ -1807,9 +1819,9 @@ function networkmap_links_to_js_links( if (($relation['parent_type'] == NODE_MODULE) && ($relation['child_type'] == NODE_MODULE)) { if (($item['status_start'] == AGENT_MODULE_STATUS_CRITICAL_BAD) || ($item['status_end'] == AGENT_MODULE_STATUS_CRITICAL_BAD)) { - $item['link_color'] = '#FC4444'; + $item['link_color'] = '#e63c52'; } else if (($item['status_start'] == AGENT_MODULE_STATUS_WARNING) || ($item['status_end'] == AGENT_MODULE_STATUS_WARNING)) { - $item['link_color'] = '#FAD403'; + $item['link_color'] = '#f3b200'; } $agent = agents_get_agent_id_by_module_id( @@ -1837,9 +1849,9 @@ function networkmap_links_to_js_links( } } else if ($relation['child_type'] == NODE_MODULE) { if ($item['status_start'] == AGENT_MODULE_STATUS_CRITICAL_BAD) { - $item['link_color'] = '#FC4444'; + $item['link_color'] = '#e63c52'; } else if ($item['status_start'] == AGENT_MODULE_STATUS_WARNING) { - $item['link_color'] = '#FAD403'; + $item['link_color'] = '#f3b200'; } $agent2 = agents_get_agent_id_by_module_id( @@ -1864,9 +1876,9 @@ function networkmap_links_to_js_links( } } else if ($relation['parent_type'] == NODE_MODULE) { if ($item['status_end'] == AGENT_MODULE_STATUS_CRITICAL_BAD) { - $item['link_color'] = '#FC4444'; + $item['link_color'] = '#e63c52'; } else if ($item['status_end'] == AGENT_MODULE_STATUS_WARNING) { - $item['link_color'] = '#FAD403'; + $item['link_color'] = '#f3b200'; } $agent = agents_get_agent_id_by_module_id( diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index fba9d87a02..4abf5152c1 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -1,20 +1,30 @@ $content['id_agent_module'], + ] + ); + + $items_label['module_name'] = $modules[$content['id_agent_module']]['nombre']; + $items_label['module_description'] = $modules[$content['id_agent_module']]['descripcion']; + + if (is_array($content['id_agent']) + && count($content['id_agent']) != 1 + ) { + $content['style']['name_label'] = str_replace( + '_agent_', + count($content['id_agent']).__(' agents'), + $content['style']['name_label'] + ); } - if (is_array($content['id_agent_module']) && count($content['id_agent_module']) != 1) { - $content['style']['name_label'] = str_replace('_module_', count($content['id_agent_module']).__(' modules'), $content['style']['name_label']); + if (is_array($content['id_agent_module']) + && count($content['id_agent_module']) != 1 + ) { + $content['style']['name_label'] = str_replace( + '_module_', + count($content['id_agent_module']).__(' modules'), + $content['style']['name_label'] + ); } - $content['name'] = reporting_label_macro($items_label, $content['style']['name_label']); - if ($metaconsole_on) { // Restore db connection. metaconsole_restore_db(); } + + $content['name'] = reporting_label_macro( + $items_label, + $content['style']['name_label'] + ); } switch (reporting_get_type($content)) { @@ -326,26 +387,32 @@ function reporting_make_reporting_data( break; case 'general': - $report['contents'][] = reporting_general( - $report, - $content + $report['contents'][] = io_safe_output( + reporting_general( + $report, + $content + ) ); break; case 'availability': - $report['contents'][] = reporting_availability( - $report, - $content, - $date, - $time + $report['contents'][] = io_safe_output( + reporting_availability( + $report, + $content, + $date, + $time + ) ); break; case 'availability_graph': - $report['contents'][] = reporting_availability_graph( - $report, - $content, - $pdf + $report['contents'][] = io_safe_output( + reporting_availability_graph( + $report, + $content, + $pdf + ) ); break; @@ -475,9 +542,11 @@ function reporting_make_reporting_data( break; case 'agent_configuration': - $report['contents'][] = reporting_agent_configuration( - $report, - $content + $report['contents'][] = io_safe_output( + reporting_agent_configuration( + $report, + $content + ) ); break; @@ -673,12 +742,14 @@ function reporting_make_reporting_data( case 'agent_detailed_event': case 'event_report_agent': - $report_control = reporting_event_report_agent( - $report, - $content, - $type, - $force_width_chart, - $force_height_chart + $report_control = io_safe_output( + reporting_event_report_agent( + $report, + $content, + $type, + $force_width_chart, + $force_height_chart + ) ); if ($report_control['total_events'] == 0 && $content['hide_no_data'] == 1) { continue; @@ -1347,8 +1418,8 @@ function reporting_event_top_n( // Get all the related data. $sql = sprintf( 'SELECT id_agent_module, server_name - FROM treport_content_item - WHERE id_report_content = %d', + FROM treport_content_item + WHERE id_report_content = %d', $content['id_rc'] ); @@ -1383,7 +1454,7 @@ function reporting_event_top_n( foreach ($tops as $key => $row) { // Metaconsole connection. $server_name = $row['server_name']; - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); @@ -1426,7 +1497,7 @@ function reporting_event_top_n( } // Restore dbconnection. - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } } @@ -1883,6 +1954,18 @@ function reporting_event_report_group( } +/** + * Events for module reports. + * + * @param array $report Report info. + * @param array $content Content info. + * @param string $type Type retun report. + * @param integer $force_width_chart Width chart. + * @param integer $force_height_chart Height chart. + * @param integer $pdf If pdf report. + * + * @return array + */ function reporting_event_report_module( $report, $content, @@ -1911,12 +1994,42 @@ function reporting_event_report_module( metaconsole_connect(null, $id_server); } - $return['title'] = $content['name']; - $return['subtitle'] = agents_get_alias($content['id_agent']).' - '.io_safe_output(modules_get_agentmodule_name($content['id_agent_module'])); + $id_agent = agents_get_module_id( + $content['id_agent_module'] + ); + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module + ); + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + $items_label = [ + 'type' => $content['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + + $return['title'] = $content['name']; + $return['subtitle'] = $agent_alias.' - '.io_safe_output($module_name); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; + if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } if (is_metaconsole()) { @@ -1930,15 +2043,24 @@ function reporting_event_report_module( $event_filter = $content['style']; $return['show_summary_group'] = $event_filter['show_summary_group']; // Filter. - $show_summary_group = $event_filter['show_summary_group']; - $filter_event_severity = json_decode($event_filter['filter_event_severity'], true); - $filter_event_type = json_decode($event_filter['filter_event_type'], true); - $filter_event_status = json_decode($event_filter['filter_event_status'], true); + $show_summary_group = $event_filter['show_summary_group']; + $filter_event_severity = json_decode( + $event_filter['filter_event_severity'], + true + ); + $filter_event_type = json_decode( + $event_filter['filter_event_type'], + true + ); + $filter_event_status = json_decode( + $event_filter['filter_event_status'], + true + ); $filter_event_filter_search = $event_filter['event_filter_search']; // Graphs. - $event_graph_by_user_validator = $event_filter['event_graph_by_user_validator']; - $event_graph_by_criticity = $event_filter['event_graph_by_criticity']; + $event_graph_by_user_validator = $event_filter['event_graph_by_user_validator']; + $event_graph_by_criticity = $event_filter['event_graph_by_criticity']; $event_graph_validated_vs_unvalidated = $event_filter['event_graph_validated_vs_unvalidated']; $server_name = $content['server_name']; @@ -2176,7 +2298,7 @@ function reporting_agent_module($report, $content) foreach ($agents as $agent) { $row = []; $row['agent_status'][$agent] = agents_get_status($agent); - $row['agent_name'] = agents_get_alias($agent); + $row['agent_name'] = io_safe_output(agents_get_alias($agent)); $agent_modules = agents_get_modules($agent); $row['modules'] = []; @@ -2311,9 +2433,9 @@ function reporting_exception( // Get all the related data. $sql = sprintf( ' - SELECT id_agent_module, server_name, operation - FROM treport_content_item - WHERE id_report_content = %d', + SELECT id_agent_module, server_name, operation + FROM treport_content_item + WHERE id_report_content = %d', $content['id_rc'] ); @@ -2330,7 +2452,7 @@ function reporting_exception( do { // Metaconsole connection. $server_name = $exceptions[$i]['server_name']; - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); @@ -2372,7 +2494,7 @@ function reporting_exception( $i++; // Restore dbconnection. - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } } while ($min === false && $i < count($exceptions)); @@ -2385,7 +2507,7 @@ function reporting_exception( foreach ($exceptions as $exc) { // Metaconsole connection. $server_name = $exc['server_name']; - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); @@ -2499,7 +2621,7 @@ function reporting_exception( } // Restore dbconnection - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } } @@ -2693,7 +2815,7 @@ function reporting_group_report($report, $content) { global $config; - $metaconsole_on = ($config['metaconsole'] == 1) && defined('METACONSOLE'); + $metaconsole_on = ($config['metaconsole'] == 1) && is_metaconsole(); $return['type'] = 'group_report'; @@ -2776,8 +2898,42 @@ function reporting_event_report_agent( $history = true; } + $id_server = false; + if (is_metaconsole()) { + $id_server = metaconsole_get_id_server($content['server_name']); + metaconsole_connect(null, $id_server); + } + + $id_agent = $content['id_agent']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + ]; + + if ($config['metaconsole']) { + metaconsole_restore_db(); + } + + $label = (isset($content['style']['label'])) ? $content['style']['label'] : ''; + if ($label != '') { + $label = reporting_label_macro( + $items_label, + $label + ); + } + + $return['label'] = $label; $return['title'] = $content['name']; - $return['subtitle'] = agents_get_alias($content['id_agent']); + $return['subtitle'] = io_safe_output($agent_alias); $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); @@ -2840,13 +2996,6 @@ function reporting_event_report_agent( $metaconsole_dbtable = false; } - $label = (isset($content['style']['label'])) ? $content['style']['label'] : ''; - if ($label != '') { - $label = reporting_label_macro($content, $label); - } - - $return['label'] = $label; - if ($event_graph_by_user_validator) { $data_graph = events_get_count_events_validated_by_user( ['id_agent' => $content['id_agent']], @@ -2926,10 +3075,6 @@ function reporting_event_report_agent( ); } - if ($config['metaconsole']) { - metaconsole_restore_db(); - } - // Total events. if ($return['data'] != '') { $return['total_events'] = count($return['data']); @@ -2941,32 +3086,65 @@ function reporting_event_report_agent( } +/** + * Show historical data. + * + * @param array $report Data report. + * @param array $content Content report. + * + * @return array + */ function reporting_historical_data($report, $content) { global $config; $return['type'] = 'historical_data'; $period = $content['period']; - $date_limit = (time() - $period); + $date_limit = ($report['datetime'] - $period); if (empty($content['name'])) { $content['name'] = __('Historical data'); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) + $id_agent = agents_get_module_id( + $content['id_agent_module'] ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_alias($content['id_agent_module']) + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = io_safe_output(agents_get_alias($id_agent)); + $module_name = io_safe_output( + modules_get_agentmodule_name( + $id_agent_module + ) + ); + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module ); + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + $return['title'] = $content['name']; - $return['subtitle'] = $agent_name.' - '.$module_name; + $return['subtitle'] = $agent_alias.' - '.$module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } $return['keys'] = [ @@ -2991,7 +3169,7 @@ function reporting_historical_data($report, $content) FROM tagente_datos_string WHERE id_agente_modulo ='.$content['id_agent_module'].' AND utimestamp >'.$date_limit.' - AND utimestamp <='.time(), + AND utimestamp <='.$report['datetime'], true ); break; @@ -3002,7 +3180,7 @@ function reporting_historical_data($report, $content) FROM tagente_datos WHERE id_agente_modulo ='.$content['id_agent_module'].' AND utimestamp >'.$date_limit.' - AND utimestamp <='.time(), + AND utimestamp <='.$report['datetime'], true ); break; @@ -3022,6 +3200,14 @@ function reporting_historical_data($report, $content) } +/** + * Show data serialized. + * + * @param array $report Data report. + * @param array $content Content report. + * + * @return array + */ function reporting_database_serialized($report, $content) { global $config; @@ -3032,15 +3218,43 @@ function reporting_database_serialized($report, $content) $content['name'] = __('Database Serialized'); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) - ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_alias($content['id_agent_module']) + if (is_metaconsole()) { + $id_meta = metaconsole_get_id_server($content['server_name']); + $server = metaconsole_get_connection_by_id($id_meta); + metaconsole_connect($server); + } + + $id_agent = agents_get_module_id( + $content['id_agent_module'] ); + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module + ); + + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + $return['title'] = $content['name']; - $return['subtitle'] = $agent_name.' - '.$module_name; + $return['subtitle'] = $agent_alias.' - '.$module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); @@ -3050,51 +3264,39 @@ function reporting_database_serialized($report, $content) } $return['keys'] = $keys; - - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) - ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_name($content['id_agent_module']) - ); - - $return['agent_name'] = $agent_name; + $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; - if ($config['metaconsole']) { - $id_meta = metaconsole_get_id_server($content['server_name']); - - $server = metaconsole_get_connection_by_id($id_meta); - metaconsole_connect($server); - } - $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } $datelimit = ($report['datetime'] - $content['period']); $search_in_history_db = db_search_in_history_db($datelimit); - // This query gets information from the default and the historic database + // This query gets information from the default and the historic database. $result = db_get_all_rows_sql( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = '.$content['id_agent_module'].' - AND utimestamp > '.$datelimit.' - AND utimestamp <= '.$report['datetime'], + FROM tagente_datos + WHERE id_agente_modulo = '.$content['id_agent_module'].' + AND utimestamp > '.$datelimit.' + AND utimestamp <= '.$report['datetime'], $search_in_history_db ); - // Adds string data if there is no numeric data - if ((count($result) < 0) or (!$result)) { - // This query gets information from the default and the historic database + // Adds string data if there is no numeric data. + if ((count($result) < 0) || (!$result)) { + // This query gets information from the default and the historic database. $result = db_get_all_rows_sql( 'SELECT * - FROM tagente_datos_string - WHERE id_agente_modulo = '.$content['id_agent_module'].' - AND utimestamp > '.$datelimit.' - AND utimestamp <= '.$report['datetime'], + FROM tagente_datos_string + WHERE id_agente_modulo = '.$content['id_agent_module'].' + AND utimestamp > '.$datelimit.' + AND utimestamp <= '.$report['datetime'], $search_in_history_db ); } @@ -3108,13 +3310,16 @@ function reporting_database_serialized($report, $content) $date = date($config['date_format'], $row['utimestamp']); $serialized_data = $row['datos']; - // Cut line by line + // Cut line by line. if (empty($content['line_separator']) || empty($serialized_data) ) { $rowsUnserialize = [$row['datos']]; } else { - $rowsUnserialize = explode($content['line_separator'], $serialized_data); + $rowsUnserialize = explode( + $content['line_separator'], + $serialized_data + ); } foreach ($rowsUnserialize as $rowUnser) { @@ -3130,7 +3335,10 @@ function reporting_database_serialized($report, $content) $row['data'][][$keys[0]] = $rowUnser; } } else { - $columnsUnserialize = explode($content['column_separator'], $rowUnser); + $columnsUnserialize = explode( + $content['column_separator'], + $rowUnser + ); $i = 0; $temp_row = []; @@ -3199,9 +3407,9 @@ function reporting_group_configuration($report, $content) } } else { $sql = ' - SELECT * - FROM tagente - WHERE id_grupo='.$content['id_group']; + SELECT * + FROM tagente + WHERE id_grupo='.$content['id_group']; } $agents_list = db_get_all_rows_sql($sql); @@ -3460,25 +3668,25 @@ function reporting_alert_report_group($report, $content) if ($content['id_group'] == 0) { $agent_modules = db_get_all_rows_sql( ' - SELECT distinct(id_agent_module) - FROM talert_template_modules - WHERE disabled = 0 - AND id_agent_module IN ( - SELECT id_agente_modulo - FROM tagente_modulo)' + SELECT distinct(id_agent_module) + FROM talert_template_modules + WHERE disabled = 0 + AND id_agent_module IN ( + SELECT id_agente_modulo + FROM tagente_modulo)' ); } else { $agent_modules = db_get_all_rows_sql( ' - SELECT distinct(id_agent_module) - FROM talert_template_modules - WHERE disabled = 0 - AND id_agent_module IN ( - SELECT id_agente_modulo - FROM tagente_modulo - WHERE id_agente IN ( - SELECT id_agente - FROM tagente WHERE id_grupo = '.$content['id_group'].'))' + SELECT distinct(id_agent_module) + FROM talert_template_modules + WHERE disabled = 0 + AND id_agent_module IN ( + SELECT id_agente_modulo + FROM tagente_modulo + WHERE id_agente IN ( + SELECT id_agente + FROM tagente WHERE id_grupo = '.$content['id_group'].'))' ); } @@ -3596,6 +3804,14 @@ function reporting_alert_report_group($report, $content) } +/** + * Report alert agent. + * + * @param array $report Info report. + * @param array $content Content report. + * + * @return array + */ function reporting_alert_report_agent($report, $content) { global $config; @@ -3613,16 +3829,33 @@ function reporting_alert_report_agent($report, $content) metaconsole_connect($server); } - $agent_name = agents_get_alias($content['id_agent']); + $id_agent = $content['id_agent']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + ]; $return['title'] = $content['name']; - $return['subtitle'] = $agent_name; + $return['subtitle'] = $agent_alias; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } $module_list = agents_get_modules($content['id_agent']); @@ -3630,10 +3863,10 @@ function reporting_alert_report_agent($report, $content) $data = []; foreach ($module_list as $id => $module_name) { $data_row = []; - $data_row['agent'] = $agent_name; + $data_row['agent'] = $agent_alias; $data_row['module'] = $module_name; - // Alerts over $id_agent_module + // Alerts over $id_agent_module. $alerts = alerts_get_effective_alert_actions($id); if ($alerts === false) { @@ -3727,6 +3960,14 @@ function reporting_alert_report_agent($report, $content) } +/** + * Alert report module. + * + * @param array $report Info report. + * @param array $content Content report. + * + * @return array + */ function reporting_alert_report_module($report, $content) { global $config; @@ -3744,36 +3985,56 @@ function reporting_alert_report_module($report, $content) metaconsole_connect($server); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) + $id_agent = agents_get_module_id( + $content['id_agent_module'] ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_alias($content['id_agent_module']) + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module ); + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + $return['title'] = $content['name']; - $return['subtitle'] = $agent_name.' - '.$module_name; + $return['subtitle'] = $agent_alias.' - '.$module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } $data_row = []; - $data_row['agent'] = io_safe_output( - agents_get_alias( - agents_get_agent_id_by_module_id($content['id_agent_module']) - ) - ); + $data_row['agent'] = io_safe_output($agent_alias); $data_row['module'] = db_get_value_filter( 'nombre', 'tagente_modulo', ['id_agente_modulo' => $content['id_agent_module']] ); - // Alerts over $id_agent_module + // Alerts over $id_agent_module. $alerts = alerts_get_effective_alert_actions($content['id_agent_module']); $ntemplates = 0; @@ -3902,7 +4163,7 @@ function reporting_sql_graph( } } - // Get chart + // Get chart. reporting_set_conf_charts($width, $height, $only_image, $type, $content, $ttl); if (!empty($force_width_chart)) { @@ -3940,6 +4201,14 @@ function reporting_sql_graph( } +/** + * Monitor report module. + * + * @param array $report Info report. + * @param array $content Content report. + * + * @return array + */ function reporting_monitor_report($report, $content) { global $config; @@ -3950,48 +4219,67 @@ function reporting_monitor_report($report, $content) $content['name'] = __('Monitor Report'); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) - ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_alias($content['id_agent_module']) - ); - - $return['title'] = $content['name']; - $return['subtitle'] = $agent_name.' - '.$module_name; - $return['description'] = $content['description']; - $return['date'] = reporting_get_date_text($report, $content); - - if ($config['metaconsole']) { + if (is_metaconsole()) { $id_meta = metaconsole_get_id_server($content['server_name']); $server = metaconsole_get_connection_by_id($id_meta); metaconsole_connect($server); } + $id_agent = agents_get_module_id( + $content['id_agent_module'] + ); + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module + ); + + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + + $return['title'] = $content['name']; + $return['subtitle'] = $agent_alias.' - '.$module_name; + $return['description'] = $content['description']; + $return['date'] = reporting_get_date_text($report, $content); + $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; if ($return['label'] != '') { - $return['label'] = reporting_label_macro($content, $return['label']); + $return['label'] = reporting_label_macro( + $items_label, + $return['label'] + ); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) - ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_name($content['id_agent_module']) - ); - - $return['agent_name'] = $agent_name; + $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; - // All values (except id module and report time) by default + // All values (except id module and report time) by default. $report = reporting_advanced_sla( $content['id_agent_module'], ($report['datetime'] - $content['period']), $report['datetime'] ); - if ($report['time_total'] === $report['time_unknown'] || empty($content['id_agent_module'])) { + if ($report['time_total'] === $report['time_unknown'] + || empty($content['id_agent_module']) + ) { $return['data']['unknown'] = 1; } else { $return['data']['ok']['value'] = $report['SLA']; @@ -4097,8 +4385,8 @@ function reporting_netflow( // Get item filters. $filter = db_get_row_sql( "SELECT * - FROM tnetflow_filter - WHERE id_sg = '".(int) $content['text']."'", + FROM tnetflow_filter + WHERE id_sg = '".(int) $content['text']."'", false, true ); @@ -4282,9 +4570,9 @@ function reporting_agent_configuration($report, $content) } $sql = ' - SELECT * - FROM tagente - WHERE id_agente='.$content['id_agent']; + SELECT * + FROM tagente + WHERE id_agente='.$content['id_agent']; $agent_data = db_get_row_sql($sql); $agent_configuration = []; @@ -4304,9 +4592,9 @@ function reporting_agent_configuration($report, $content) if (!empty($modules)) { foreach ($modules as $id_agent_module => $module) { $sql = " - SELECT * - FROM tagente_modulo - WHERE id_agente_modulo = $id_agent_module"; + SELECT * + FROM tagente_modulo + WHERE id_agente_modulo = $id_agent_module"; $module_db = db_get_row_sql($sql); $data_module = []; @@ -4352,12 +4640,12 @@ function reporting_agent_configuration($report, $content) $data_module['status_icon'] = ui_print_status_image($status, $title, true); $data_module['status'] = $title; $sql_tag = " - SELECT name - FROM ttag - WHERE id_tag IN ( - SELECT id_tag - FROM ttag_module - WHERE id_agente_modulo = $id_agent_module)"; + SELECT name + FROM ttag + WHERE id_tag IN ( + SELECT id_tag + FROM ttag_module + WHERE id_agente_modulo = $id_agent_module)"; $tags = db_get_all_rows_sql($sql_tag); if ($tags === false) { $data_module['tags'] = []; @@ -4525,41 +4813,41 @@ function reporting_value($report, $content, $type, $pdf=false) } } else { $value = ' - - - - - + + - - + + - - - + + + '; echo ""; echo '
'; + + + - - + + - - - + + + + +
'; if ($content['visual_format'] == 1 || $content['visual_format'] == 2 || $content['visual_format'] == 3) { $value .= ' - - - - - - - - - - -
- '.__('Agent').' - - '.__('Module').' - - '.__('Maximum').' -
- '.$agent_name.' - - '.$module_name.' - - '.format_for_graph(reporting_get_agentmodule_data_max($content['id_agent_module'], $content['period'], $report['datetime']), $config['graph_precision']).' '.$unit.' -
'; + + + + + + + + + + +
+ '.__('Agent').' + + '.__('Module').' + + '.__('Maximum').' +
+ '.$agent_name.' + + '.$module_name.' + + '.format_for_graph(reporting_get_agentmodule_data_max($content['id_agent_module'], $content['period'], $report['datetime']), $config['graph_precision']).' '.$unit.' +
'; } $value .= ' -
- '; + + '; if ($content['visual_format'] == 2 || $content['visual_format'] == 3) { $params['force_interval'] = 'max_only'; @@ -4568,23 +4856,23 @@ function reporting_value($report, $content, $type, $pdf=false) $value .= ' -
'; +
'; if ($content['visual_format'] == 1 || $content['visual_format'] == 3) { $value .= ' - - - - - - '; +
- '.__('Lapse').' - - '.__('Maximum').' -
+ + + + + '; $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module'], true); $date_reference = getdate(); @@ -4658,16 +4946,16 @@ function reporting_value($report, $content, $type, $pdf=false) - -
+ '.__('Lapse').' + + '.__('Maximum').' +
'.format_for_graph(reporting_get_agentmodule_data_min($content['id_agent_module'], $content['period'], $report['datetime']), $config['graph_precision']).' '.$unit.' -
'; +
'; } $value .= ' -
- '; + + '; if ($content['visual_format'] == 2 || $content['visual_format'] == 3) { $params['force_interval'] = 'min_only'; @@ -4682,16 +4970,16 @@ function reporting_value($report, $content, $type, $pdf=false) if ($content['visual_format'] == 1 || $content['visual_format'] == 3) { $value .= ' - - - - - - '; +
- '.__('Lapse').' - - '.__('Minimum').' -
+ + + + + '; $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module']); $date_reference = getdate(); @@ -4716,7 +5004,7 @@ function reporting_value($report, $content, $type, $pdf=false) } $value .= ' - +
+ '.__('Lapse').' + + '.__('Minimum').' +
'; @@ -4745,60 +5033,60 @@ function reporting_value($report, $content, $type, $pdf=false) if ($content['visual_format'] == 1 || $content['visual_format'] == 2 || $content['visual_format'] == 3) { $value .= ' - - - - - - - - - - -
- '.__('Agent').' - - '.__('Module').' - - '.__('Average').' -
- '.$agent_name.' - - '.$module_name.' - - '.format_for_graph(reporting_get_agentmodule_data_average($content['id_agent_module'], $content['period'], $report['datetime']), $config['graph_precision']).' '.$unit.' -
'; + + + + + + + + + + +
+ '.__('Agent').' + + '.__('Module').' + + '.__('Average').' +
+ '.$agent_name.' + + '.$module_name.' + + '.format_for_graph(reporting_get_agentmodule_data_average($content['id_agent_module'], $content['period'], $report['datetime']), $config['graph_precision']).' '.$unit.' +
'; } $value .= ' -
- '; + + '; if ($content['visual_format'] == 2 || $content['visual_format'] == 3) { $params['force_interval'] = 'avg_only'; $value .= grafico_modulo_sparse($params); } $value .= ' - -
'; + +
'; if ($content['visual_format'] == 1 || $content['visual_format'] == 3) { $value .= ' - - - - - - '; +
- '.__('Lapse').' - - '.__('Average').' -
+ + + + + '; $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module']); $date_reference = getdate(); @@ -4823,7 +5111,7 @@ function reporting_value($report, $content, $type, $pdf=false) } $value .= ' - +
+ '.__('Lapse').' + + '.__('Average').' +
'; @@ -5021,6 +5309,9 @@ function reporting_sql($report, $content) $sql = io_safe_output($content['external_source']); } + // Check if exist sql macro + $sql = reporting_sql_macro($report, $sql); + // Do a security check on SQL coming from the user. $sql = check_sql($sql); @@ -6073,7 +6364,7 @@ function reporting_advanced_sla( // SLA. $return['SLA'] = reporting_sla_get_compliance_from_array($return); - $return['SLA_fixed'] = sla_truncate( + $return['sla_fixed'] = sla_truncate( $return['SLA'], $config['graph_precision'] ); @@ -6134,10 +6425,10 @@ function reporting_availability($report, $content, $date=false, $time=false) if (empty($content['subitems'])) { $sql = sprintf( ' - SELECT id_agent_module, - server_name, operation - FROM treport_content_item - WHERE id_report_content = %d', + SELECT id_agent_module, + server_name, operation + FROM treport_content_item + WHERE id_report_content = %d', $content['id_rc'] ); @@ -6173,7 +6464,7 @@ function reporting_availability($report, $content, $date=false, $time=false) foreach ($items as $item) { // aaMetaconsole connection $server_name = $item['server_name']; - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); @@ -6185,7 +6476,7 @@ function reporting_availability($report, $content, $date=false, $time=false) || modules_is_not_init($item['id_agent_module']) ) { // Restore dbconnection - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } @@ -6242,7 +6533,7 @@ function reporting_availability($report, $content, $date=false, $time=false) $text = $row['data']['agent'].' ('.$text.')'; // Restore dbconnection - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } @@ -6358,11 +6649,15 @@ function reporting_availability($report, $content, $date=false, $time=false) } -/** - * reporting_availability_graph - * - * Generates a structure the report. - */ + /** + * Reporting_availability_graph. + * + * @param array $report Info report. + * @param array $content Content data. + * @param boolean $pdf Output type PDF. + * + * @return array Generates a structure the report. + */ function reporting_availability_graph($report, $content, $pdf=false) { global $config; @@ -6379,9 +6674,10 @@ function reporting_availability_graph($report, $content, $pdf=false) $return['title'] = $content['name']; $return['description'] = $content['description']; + $return['failover_type'] = $content['failover_type']; $return['date'] = reporting_get_date_text($report, $content); - // Get chart + // Get chart. reporting_set_conf_charts( $width, $height, @@ -6396,10 +6692,12 @@ function reporting_availability_graph($report, $content, $pdf=false) $edge_interval = 10; if (empty($content['subitems'])) { - $slas = db_get_all_rows_field_filter( - 'treport_content_sla_combined', - 'id_report_content', - $content['id_rc'] + $slas = io_safe_output( + db_get_all_rows_field_filter( + 'treport_content_sla_combined', + 'id_report_content', + $content['id_rc'] + ) ); } else { $slas = $content['subitems']; @@ -6423,83 +6721,8 @@ function reporting_availability_graph($report, $content, $pdf=false) foreach ($slas as $sla) { $server_name = $sla['server_name']; - // Metaconsole connection - if ($metaconsole_on && $server_name != '') { - $connection = metaconsole_get_connection($server_name); - if (!metaconsole_load_external_db($connection)) { - // ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - if (modules_is_disable_agent($sla['id_agent_module']) - || modules_is_not_init($sla['id_agent_module']) - ) { - if ($metaconsole_on) { - // Restore db connection - metaconsole_restore_db(); - } - - continue; - } - - // controller min and max == 0 then dinamic min and max critical - $dinamic_text = 0; - if ($sla['sla_min'] == 0 && $sla['sla_max'] == 0) { - $sla['sla_min'] = null; - $sla['sla_max'] = null; - $dinamic_text = __('Dynamic'); - } - - // controller inverse interval - $inverse_interval = 0; - if ((isset($sla['sla_max'])) && (isset($sla['sla_min']))) { - if ($sla['sla_max'] < $sla['sla_min']) { - $content_sla_max = $sla['sla_max']; - $sla['sla_max'] = $sla['sla_min']; - $sla['sla_min'] = $content_sla_max; - $inverse_interval = 1; - $dinamic_text = __('Inverse'); - } - } - - // for graph slice for module-interval, if not slice=0; - $module_interval = modules_get_interval($sla['id_agent_module']); - $slice = ($content['period'] / $module_interval); - - // call functions sla - $sla_array = []; - $sla_array = reporting_advanced_sla( - $sla['id_agent_module'], - ($report['datetime'] - $content['period']), - $report['datetime'], - $sla['sla_min'], - // min_value -> dynamic - $sla['sla_max'], - // max_value -> dynamic - $inverse_interval, - // inverse_interval -> dynamic - [ - '1' => $content['sunday'], - '2' => $content['monday'], - '3' => $content['tuesday'], - '4' => $content['wednesday'], - '5' => $content['thursday'], - '6' => $content['friday'], - '7' => $content['saturday'], - ], - $content['time_from'], - $content['time_to'], - $slice - ); - - if ($metaconsole_on) { - // Restore db connection - metaconsole_restore_db(); - } - - $server_name = $sla['server_name']; - // Metaconsole connection + // Metaconsole connection. if ($metaconsole_on && $server_name != '') { $connection = metaconsole_get_connection($server_name); if (metaconsole_connect($connection) != NOERR) { @@ -6507,199 +6730,149 @@ function reporting_availability_graph($report, $content, $pdf=false) } } - $planned_downtimes = reporting_get_planned_downtimes_intervals($sla['id_agent_module'], ($report['datetime'] - $content['period']), $report['datetime']); - - if ((is_array($planned_downtimes)) && (count($planned_downtimes) > 0)) { - // Sort retrieved planned downtimes - usort( - $planned_downtimes, - function ($a, $b) { - $a = intval($a['date_from']); - $b = intval($b['date_from']); - if ($a == $b) { - return 0; + if ($content['failover_mode']) { + $sla_failover = []; + $sla_failover['primary'] = $sla; + if (isset($sla['id_agent_module_failover']) === true + && $sla['id_agent_module_failover'] != 0 + ) { + $sla_failover['failover'] = $sla; + $sla_failover['failover']['id_agent_module'] = $sla['id_agent_module_failover']; + } else { + $sql_relations = sprintf( + 'SELECT module_b + FROM tmodule_relationship + WHERE module_a = %d + AND type = "failover"', + $sla['id_agent_module'] + ); + $relations = db_get_all_rows_sql($sql_relations); + if (isset($relations) === true + && is_array($relations) === true + ) { + foreach ($relations as $key => $value) { + $sla_failover['failover_'.$key] = $sla; + $sla_failover['failover_'.$key]['id_agent_module'] = $value['module_b']; } - - return ($a < $b) ? -1 : 1; } + } + + // For graph slice for module-interval, if not slice=0. + $module_interval = modules_get_interval($sla['id_agent_module']); + $slice = ($content['period'] / $module_interval); + $data_combined = []; + + foreach ($sla_failover as $k_sla => $v_sla) { + $sla_array = data_db_uncompress_module( + $v_sla, + $content, + $report['datetime'], + $slice + ); + + if ($content['failover_type'] == REPORT_FAILOVER_TYPE_NORMAL) { + $return = prepare_data_for_paint( + $v_sla, + $sla_array, + $content, + $report['datetime'], + $return, + $k_sla, + $pdf + ); + } + + $data_combined[] = $sla_array; + } + + if (isset($data_combined) === true + && is_array($data_combined) === true + && count($data_combined) > 0 + ) { + $count_failover = count($data_combined); + + $data_a = $data_combined[0]; + for ($i = 1; $count_failover > $i; $i++) { + $data_a = array_map( + function ($primary, $failover) { + $return_map = []; + if ($primary['date_from'] === $failover['date_from'] + && $primary['date_to'] === $failover['date_to'] + ) { + if ($primary['time_ok'] < $failover['time_ok']) { + $primary['time_total'] = $failover['time_total']; + $primary['time_ok'] = $failover['time_ok']; + $primary['time_error'] = $failover['time_error']; + $primary['time_unknown'] = $failover['time_unknown']; + $primary['time_not_init'] = $failover['time_not_init']; + $primary['time_downtime'] = $failover['time_downtime']; + $primary['time_out'] = $failover['time_out']; + $primary['checks_total'] = $failover['checks_total']; + $primary['checks_ok'] = $failover['checks_ok']; + $primary['checks_error'] = $failover['checks_error']; + $primary['checks_unknown'] = $failover['checks_unknown']; + $primary['checks_not_init'] = $failover['checks_not_init']; + $primary['SLA'] = $failover['SLA']; + $primary['sla_fixed'] = $failover['sla_fixed']; + } + + $return_map = $primary; + } + + return $return_map; + }, + $data_a, + $data_combined[($i)] + ); + } + + $return = prepare_data_for_paint( + $sla, + $data_a, + $content, + $report['datetime'], + $return, + 'result', + $pdf + ); + } + } else { + $sla_array = data_db_uncompress_module( + $sla, + $content, + $report['datetime'] ); - // Compress (overlapped) planned downtimes - $npd = count($planned_downtimes); - for ($i = 0; $i < $npd; $i++) { - if (isset($planned_downtimes[($i + 1)])) { - if ($planned_downtimes[$i]['date_to'] >= $planned_downtimes[($i + 1)]['date_from']) { - // merge - $planned_downtimes[$i]['date_to'] = $planned_downtimes[($i + 1)]['date_to']; - array_splice($planned_downtimes, ($i + 1), 1); - $npd--; - } - } - } - } else { - $planned_downtimes = null; + $return = prepare_data_for_paint( + $sla, + $sla_array, + $content, + $report['datetime'], + $return, + '', + $pdf + ); } - $data = []; - $data['agent'] = modules_get_agentmodule_agent_alias($sla['id_agent_module']); - $data['module'] = modules_get_agentmodule_name($sla['id_agent_module']); - $data['max'] = $sla['sla_max']; - $data['min'] = $sla['sla_min']; - $data['sla_limit'] = $sla['sla_limit']; - $data['dinamic_text'] = $dinamic_text; - - if (isset($sla_array[0])) { - $data['time_total'] = 0; - $data['time_ok'] = 0; - $data['time_error'] = 0; - $data['time_unknown'] = 0; - $data['time_not_init'] = 0; - $data['time_downtime'] = 0; - $data['checks_total'] = 0; - $data['checks_ok'] = 0; - $data['checks_error'] = 0; - $data['checks_unknown'] = 0; - $data['checks_not_init'] = 0; - - $raw_graph = []; - $i = 0; - foreach ($sla_array as $value_sla) { - $data['time_total'] += $value_sla['time_total']; - $data['time_ok'] += $value_sla['time_ok']; - $data['time_error'] += $value_sla['time_error']; - $data['time_unknown'] += $value_sla['time_unknown']; - $data['time_downtime'] += $value_sla['time_downtime']; - $data['time_not_init'] += $value_sla['time_not_init']; - $data['checks_total'] += $value_sla['checks_total']; - $data['checks_ok'] += $value_sla['checks_ok']; - $data['checks_error'] += $value_sla['checks_error']; - $data['checks_unknown'] += $value_sla['checks_unknown']; - $data['checks_not_init'] += $value_sla['checks_not_init']; - - // generate raw data for graph - $period = reporting_sla_get_status_period($value_sla, $priority_mode); - $raw_graph[$i]['data'] = reporting_translate_sla_status_for_graph($period); - $raw_graph[$i]['utimestamp'] = ($value_sla['date_to'] - $value_sla['date_from']); - $i++; - } - - $data['sla_value'] = reporting_sla_get_compliance_from_array($data); - $data['sla_fixed'] = sla_truncate($data['sla_value'], $config['graph_precision']); - } else { - // Show only table not divider in slice for defect slice=1 - $data['time_total'] = $sla_array['time_total']; - $data['time_ok'] = $sla_array['time_ok']; - $data['time_error'] = $sla_array['time_error']; - $data['time_unknown'] = $sla_array['time_unknown']; - $data['time_downtime'] = $sla_array['time_downtime']; - $data['time_not_init'] = $sla_array['time_not_init']; - $data['checks_total'] = $sla_array['checks_total']; - $data['checks_ok'] = $sla_array['checks_ok']; - $data['checks_error'] = $sla_array['checks_error']; - $data['checks_unknown'] = $sla_array['checks_unknown']; - $data['checks_not_init'] = $sla_array['checks_not_init']; - $data['sla_value'] = $sla_array['SLA']; - } - - // checks whether or not it meets the SLA - if ($data['sla_value'] >= $sla['sla_limit']) { - $data['sla_status'] = 1; - $sla_failed = false; - } else { - $sla_failed = true; - $data['sla_status'] = 0; - } - - // Do not show right modules if 'only_display_wrong' is active - if ($content['only_display_wrong'] && $sla_failed == false) { - continue; - } - - // find order - $data['order'] = $data['sla_value']; - $return['data'][] = $data; - - $data_init = -1; - $acum = 0; - $sum = 0; - $array_result = []; - $i = 0; - foreach ($raw_graph as $key => $value) { - if ($data_init == -1) { - $data_init = $value['data']; - $acum = $value['utimestamp']; - $sum = $value['data']; - } else { - if ($data_init == $value['data']) { - $acum = ($acum + $value['utimestamp']); - $sum = ($sum + $value['real_data']); - } else { - $array_result[$i]['data'] = $data_init; - $array_result[$i]['utimestamp'] = $acum; - $array_result[$i]['real_data'] = $sum; - $i++; - $data_init = $value['data']; - $acum = $value['utimestamp']; - $sum = $value['real_data']; - } - } - } - - $array_result[$i]['data'] = $data_init; - $array_result[$i]['utimestamp'] = $acum; - $array_result[$i]['real_data'] = $sum; - - // Slice graphs calculation - $dataslice = []; - $dataslice['agent'] = modules_get_agentmodule_agent_alias($sla['id_agent_module']); - $dataslice['module'] = modules_get_agentmodule_name($sla['id_agent_module']); - $dataslice['order'] = $data['sla_value']; - $dataslice['checks_total'] = $data['checks_total']; - $dataslice['checks_ok'] = $data['checks_ok']; - $dataslice['time_total'] = $data['time_total']; - $dataslice['time_not_init'] = $data['time_not_init']; - $dataslice['sla_status'] = $data['sla_status']; - $dataslice['sla_value'] = $data['sla_value']; - - $dataslice['chart'] = graph_sla_slicebar( - $sla['id_agent_module'], - $content['period'], - $sla['sla_min'], - $sla['sla_max'], - $report['datetime'], - $content, - $content['time_from'], - $content['time_to'], - 100, - 70, - $urlImage, - $ttl, - $array_result, - false - ); - - $return['charts'][] = $dataslice; - if ($metaconsole_on) { - // Restore db connection + // Restore db connection. metaconsole_restore_db(); } } - // SLA items sorted descending () + // SLA items sorted descending. if ($content['top_n'] == 2) { arsort($return['data']['']); - } - // SLA items sorted ascending - else if ($content['top_n'] == 1) { + } else if ($content['top_n'] == 1) { + // SLA items sorted ascending. asort($sla_showed_values); } - // order data for ascending or descending + // Order data for ascending or descending. if ($content['top_n'] != 0) { switch ($content['top_n']) { case 1: - // order tables + // Order tables. $temp = []; foreach ($return['data'] as $row) { $i = 0; @@ -6716,7 +6889,7 @@ function reporting_availability_graph($report, $content, $pdf=false) $return['data'] = $temp; - // order graphs + // Order graphs. $temp = []; foreach ($return['charts'] as $row) { $i = 0; @@ -6732,11 +6905,10 @@ function reporting_availability_graph($report, $content, $pdf=false) } $return['charts'] = $temp; - break; case 2: - // order tables + // Order tables. $temp = []; foreach ($return['data'] as $row) { $i = 0; @@ -6753,7 +6925,7 @@ function reporting_availability_graph($report, $content, $pdf=false) $return['data'] = $temp; - // order graph + // Order graph. $temp = []; foreach ($return['charts'] as $row) { $i = 0; @@ -6769,7 +6941,10 @@ function reporting_availability_graph($report, $content, $pdf=false) } $return['charts'] = $temp; + break; + default: + // If not posible. break; } } @@ -6779,6 +6954,313 @@ function reporting_availability_graph($report, $content, $pdf=false) } +/** + * Return data db uncompress for module. + * + * @param array $sla Data neccesary for db_uncompress. + * @param array $content Conetent report. + * @param array $datetime Date. + * @param integer $slice Defined slice. + * + * @return array + */ +function data_db_uncompress_module($sla, $content, $datetime, $slice=0) +{ + // Controller min and max == 0 then dinamic min and max critical. + $dinamic_text = 0; + if ($sla['sla_min'] == 0 && $sla['sla_max'] == 0) { + $sla['sla_min'] = null; + $sla['sla_max'] = null; + $dinamic_text = __('Dynamic'); + } + + // Controller inverse interval. + $inverse_interval = 0; + if ((isset($sla['sla_max'])) && (isset($sla['sla_min']))) { + if ($sla['sla_max'] < $sla['sla_min']) { + $content_sla_max = $sla['sla_max']; + $sla['sla_max'] = $sla['sla_min']; + $sla['sla_min'] = $content_sla_max; + $inverse_interval = 1; + $dinamic_text = __('Inverse'); + } + } + + if ($slice === 0) { + // For graph slice for module-interval, if not slice=0. + $module_interval = modules_get_interval($sla['id_agent_module']); + $slice = ($content['period'] / $module_interval); + } + + // Call functions sla. + $sla_array = []; + $sla_array = reporting_advanced_sla( + $sla['id_agent_module'], + ($datetime - $content['period']), + $datetime, + $sla['sla_min'], + $sla['sla_max'], + $inverse_interval, + [ + '1' => $content['sunday'], + '2' => $content['monday'], + '3' => $content['tuesday'], + '4' => $content['wednesday'], + '5' => $content['thursday'], + '6' => $content['friday'], + '7' => $content['saturday'], + ], + $content['time_from'], + $content['time_to'], + $slice + ); + + return $sla_array; +} + + +/** + * Return array planned downtimes. + * + * @param integer $id_agent_module Id module. + * @param integer $datetime Date utimestamp. + * @param integer $period Period utimestamp. + * + * @return array + */ +function reporting_get_planned_downtimes_sla($id_agent_module, $datetime, $period) +{ + $planned_downtimes = reporting_get_planned_downtimes_intervals( + $id_agent_module, + ($datetime - $period), + $datetime + ); + + if ((is_array($planned_downtimes)) + && (count($planned_downtimes) > 0) + ) { + // Sort retrieved planned downtimes. + usort( + $planned_downtimes, + function ($a, $b) { + $a = intval($a['date_from']); + $b = intval($b['date_from']); + if ($a == $b) { + return 0; + } + + return ($a < $b) ? (-1) : 1; + } + ); + + // Compress (overlapped) planned downtimes. + $npd = count($planned_downtimes); + for ($i = 0; $i < $npd; $i++) { + if (isset($planned_downtimes[($i + 1)])) { + if ($planned_downtimes[$i]['date_to'] >= $planned_downtimes[($i + 1)]['date_from']) { + // Merge. + $planned_downtimes[$i]['date_to'] = $planned_downtimes[($i + 1)]['date_to']; + array_splice($planned_downtimes, ($i + 1), 1); + $npd--; + } + } + } + } else { + $planned_downtimes = []; + } + + return $planned_downtimes; +} + + +/** + * Prepare data for Paint in report. + * + * @param array $sla Data Module to sla. + * @param array $sla_array Data uncompressed. + * @param array $content Content report data. + * @param integer $datetime Date. + * @param array $return Array return. + * @param string $failover Type primary, failover, Result. + * @param boolean $pdf Chart pdf mode. + * + * @return array Return modify. + */ +function prepare_data_for_paint( + $sla, + $sla_array, + $content, + $datetime, + $return, + $failover='', + $pdf=false +) { + $data = []; + $alias_agent = modules_get_agentmodule_agent_alias( + $sla['id_agent_module'] + ); + $name_module = modules_get_agentmodule_name( + $sla['id_agent_module'] + ); + + $data['agent'] = $alias_agent; + $data['module'] = $name_module; + $data['max'] = $sla['sla_max']; + $data['min'] = $sla['sla_min']; + $data['sla_limit'] = $sla['sla_limit']; + $data['dinamic_text'] = $dinamic_text; + $data['failover'] = $failover; + if (isset($sla_array[0])) { + $data['time_total'] = 0; + $data['time_ok'] = 0; + $data['time_error'] = 0; + $data['time_unknown'] = 0; + $data['time_not_init'] = 0; + $data['time_downtime'] = 0; + $data['checks_total'] = 0; + $data['checks_ok'] = 0; + $data['checks_error'] = 0; + $data['checks_unknown'] = 0; + $data['checks_not_init'] = 0; + + $raw_graph = []; + $i = 0; + foreach ($sla_array as $value_sla) { + $data['time_total'] += $value_sla['time_total']; + $data['time_ok'] += $value_sla['time_ok']; + $data['time_error'] += $value_sla['time_error']; + $data['time_unknown'] += $value_sla['time_unknown']; + $data['time_downtime'] += $value_sla['time_downtime']; + $data['time_not_init'] += $value_sla['time_not_init']; + $data['checks_total'] += $value_sla['checks_total']; + $data['checks_ok'] += $value_sla['checks_ok']; + $data['checks_error'] += $value_sla['checks_error']; + $data['checks_unknown'] += $value_sla['checks_unknown']; + $data['checks_not_init'] += $value_sla['checks_not_init']; + + // Generate raw data for graph. + $period = reporting_sla_get_status_period( + $value_sla, + $priority_mode + ); + $raw_graph[$i]['data'] = reporting_translate_sla_status_for_graph( + $period + ); + $raw_graph[$i]['utimestamp'] = ($value_sla['date_to'] - $value_sla['date_from']); + $i++; + } + + $data['sla_value'] = reporting_sla_get_compliance_from_array( + $data + ); + $data['sla_fixed'] = sla_truncate( + $data['sla_value'], + $config['graph_precision'] + ); + } else { + // Show only table not divider in slice for defect slice=1. + $data['time_total'] = $sla_array['time_total']; + $data['time_ok'] = $sla_array['time_ok']; + $data['time_error'] = $sla_array['time_error']; + $data['time_unknown'] = $sla_array['time_unknown']; + $data['time_downtime'] = $sla_array['time_downtime']; + $data['time_not_init'] = $sla_array['time_not_init']; + $data['checks_total'] = $sla_array['checks_total']; + $data['checks_ok'] = $sla_array['checks_ok']; + $data['checks_error'] = $sla_array['checks_error']; + $data['checks_unknown'] = $sla_array['checks_unknown']; + $data['checks_not_init'] = $sla_array['checks_not_init']; + $data['sla_value'] = $sla_array['SLA']; + } + + // Checks whether or not it meets the SLA. + if ($data['sla_value'] >= $sla['sla_limit']) { + $data['sla_status'] = 1; + $sla_failed = false; + } else { + $sla_failed = true; + $data['sla_status'] = 0; + } + + // Do not show right modules if 'only_display_wrong' is active. + if ($content['only_display_wrong'] && $sla_failed == false) { + return $return; + } + + // Find order. + $data['order'] = $data['sla_value']; + $return['data'][] = $data; + + $data_init = -1; + $acum = 0; + $sum = 0; + $array_result = []; + $i = 0; + foreach ($raw_graph as $key => $value) { + if ($data_init == -1) { + $data_init = $value['data']; + $acum = $value['utimestamp']; + $sum = $value['data']; + } else { + if ($data_init == $value['data']) { + $acum = ($acum + $value['utimestamp']); + $sum = ($sum + $value['real_data']); + } else { + $array_result[$i]['data'] = $data_init; + $array_result[$i]['utimestamp'] = $acum; + $array_result[$i]['real_data'] = $sum; + $i++; + $data_init = $value['data']; + $acum = $value['utimestamp']; + $sum = $value['real_data']; + } + } + } + + $array_result[$i]['data'] = $data_init; + $array_result[$i]['utimestamp'] = $acum; + $array_result[$i]['real_data'] = $sum; + + // Slice graphs calculation. + $dataslice = []; + $dataslice['agent'] = $alias_agent; + $dataslice['module'] = $name_module; + $dataslice['order'] = $data['sla_value']; + $dataslice['checks_total'] = $data['checks_total']; + $dataslice['checks_ok'] = $data['checks_ok']; + $dataslice['time_total'] = $data['time_total']; + $dataslice['time_not_init'] = $data['time_not_init']; + $dataslice['sla_status'] = $data['sla_status']; + $dataslice['sla_value'] = $data['sla_value']; + + $height = 80; + if ($failover !== '' && $failover !== 'result') { + $height = 50; + } + + $dataslice['chart'] = graph_sla_slicebar( + $sla['id_agent_module'], + $content['period'], + $sla['sla_min'], + $sla['sla_max'], + $datetime, + $content, + $content['time_from'], + $content['time_to'], + 100, + $height, + $urlImage, + ($pdf) ? 2 : 0, + $array_result, + false + ); + + $return['charts'][] = $dataslice; + + return $return; +} + + /** * reporting_increment * @@ -6807,15 +7289,15 @@ function reporting_increment($report, $content) $return['data'] = []; - if (defined('METACONSOLE')) { + if (is_metaconsole()) { $sql1 = 'SELECT datos FROM tagente_datos WHERE id_agente_modulo = '.$id_agent_module.' - AND utimestamp <= '.(time() - $period).' ORDER BY utimestamp DESC'; + AND utimestamp <= '.(time() - $period).' ORDER BY utimestamp DESC'; $sql2 = 'SELECT datos FROM tagente_datos WHERE id_agente_modulo = '.$id_agent_module.' ORDER BY utimestamp DESC'; $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -6839,13 +7321,13 @@ function reporting_increment($report, $content) } else { $old_data = db_get_value_sql( 'SELECT datos FROM tagente_datos WHERE id_agente_modulo = '.$id_agent_module.' - AND utimestamp <= '.(time() - $period).' ORDER BY utimestamp DESC' + AND utimestamp <= '.(time() - $period).' ORDER BY utimestamp DESC' ); $last_data = db_get_value_sql('SELECT datos FROM tagente_datos WHERE id_agente_modulo = '.$id_agent_module.' ORDER BY utimestamp DESC'); } - if (!defined('METACONSOLE')) { + if (!is_metaconsole()) { } if ($old_data === false || $last_data === false) { @@ -6934,7 +7416,7 @@ function reporting_general($report, $content) foreach ($generals as $row) { // Metaconsole connection $server_name = $row['server_name']; - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); @@ -6955,6 +7437,7 @@ function reporting_general($report, $content) $mod_name = modules_get_agentmodule_name($row['id_agent_module']); $ag_name = modules_get_agentmodule_agent_alias($row['id_agent_module']); + $name_agent = modules_get_agentmodule_agent_name($row['id_agent_module']); $type_mod = modules_get_last_value($row['id_agent_module']); $is_string[$index] = modules_is_string($row['id_agent_module']); $unit = db_get_value( @@ -7029,12 +7512,12 @@ function reporting_general($report, $content) } if ($data_res[$index] === false) { - $return['data'][$ag_name][$mod_name] = null; + $return['data'][$name_agent][$mod_name] = null; } else { if (!is_numeric($data_res[$index])) { - $return['data'][$ag_name][$mod_name] = $data_res[$index]; + $return['data'][$name_agent][$mod_name] = $data_res[$index]; } else { - $return['data'][$ag_name][$mod_name] = format_for_graph($data_res[$index], 2).' '.$unit; + $return['data'][$name_agent][$mod_name] = format_for_graph($data_res[$index], 2).' '.$unit; } } break; @@ -7085,7 +7568,7 @@ function reporting_general($report, $content) $i++; // Restore dbconnection - if (($config['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) { + if (($config['metaconsole'] == 1) && $server_name != '' && is_metaconsole()) { metaconsole_restore_db(); } } @@ -7262,8 +7745,8 @@ function reporting_custom_graph( if (is_metaconsole()) { $module_source = db_get_all_rows_sql( 'SELECT id_agent_module, id_server - FROM tgraph_source - WHERE id_graph = '.$content['id_gs'] + FROM tgraph_source + WHERE id_graph = '.$content['id_gs'] ); if (isset($module_source) && is_array($module_source)) { @@ -7337,6 +7820,17 @@ function reporting_custom_graph( } +/** + * Simple graph report. + * + * @param array $report Info report. + * @param array $content Content report. + * @param string $type Type report. + * @param integer $force_width_chart Width chart. + * @param integer $force_height_chart Height chart. + * + * @return array + */ function reporting_simple_graph( $report, $content, @@ -7346,13 +7840,6 @@ function reporting_simple_graph( ) { global $config; - if ($config['metaconsole']) { - $id_meta = metaconsole_get_id_server($content['server_name']); - - $server = metaconsole_get_connection_by_id($id_meta); - metaconsole_connect($server); - } - $return = []; $return['type'] = 'simple_graph'; @@ -7360,16 +7847,52 @@ function reporting_simple_graph( $content['name'] = __('Simple graph'); } - $module_name = io_safe_output( - modules_get_agentmodule_name($content['id_agent_module']) + if ($config['metaconsole']) { + $id_meta = metaconsole_get_id_server($content['server_name']); + + $server = metaconsole_get_connection_by_id($id_meta); + metaconsole_connect($server); + } + + $id_agent = agents_get_module_id( + $content['id_agent_module'] ); - $agent_name = io_safe_output( - modules_get_agentmodule_agent_alias($content['id_agent_module']) + $id_agent_module = $content['id_agent_module']; + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module ); + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + + $items_label = [ + 'type' => $return['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + + $label = (isset($content['style']['label'])) ? $content['style']['label'] : ''; + if ($label != '') { + $label = reporting_label_macro( + $items_label, + $label + ); + } + $return['title'] = $content['name']; - $return['subtitle'] = $agent_name.' - '.$module_name; - $return['agent_name'] = $agent_name; + $return['subtitle'] = $agent_alias.' - '.$module_name; + $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text( @@ -7377,11 +7900,6 @@ function reporting_simple_graph( $content ); - $label = (isset($content['style']['label'])) ? $content['style']['label'] : ''; - if ($label != '') { - $label = reporting_label_macro($content, $label); - } - if (isset($content['style']['fullscale'])) { $fullscale = (bool) $content['style']['fullscale']; } @@ -7389,7 +7907,14 @@ function reporting_simple_graph( $return['chart'] = ''; // Get chart. - reporting_set_conf_charts($width, $height, $only_image, $type, $content, $ttl); + reporting_set_conf_charts( + $width, + $height, + $only_image, + $type, + $content, + $ttl + ); if (!empty($force_width_chart)) { $width = $force_width_chart; @@ -7415,7 +7940,12 @@ function reporting_simple_graph( 'pure' => false, 'date' => $report['datetime'], 'only_image' => $only_image, - 'homeurl' => ui_get_full_url(false, false, false, false), + 'homeurl' => ui_get_full_url( + false, + false, + false, + false + ), 'ttl' => $ttl, 'compare' => $time_compare_overlapped, 'show_unknown' => true, @@ -7426,7 +7956,6 @@ function reporting_simple_graph( ]; $return['chart'] = grafico_modulo_sparse($params); - break; case 'data': @@ -7440,6 +7969,10 @@ function reporting_simple_graph( $return['chart'][$d['utimestamp']] = $d['data']; } break; + + default: + // Not Possible. + break; } if ($config['metaconsole']) { @@ -8001,10 +8534,10 @@ function reporting_get_group_stats($id_group=0, $access='AR') foreach ($id_group as $group) { $group_stat = db_get_all_rows_sql( "SELECT * - FROM tgroup_stat, tgrupo - WHERE tgrupo.id_grupo = tgroup_stat.id_group - AND tgroup_stat.id_group = $group - ORDER BY nombre" + FROM tgroup_stat, tgrupo + WHERE tgrupo.id_grupo = tgroup_stat.id_group + AND tgroup_stat.id_group = $group + ORDER BY nombre" ); $data['monitor_checks'] += $group_stat[0]['modules']; @@ -8232,10 +8765,10 @@ function reporting_get_group_stats_resume($id_group=0, $access='AR') foreach ($id_group as $group) { $group_stat = db_get_all_rows_sql( "SELECT * - FROM tgroup_stat, tgrupo - WHERE tgrupo.id_grupo = tgroup_stat.id_group - AND tgroup_stat.id_group = $group - ORDER BY nombre" + FROM tgroup_stat, tgrupo + WHERE tgrupo.id_grupo = tgroup_stat.id_group + AND tgroup_stat.id_group = $group + ORDER BY nombre" ); $data['monitor_checks'] += $group_stat[0]['modules']; @@ -8270,8 +8803,8 @@ function reporting_get_group_stats_resume($id_group=0, $access='AR') $tags = db_get_value('tags', 'tusuario_perfil', 'id_usuario', $config['id_user']); if ($tags) { $tags_sql = " AND tae.id_agente_modulo IN ( SELECT id_agente_modulo - FROM ttag_module - WHERE id_tag IN ($tags) ) "; + FROM ttag_module + WHERE id_tag IN ($tags) ) "; } else { $tags_sql = ''; } @@ -8282,27 +8815,27 @@ function reporting_get_group_stats_resume($id_group=0, $access='AR') // for stats modules $sql = "SELECT tg.id_grupo as id, tg.nombre as name, - SUM(tae.estado=0) as monitor_ok, - SUM(tae.estado=1) as monitor_critical, - SUM(tae.estado=2) as monitor_warning, - SUM(tae.estado=3) as monitor_unknown, - SUM(tae.estado=4) as monitor_not_init, - COUNT(tae.estado) as monitor_total + SUM(tae.estado=0) as monitor_ok, + SUM(tae.estado=1) as monitor_critical, + SUM(tae.estado=2) as monitor_warning, + SUM(tae.estado=3) as monitor_unknown, + SUM(tae.estado=4) as monitor_not_init, + COUNT(tae.estado) as monitor_total - FROM - tagente_estado tae, - tagente ta, - tagente_modulo tam, - tgrupo tg + FROM + tagente_estado tae, + tagente ta, + tagente_modulo tam, + tgrupo tg - WHERE 1=1 - AND tae.id_agente = ta.id_agente - AND tae.id_agente_modulo = tam.id_agente_modulo - AND ta.id_grupo = tg.id_grupo - AND tam.disabled = 0 - AND ta.disabled = 0 - AND ta.id_grupo IN ($id_group) $tags_sql - GROUP BY tg.id_grupo;"; + WHERE 1=1 + AND tae.id_agente = ta.id_agente + AND tae.id_agente_modulo = tam.id_agente_modulo + AND ta.id_grupo = tg.id_grupo + AND tam.disabled = 0 + AND ta.disabled = 0 + AND ta.id_grupo IN ($id_group) $tags_sql + GROUP BY tg.id_grupo;"; $data_array = db_get_all_rows_sql($sql); $data = $data_array[0]; @@ -8315,27 +8848,27 @@ function reporting_get_group_stats_resume($id_group=0, $access='AR') // for stats agents $sql = "SELECT tae.id_agente id_agente, tg.id_grupo id_grupo, - SUM(tae.estado=0) as monitor_agent_ok, - SUM(tae.estado=1) as monitor_agent_critical, - SUM(tae.estado=2) as monitor_agent_warning, - SUM(tae.estado=3) as monitor_agent_unknown, - SUM(tae.estado=4) as monitor_agent_not_init, - COUNT(tae.estado) as monitor_agent_total + SUM(tae.estado=0) as monitor_agent_ok, + SUM(tae.estado=1) as monitor_agent_critical, + SUM(tae.estado=2) as monitor_agent_warning, + SUM(tae.estado=3) as monitor_agent_unknown, + SUM(tae.estado=4) as monitor_agent_not_init, + COUNT(tae.estado) as monitor_agent_total - FROM - tagente_estado tae, - tagente ta, - tagente_modulo tam, - tgrupo tg - - WHERE 1=1 - AND tae.id_agente = ta.id_agente - AND tae.id_agente_modulo = tam.id_agente_modulo - AND ta.id_grupo = tg.id_grupo - AND tam.disabled = 0 - AND ta.disabled = 0 - AND ta.id_grupo IN ($id_group) $tags_sql - GROUP BY tae.id_agente;"; + FROM + tagente_estado tae, + tagente ta, + tagente_modulo tam, + tgrupo tg + + WHERE 1=1 + AND tae.id_agente = ta.id_agente + AND tae.id_agente_modulo = tam.id_agente_modulo + AND ta.id_grupo = tg.id_grupo + AND tam.disabled = 0 + AND ta.disabled = 0 + AND ta.id_grupo IN ($id_group) $tags_sql + GROUP BY tae.id_agente;"; $data_array_2 = db_get_all_rows_sql($sql); if (is_array($data_array_2) || is_object($data_array_2)) { @@ -8446,22 +8979,22 @@ function reporting_get_stats_indicators($data, $width=280, $height=20, $html=tru if ($html) { $tdata[0] = '
- '.__('Server health').ui_print_help_tip(sprintf(__('%d Downed servers'), $servers['down']), true).''.progress_bar($servers['health'], $width, $height, '', 0).'
'; + '.__('Server health').ui_print_help_tip(sprintf(__('%d Downed servers'), $servers['down']), true).''.progress_bar($servers['health'], $width, $height, '', 0).''; $table_ind->rowclass[] = ''; $table_ind->data[] = $tdata; $tdata[0] = '
- '.__('Monitor health').ui_print_help_tip(sprintf(__('%d Not Normal monitors'), $data['monitor_not_normal']), true).''.progress_bar($data['monitor_health'], $width, $height, $data['monitor_health'].'% '.__('of monitors up'), 0).'
'; + '.__('Monitor health').ui_print_help_tip(sprintf(__('%d Not Normal monitors'), $data['monitor_not_normal']), true).''.progress_bar($data['monitor_health'], $width, $height, $data['monitor_health'].'% '.__('of monitors up'), 0).''; $table_ind->rowclass[] = ''; $table_ind->data[] = $tdata; $tdata[0] = '
- '.__('Module sanity').ui_print_help_tip(sprintf(__('%d Not inited monitors'), $data['monitor_not_init']), true).''.progress_bar($data['module_sanity'], $width, $height, $data['module_sanity'].'% '.__('of total modules inited'), 0).'
'; + '.__('Module sanity').ui_print_help_tip(sprintf(__('%d Not inited monitors'), $data['monitor_not_init']), true).''.progress_bar($data['module_sanity'], $width, $height, $data['module_sanity'].'% '.__('of total modules inited'), 0).''; $table_ind->rowclass[] = ''; $table_ind->data[] = $tdata; $tdata[0] = '
- '.__('Alert level').ui_print_help_tip(sprintf(__('%d Fired alerts'), $data['monitor_alerts_fired']), true).''.progress_bar($data['alert_level'], $width, $height, $data['alert_level'].'% '.__('of defined alerts not fired'), 0).'
'; + '.__('Alert level').ui_print_help_tip(sprintf(__('%d Fired alerts'), $data['monitor_alerts_fired']), true).''.progress_bar($data['alert_level'], $width, $height, $data['alert_level'].'% '.__('of defined alerts not fired'), 0).''; $table_ind->rowclass[] = ''; $table_ind->data[] = $tdata; @@ -8544,7 +9077,7 @@ function reporting_get_stats_alerts($data, $links=false) if (!is_metaconsole()) { $output = '
- '.__('Defined and fired alerts').''.html_print_table($table_al, true).'
'; + '.__('Defined and fired alerts').''.html_print_table($table_al, true).''; } else { // Remove the defined alerts cause with the new cache table is difficult to retrieve them unset($table_al->data[0][0], $table_al->data[0][1]); @@ -8552,7 +9085,7 @@ function reporting_get_stats_alerts($data, $links=false) $table_al->class = 'tactical_view'; $table_al->style = []; $output = '
- '.__('Fired alerts').''.html_print_table($table_al, true).'
'; + '.__('Fired alerts').''.html_print_table($table_al, true).''; } return $output; @@ -8628,14 +9161,14 @@ function reporting_get_stats_modules_status($data, $graph_width=250, $graph_heig if (!is_metaconsole()) { $output = ' -
- '.__('Monitors by status').''.html_print_table($table_mbs, true).'
'; +
+ '.__('Monitors by status').''.html_print_table($table_mbs, true).'
'; } else { $table_mbs->class = 'tactical_view'; $table_mbs->style = []; $output = ' -
- '.__('Monitors by status').''.html_print_table($table_mbs, true).'
'; +
+ '.__('Monitors by status').''.html_print_table($table_mbs, true).'
'; } return $output; @@ -8701,7 +9234,7 @@ function reporting_get_stats_agents_monitors($data) $table_am->data[] = $tdata; $output = '
- '.__('Total agents and monitors').''.html_print_table($table_am, true).'
'; + '.__('Total agents and monitors').''.html_print_table($table_am, true).''; return $output; } @@ -8732,7 +9265,7 @@ function reporting_get_stats_users($data) $table_us->data[] = $tdata; $output = '
- '.__('Users').''.html_print_table($table_us, true).'
'; + '.__('Users').''.html_print_table($table_us, true).''; return $output; } @@ -8767,8 +9300,8 @@ function reporting_get_agentmodule_data_average($id_agent_module, $period=0, $da // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + FROM tagente_datos + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -8893,8 +9426,8 @@ function reporting_get_agentmodule_mttr($id_agent_module, $period=0, $date=0) $module = db_get_row_sql( 'SELECT max_critical, min_critical, id_tipo_modulo - FROM tagente_modulo - WHERE id_agente_modulo = '.(int) $id_agent_module + FROM tagente_modulo + WHERE id_agente_modulo = '.(int) $id_agent_module ); if ($module === false) { return false; @@ -8915,7 +9448,7 @@ function reporting_get_agentmodule_mttr($id_agent_module, $period=0, $date=0) // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -9039,8 +9572,8 @@ function reporting_get_agentmodule_mtbf($id_agent_module, $period=0, $date=0) $module = db_get_row_sql( 'SELECT max_critical, min_critical, id_tipo_modulo - FROM tagente_modulo - WHERE id_agente_modulo = '.(int) $id_agent_module + FROM tagente_modulo + WHERE id_agente_modulo = '.(int) $id_agent_module ); if ($module === false) { return false; @@ -9061,7 +9594,7 @@ function reporting_get_agentmodule_mtbf($id_agent_module, $period=0, $date=0) // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -9181,8 +9714,8 @@ function reporting_get_agentmodule_tto($id_agent_module, $period=0, $date=0) $module = db_get_row_sql( 'SELECT max_critical, min_critical, id_tipo_modulo - FROM tagente_modulo - WHERE id_agente_modulo = '.(int) $id_agent_module + FROM tagente_modulo + WHERE id_agente_modulo = '.(int) $id_agent_module ); if ($module === false) { return false; @@ -9203,7 +9736,7 @@ function reporting_get_agentmodule_tto($id_agent_module, $period=0, $date=0) // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -9290,8 +9823,8 @@ function reporting_get_agentmodule_ttr($id_agent_module, $period=0, $date=0) $module = db_get_row_sql( 'SELECT max_critical, min_critical, id_tipo_modulo - FROM tagente_modulo - WHERE id_agente_modulo = '.(int) $id_agent_module + FROM tagente_modulo + WHERE id_agente_modulo = '.(int) $id_agent_module ); if ($module === false) { return false; @@ -9312,7 +9845,7 @@ function reporting_get_agentmodule_ttr($id_agent_module, $period=0, $date=0) // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -9761,9 +10294,9 @@ function reporting_get_agentmodule_sla( // Get interval data $sql = sprintf( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = %d - AND utimestamp > %d AND utimestamp <= %d', + FROM tagente_datos + WHERE id_agente_modulo = %d + AND utimestamp > %d AND utimestamp <= %d', $id_agent_module, $datelimit, $date @@ -9982,43 +10515,43 @@ function reporting_get_planned_downtimes_intervals($id_agent_module, $start_date } $sql_downtime = ' - SELECT DISTINCT(tpdr.id), - tpdr.name, - '.$tpdr_description.", - tpdr.date_from, - tpdr.date_to, - tpdr.executed, - tpdr.id_group, - tpdr.only_alerts, - tpdr.monday, - tpdr.tuesday, - tpdr.wednesday, - tpdr.thursday, - tpdr.friday, - tpdr.saturday, - tpdr.sunday, - tpdr.periodically_time_from, - tpdr.periodically_time_to, - tpdr.periodically_day_from, - tpdr.periodically_day_to, - tpdr.type_downtime, - tpdr.type_execution, - tpdr.type_periodicity, - tpdr.id_user - FROM ( - SELECT tpd.* - FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam - WHERE tpd.id = tpda.id_downtime - AND tpda.all_modules = 1 - AND tpda.id_agent = tam.id_agente - AND tam.id_agente_modulo = $id_agent_module - UNION ALL - SELECT tpd.* - FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm - WHERE tpd.id = tpdm.id_downtime - AND tpdm.id_agent_module = $id_agent_module - ) tpdr - ORDER BY tpdr.id"; + SELECT DISTINCT(tpdr.id), + tpdr.name, + '.$tpdr_description.", + tpdr.date_from, + tpdr.date_to, + tpdr.executed, + tpdr.id_group, + tpdr.only_alerts, + tpdr.monday, + tpdr.tuesday, + tpdr.wednesday, + tpdr.thursday, + tpdr.friday, + tpdr.saturday, + tpdr.sunday, + tpdr.periodically_time_from, + tpdr.periodically_time_to, + tpdr.periodically_day_from, + tpdr.periodically_day_to, + tpdr.type_downtime, + tpdr.type_execution, + tpdr.type_periodicity, + tpdr.id_user + FROM ( + SELECT tpd.* + FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam + WHERE tpd.id = tpda.id_downtime + AND tpda.all_modules = 1 + AND tpda.id_agent = tam.id_agente + AND tam.id_agente_modulo = $id_agent_module + UNION ALL + SELECT tpd.* + FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm + WHERE tpd.id = tpdm.id_downtime + AND tpdm.id_agent_module = $id_agent_module + ) tpdr + ORDER BY tpdr.id"; $downtimes = db_get_all_rows_sql($sql_downtime); @@ -10227,8 +10760,8 @@ function reporting_get_agentmodule_data_max($id_agent_module, $period=0, $date=0 // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + FROM tagente_datos + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); @@ -10333,8 +10866,8 @@ function reporting_get_agentmodule_data_min($id_agent_module, $period=0, $date=0 // Get module data $interval_data = db_get_all_rows_sql( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', + FROM tagente_datos + WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' ORDER BY utimestamp ASC', $search_in_history_db ); if ($interval_data === false) { @@ -10459,11 +10992,11 @@ function reporting_get_agentmodule_data_sum( // Get module data $interval_data = db_get_all_rows_sql( ' - SELECT * FROM tagente_datos - WHERE id_agente_modulo = '.(int) $id_agent_module.' - AND utimestamp > '.(int) $datelimit.' - AND utimestamp < '.(int) $date.' - ORDER BY utimestamp ASC', + SELECT * FROM tagente_datos + WHERE id_agente_modulo = '.(int) $id_agent_module.' + AND utimestamp > '.(int) $datelimit.' + AND utimestamp < '.(int) $date.' + ORDER BY utimestamp ASC', $search_in_history_db ); } else { @@ -10558,24 +11091,24 @@ function reporting_get_planned_downtimes($start_date, $end_date, $id_agent_modul // is inside the planned downtime execution. // The start and end time is very important. $periodically_monthly_w = "type_periodicity = 'monthly' - AND (((periodically_day_from > '$start_day' - OR (periodically_day_from = '$start_day' - AND periodically_time_from >= '$start_time')) - AND (periodically_day_to < '$end_day' - OR (periodically_day_to = '$end_day' - AND periodically_time_to <= '$end_time'))) - OR ((periodically_day_from < '$start_day' - OR (periodically_day_from = '$start_day' - AND periodically_time_from <= '$start_time')) - AND (periodically_day_to > '$start_day' - OR (periodically_day_to = '$start_day' - AND periodically_time_to >= '$start_time'))) - OR ((periodically_day_from < '$end_day' - OR (periodically_day_from = '$end_day' - AND periodically_time_from <= '$end_time')) - AND (periodically_day_to > '$end_day' - OR (periodically_day_to = '$end_day' - AND periodically_time_to >= '$end_time'))))"; + AND (((periodically_day_from > '$start_day' + OR (periodically_day_from = '$start_day' + AND periodically_time_from >= '$start_time')) + AND (periodically_day_to < '$end_day' + OR (periodically_day_to = '$end_day' + AND periodically_time_to <= '$end_time'))) + OR ((periodically_day_from < '$start_day' + OR (periodically_day_from = '$start_day' + AND periodically_time_from <= '$start_time')) + AND (periodically_day_to > '$start_day' + OR (periodically_day_to = '$start_day' + AND periodically_time_to >= '$start_time'))) + OR ((periodically_day_from < '$end_day' + OR (periodically_day_from = '$end_day' + AND periodically_time_from <= '$end_time')) + AND (periodically_day_to > '$end_day' + OR (periodically_day_to = '$end_day' + AND periodically_time_to >= '$end_time'))))"; } $periodically_weekly_days = []; @@ -10595,13 +11128,13 @@ function reporting_get_planned_downtimes($start_date, $end_date, $id_agent_modul // the start or end time of the date range. $weekday_actual = strtolower(date('l', $start_date)); $periodically_weekly_days[] = "($weekday_actual = 1 - AND ((periodically_time_from > '$start_time' AND periodically_time_to < '$end_time') - OR (periodically_time_from = '$start_time' - OR (periodically_time_from < '$start_time' - AND periodically_time_to >= '$start_time')) - OR (periodically_time_from = '$end_time' - OR (periodically_time_from < '$end_time' - AND periodically_time_to >= '$end_time'))))"; + AND ((periodically_time_from > '$start_time' AND periodically_time_to < '$end_time') + OR (periodically_time_from = '$start_time' + OR (periodically_time_from < '$start_time' + AND periodically_time_to >= '$start_time')) + OR (periodically_time_from = '$end_time' + OR (periodically_time_from < '$end_time' + AND periodically_time_to >= '$end_time'))))"; } else { while ($date_aux <= $end_date && $i < 7) { $weekday_actual = strtolower(date('l', $date_aux)); @@ -10646,68 +11179,68 @@ function reporting_get_planned_downtimes($start_date, $end_date, $id_agent_modul } $sql_downtime = ' - SELECT - DISTINCT(tpdr.id), - tpdr.name, - '.$tpdr_description.", - tpdr.date_from, - tpdr.date_to, - tpdr.executed, - tpdr.id_group, - tpdr.only_alerts, - tpdr.monday, - tpdr.tuesday, - tpdr.wednesday, - tpdr.thursday, - tpdr.friday, - tpdr.saturday, - tpdr.sunday, - tpdr.periodically_time_from, - tpdr.periodically_time_to, - tpdr.periodically_day_from, - tpdr.periodically_day_to, - tpdr.type_downtime, - tpdr.type_execution, - tpdr.type_periodicity, - tpdr.id_user - FROM ( - SELECT tpd.* - FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam - WHERE (tpd.id = tpda.id_downtime - AND tpda.all_modules = 1 - AND tpda.id_agent = tam.id_agente - AND tam.id_agente_modulo IN ($id_agent_modules_str)) - AND ((type_execution = 'periodically' - AND $periodically_condition) - OR (type_execution = 'once' - AND ((date_from >= '$start_date' AND date_to <= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$start_date') - OR (date_from <= '$end_date' AND date_to >= '$end_date')))) - UNION ALL - SELECT tpd.* - FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm - WHERE (tpd.id = tpdm.id_downtime - AND tpdm.id_agent_module IN ($id_agent_modules_str)) - AND ((type_execution = 'periodically' - AND $periodically_condition) - OR (type_execution = 'once' - AND ((date_from >= '$start_date' AND date_to <= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$start_date') - OR (date_from <= '$end_date' AND date_to >= '$end_date')))) - ) tpdr - ORDER BY tpdr.id"; + SELECT + DISTINCT(tpdr.id), + tpdr.name, + '.$tpdr_description.", + tpdr.date_from, + tpdr.date_to, + tpdr.executed, + tpdr.id_group, + tpdr.only_alerts, + tpdr.monday, + tpdr.tuesday, + tpdr.wednesday, + tpdr.thursday, + tpdr.friday, + tpdr.saturday, + tpdr.sunday, + tpdr.periodically_time_from, + tpdr.periodically_time_to, + tpdr.periodically_day_from, + tpdr.periodically_day_to, + tpdr.type_downtime, + tpdr.type_execution, + tpdr.type_periodicity, + tpdr.id_user + FROM ( + SELECT tpd.* + FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam + WHERE (tpd.id = tpda.id_downtime + AND tpda.all_modules = 1 + AND tpda.id_agent = tam.id_agente + AND tam.id_agente_modulo IN ($id_agent_modules_str)) + AND ((type_execution = 'periodically' + AND $periodically_condition) + OR (type_execution = 'once' + AND ((date_from >= '$start_date' AND date_to <= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$start_date') + OR (date_from <= '$end_date' AND date_to >= '$end_date')))) + UNION ALL + SELECT tpd.* + FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm + WHERE (tpd.id = tpdm.id_downtime + AND tpdm.id_agent_module IN ($id_agent_modules_str)) + AND ((type_execution = 'periodically' + AND $periodically_condition) + OR (type_execution = 'once' + AND ((date_from >= '$start_date' AND date_to <= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$start_date') + OR (date_from <= '$end_date' AND date_to >= '$end_date')))) + ) tpdr + ORDER BY tpdr.id"; } else { $sql_downtime = "SELECT * - FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm - WHERE (type_execution = 'periodically' - AND $periodically_condition) - OR (type_execution = 'once' - AND ((date_from >= '$start_date' AND date_to <= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$end_date') - OR (date_from <= '$start_date' AND date_to >= '$start_date') - OR (date_from <= '$end_date' AND date_to >= '$end_date')))"; + FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm + WHERE (type_execution = 'periodically' + AND $periodically_condition) + OR (type_execution = 'once' + AND ((date_from >= '$start_date' AND date_to <= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$end_date') + OR (date_from <= '$start_date' AND date_to >= '$start_date') + OR (date_from <= '$end_date' AND date_to >= '$end_date')))"; } $downtimes = db_get_all_rows_sql($sql_downtime); @@ -10775,10 +11308,10 @@ function reporting_get_agentmodule_sla_day($id_agent_module, $period=0, $min_val // Get interval data $sql = sprintf( 'SELECT * - FROM tagente_datos - WHERE id_agente_modulo = %d - AND utimestamp > %d - AND utimestamp <= %d', + FROM tagente_datos + WHERE id_agente_modulo = %d + AND utimestamp > %d + AND utimestamp <= %d', $id_agent_module, $datelimit, $date @@ -10980,10 +11513,10 @@ function reporting_get_stats_servers() $tdata = []; ''.format_numeric($server_performance['total_local_modules']).''; - $tdata[0] = html_print_image('images/module.png', true, ['title' => __('Total running modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/module.png', true, ['title' => __('Total running modules')]); $tdata[1] = ''.format_numeric($server_performance['total_modules']).''; $tdata[2] = ''.format_numeric($server_performance['total_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; @@ -10995,22 +11528,22 @@ function reporting_get_stats_servers() $table_srv->data[] = $tdata; $tdata = []; - $tdata[0] = html_print_image('images/database.png', true, ['title' => __('Local modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/database.png', true, ['title' => __('Local modules')]); $tdata[1] = ''.format_numeric($server_performance['total_local_modules']).''; $tdata[2] = ''.format_numeric($server_performance['local_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; if (isset($server_performance['total_network_modules'])) { $tdata = []; - $tdata[0] = html_print_image('images/network.png', true, ['title' => __('Network modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/network.png', true, ['title' => __('Network modules')]); $tdata[1] = ''.format_numeric($server_performance['total_network_modules']).''; $tdata[2] = ''.format_numeric($server_performance['network_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; if ($server_performance['total_remote_modules'] > 10000 && !enterprise_installed()) { $tdata[4] = "
"; @@ -11024,11 +11557,11 @@ function reporting_get_stats_servers() if (isset($server_performance['total_plugin_modules'])) { $tdata = []; - $tdata[0] = html_print_image('images/plugin.png', true, ['title' => __('Plugin modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/plugin.png', true, ['title' => __('Plugin modules')]); $tdata[1] = ''.format_numeric($server_performance['total_plugin_modules']).''; $tdata[2] = ''.format_numeric($server_performance['plugin_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; @@ -11036,11 +11569,11 @@ function reporting_get_stats_servers() if (isset($server_performance['total_prediction_modules'])) { $tdata = []; - $tdata[0] = html_print_image('images/chart_bar.png', true, ['title' => __('Prediction modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/chart_bar.png', true, ['title' => __('Prediction modules')]); $tdata[1] = ''.format_numeric($server_performance['total_prediction_modules']).''; $tdata[2] = ''.format_numeric($server_performance['prediction_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; @@ -11048,11 +11581,11 @@ function reporting_get_stats_servers() if (isset($server_performance['total_wmi_modules'])) { $tdata = []; - $tdata[0] = html_print_image('images/wmi.png', true, ['title' => __('WMI modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/wmi.png', true, ['title' => __('WMI modules')]); $tdata[1] = ''.format_numeric($server_performance['total_wmi_modules']).''; $tdata[2] = ''.format_numeric($server_performance['wmi_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; @@ -11060,11 +11593,11 @@ function reporting_get_stats_servers() if (isset($server_performance['total_web_modules'])) { $tdata = []; - $tdata[0] = html_print_image('images/world.png', true, ['title' => __('Web modules'), 'width' => '25px']); + $tdata[0] = html_print_image('images/world.png', true, ['title' => __('Web modules')]); $tdata[1] = ''.format_numeric($server_performance['total_web_modules']).''; $tdata[2] = ''.format_numeric($server_performance['web_modules_rate'], 2).''; - $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'width' => '16px']).'/sec '; + $tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second')]).'/sec '; $table_srv->rowclass[] = ''; $table_srv->data[] = $tdata; @@ -11082,7 +11615,6 @@ function reporting_get_stats_servers() true, [ 'title' => __('Total events'), - 'width' => '25px', ] ); $tdata[1] = ''.html_print_image('images/spinner.gif', true).''; @@ -11104,23 +11636,40 @@ function reporting_get_stats_servers() $table_srv->data[] = $tdata; $output = '
- '.__('Server performance').''.html_print_table($table_srv, true).'
'; + '.__('Server performance').''.html_print_table($table_srv, true).''; - $output .= ''; + $output .= ''; + } else { + // This is for public link on the dashboard + $sql_count_event = 'SELECT SQL_NO_CACHE COUNT(id_evento) FROM tevento '; + if ($config['event_view_hr']) { + $sql_count_event .= 'WHERE utimestamp > (UNIX_TIMESTAMP(NOW()) - '.($config['event_view_hr'] * SECONDS_1HOUR).')'; + } - return $output; + $system_events = db_get_value_sql($sql_count_event); + + $output .= ''; + } + + return $output; } @@ -11462,120 +12011,100 @@ function reporting_get_agentmodule_sla_working_timestamp($period, $date_end, $wt } +/** + * Convert macros for value. + * Item content: + * type + * id_agent + * id_agent_module + * agent_description + * agent_group + * agent_address + * agent_alias + * module_name + * module_description. + * + * @param array $item Data to replace in the macros. + * @param string $label String check macros. + * + * @return string + */ function reporting_label_macro($item, $label) { - switch ($item['type']) { - case 'event_report_agent': - case 'alert_report_agent': - case 'agent_configuration': - case 'event_report_log': - if (preg_match('/_agent_/', $label)) { - $agent_name = agents_get_alias($item['id_agent']); - $label = str_replace('_agent_', $agent_name, $label); - } + if (preg_match('/_agent_/', $label)) { + $label = str_replace( + '_agent_', + $item['agent_alias'], + $label + ); + } - if (preg_match('/_agentdescription_/', $label)) { - $agent_name = agents_get_description($item['id_agent']); - $label = str_replace('_agentdescription_', $agent_name, $label); - } + if (preg_match('/_agentdescription_/', $label)) { + $label = str_replace( + '_agentdescription_', + $item['agent_description'], + $label + ); + } - if (preg_match('/_agentgroup_/', $label)) { - $agent_name = groups_get_name(agents_get_agent_group($item['id_agent']), true); - $label = str_replace('_agentgroup_', $agent_name, $label); - } + if (preg_match('/_agentgroup_/', $label)) { + $label = str_replace( + '_agentgroup_', + $item['agent_group'], + $label + ); + } - if (preg_match('/_address_/', $label)) { - $agent_name = agents_get_address($item['id_agent']); - $label = str_replace('_address_', $agent_name, $label); - } - break; + if (preg_match('/_address_/', $label)) { + $label = str_replace( + '_address_', + $item['agent_address'], + $label + ); + } - case 'simple_graph': - case 'module_histogram_graph': - case 'custom_graph': - case 'simple_baseline_graph': - case 'event_report_module': - case 'alert_report_module': - case 'historical_data': - case 'sumatory': - case 'database_serialized': - case 'monitor_report': - case 'min_value': - case 'max_value': - case 'avg_value': - case 'projection_graph': - case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': - case 'automatic_graph': - if (preg_match('/_agent_/', $label)) { - if (isset($item['agents']) && count($item['agents']) > 1) { - $agent_name = count($item['agents']).__(' agents'); - } else { - $agent_name = agents_get_alias($item['id_agent']); - } + if (preg_match('/_module_/', $label)) { + $label = str_replace( + '_module_', + $item['module_name'], + $label + ); + } - $label = str_replace('_agent_', $agent_name, $label); - } - - if (preg_match('/_agentdescription_/', $label)) { - if (count($item['agents']) > 1) { - $agent_name = ''; - } else { - $agent_name = agents_get_description($item['id_agent']); - } - - $label = str_replace('_agentdescription_', $agent_name, $label); - } - - if (preg_match('/_agentgroup_/', $label)) { - if (count($item['agents']) > 1) { - $agent_name = ''; - } else { - $agent_name = groups_get_name(agents_get_agent_group($item['id_agent']), true); - } - - $label = str_replace('_agentgroup_', $agent_name, $label); - } - - if (preg_match('/_address_/', $label)) { - if (count($item['agents']) > 1) { - $agent_name = ''; - } else { - $agent_name = agents_get_address($item['id_agent']); - } - - $label = str_replace('_address_', $agent_name, $label); - } - - if (preg_match('/_module_/', $label)) { - if ($item['modules'] > 1) { - $module_name = $item['modules'].__(' modules'); - } else { - $module_name = modules_get_agentmodule_name($item['id_agent_module']); - } - - $label = str_replace('_module_', $module_name, $label); - } - - if (preg_match('/_moduledescription_/', $label)) { - if ($item['modules'] > 1) { - $module_description = ''; - } else { - $module_description = modules_get_agentmodule_descripcion($item['id_agent_module']); - } - - $label = str_replace('_moduledescription_', $module_description, $label); - } - break; + if (preg_match('/_moduledescription_/', $label)) { + $label = str_replace( + '_moduledescription_', + $item['module_description'], + $label + ); } return $label; } +/** + * Convert macro in sql string to value + * + * @param array $report + * @param string $sql + * + * @return string + */ +function reporting_sql_macro(array $report, string $sql): string +{ + if (preg_match('/_timefrom_/', $sql)) { + $sql = str_replace( + '_timefrom_', + $report['datetime'], + $sql + ); + } + + return $sql; +} + + /** * @brief Calculates the SLA compliance value given an sla array * diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 10bef8631f..6a7d60c620 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -107,9 +107,15 @@ function html_do_report_info($report) { global $config; + if ($config['style'] === 'pandora_black') { + $background_color = '#222'; + } else { + $background_color = '#f5f5f5'; + } + $date_today = date($config['date_format']); - $html = '
+ $html = '
@@ -135,6 +141,15 @@ function html_do_report_info($report) } +/** + * Print html report. + * + * @param array $report Info. + * @param boolean $mini Type. + * @param integer $report_info Show info. + * + * @return array + */ function reporting_html_print_report($report, $mini=false, $report_info=1) { if ($report_info == 1) { @@ -155,7 +170,38 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) $table->rowstyle = []; if (isset($item['label']) && $item['label'] != '') { - $label = reporting_label_macro($item, $item['label']); + $id_agent = $item['id_agent']; + $id_agent_module = $item['id_agent_module']; + + // Add macros name. + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module + ); + + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + + $items_label = [ + 'type' => $item['type'], + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'agent_description' => $agent_description, + 'agent_group' => $agent_group, + 'agent_address' => $agent_address, + 'agent_alias' => $agent_alias, + 'module_name' => $module_name, + 'module_description' => $module_description, + ]; + + $label = reporting_label_macro( + $items_label, + $item['label'] + ); } else { $label = ''; } @@ -174,7 +220,10 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) $table->data['description_row']['description'] = $item['description']; - if ($item['type'] == 'event_report_agent' || $item['type'] == 'event_report_group' || $item['type'] == 'event_report_module') { + if ($item['type'] == 'event_report_agent' + || $item['type'] == 'event_report_group' + || $item['type'] == 'event_report_module' + ) { $table->data['count_row']['count'] = 'Total events: '.$item['total_events']; } @@ -753,7 +802,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) $table1->size[10] = '2%'; $table1->data[0][10] = ''; $table1->size[11] = '15%'; - $table1->data[0][11] = ''.__('Ignore time').''; + $table1->data[0][11] = ''.__('Planned Downtime').''; if ($pdf === 0) { $table->colspan['legend']['cell'] = 2; @@ -3252,53 +3301,111 @@ function reporting_html_availability_graph($table, $item, $pdf=0) $tables_chart = ''; - $table1 = new stdClass(); - $table1->width = '99%'; - $table1->data = []; - $table1->size = []; - $table1->size[0] = '10%'; - $table1->size[1] = '80%'; - $table1->size[2] = '5%'; - $table1->size[3] = '5%'; - foreach ($item['charts'] as $chart) { - $checks_resume = ''; - $sla_value = ''; - if (reporting_sla_is_not_init_from_array($chart)) { - $color = COL_NOTINIT; - $sla_value = __('Not init'); - } else if (reporting_sla_is_ignored_from_array($chart)) { - $color = COL_IGNORED; - $sla_value = __('No data'); - } else { - switch ($chart['sla_status']) { - case REPORT_STATUS_ERR: - $color = COL_CRITICAL; - break; + if (isset($item['failed']) === true && empty($item['failed']) === false) { + $tables_chart .= $item['failed']; + } else { + foreach ($item['charts'] as $k_chart => $chart) { + $checks_resume = ''; + $sla_value = ''; + if (reporting_sla_is_not_init_from_array($chart)) { + $color = COL_NOTINIT; + $sla_value = __('Not init'); + } else if (reporting_sla_is_ignored_from_array($chart)) { + $color = COL_IGNORED; + $sla_value = __('No data'); + } else { + switch ($chart['sla_status']) { + case REPORT_STATUS_ERR: + $color = COL_CRITICAL; + break; - case REPORT_STATUS_OK: - $color = COL_NORMAL; - break; + case REPORT_STATUS_OK: + $color = COL_NORMAL; + break; - default: - $color = COL_UNKNOWN; - break; + default: + $color = COL_UNKNOWN; + break; + } + + $sla_value = sla_truncate( + $chart['sla_value'], + $config['graph_precision'] + ).'%'; + $checks_resume = '('.$chart['checks_ok'].'/'.$chart['checks_total'].')'; } - $sla_value = sla_truncate( - $chart['sla_value'], - $config['graph_precision'] - ).'%'; - $checks_resume = '('.$chart['checks_ok'].'/'.$chart['checks_total'].')'; - } + // Check failover availability report. + if ($item['data'][$k_chart]['failover'] === '') { + $table1 = new stdClass(); + $table1->width = '99%'; + $table1->data = []; + $table1->size = []; + $table1->size[0] = '10%'; + $table1->size[1] = '80%'; + $table1->size[2] = '5%'; + $table1->size[3] = '5%'; + $table1->data[0][0] = $chart['agent'].'
'.$chart['module']; + $table1->data[0][1] = $chart['chart']; + $table1->data[0][2] = "".$sla_value.''; + $table1->data[0][3] = $checks_resume; + $tables_chart .= html_print_table( + $table1, + true + ); + } else { + if ($item['data'][$k_chart]['failover'] === 'primary' + || $item['failover_type'] == REPORT_FAILOVER_TYPE_SIMPLE + ) { + $table1 = new stdClass(); + $table1->width = '99%'; + $table1->data = []; + $table1->size = []; + $table1->size[0] = '10%'; + $table1->size[1] = '80%'; + $table1->size[2] = '5%'; + $table1->size[3] = '5%'; + } - $table1->data[0][0] = $chart['agent'].'
'.$chart['module']; - $table1->data[0][1] = $chart['chart']; - $table1->data[0][2] = "".$sla_value.''; - $table1->data[0][3] = $checks_resume; - $tables_chart .= html_print_table( - $table1, - true - ); + $title = ''; + $checks_resume_text = $checks_resume; + $sla_value_text = "".$sla_value.''; + switch ($item['data'][$k_chart]['failover']) { + case 'primary': + $title = ''.__('Primary').''; + $title .= '
'.$chart['agent']; + $title .= '
'.$chart['module']; + break; + + case (preg_match('/failover.*/', $item['data'][$k_chart]['failover']) ? true : false): + $title = ''.__('Failover').''; + $title .= '
'.$chart['agent']; + $title .= '
'.$chart['module']; + break; + + case 'result': + default: + $title = ''.__('Result').''; + $sla_value_text = "".$sla_value.''; + $checks_resume_text = ''; + $checks_resume_text .= $checks_resume; + $checks_resume_text .= ''; + break; + } + + $table1->data[$item['data'][$k_chart]['failover']][0] = $title; + $table1->data[$item['data'][$k_chart]['failover']][1] = $chart['chart']; + $table1->data[$item['data'][$k_chart]['failover']][2] = $sla_value_text; + $table1->data[$item['data'][$k_chart]['failover']][3] = $checks_resume_text; + + if ($item['data'][$k_chart]['failover'] === 'result') { + $tables_chart .= html_print_table( + $table1, + true + ); + } + } + } } if ($item['type'] == 'availability_graph') { @@ -3335,7 +3442,7 @@ function reporting_html_availability_graph($table, $item, $pdf=0) $table2->size[10] = '2%'; $table2->data[0][10] = ''; $table2->size[11] = '15%'; - $table2->data[0][11] = ''.__('Ignore time').''; + $table2->data[0][11] = ''.__('Planned Downtime').''; } if ($pdf !== 0) { @@ -3496,7 +3603,8 @@ function reporting_html_general($table, $item, $pdf=0) $table1->head = array_merge([__('Agent')], $list_modules); foreach ($item['data'] as $agent => $modules) { $row = []; - $row['agent'] = $agent; + $alias = agents_get_alias_by_name($agent); + $row['agent'] = $alias; $table1->style['agent'] = 'text-align: center;'; foreach ($list_modules as $name) { $table1->style[$name] = 'text-align: center;'; @@ -4270,16 +4378,16 @@ function reporting_get_agents_by_status($data, $graph_width=250, $graph_height=1 $agent_data = []; $agent_data[0] = html_print_image('images/agent_critical.png', true, ['title' => __('Agents critical')]); - $agent_data[1] = "".format_numeric($data['agent_critical']).''; + $agent_data[1] = "".format_numeric($data['agent_critical']).''; $agent_data[2] = html_print_image('images/agent_warning.png', true, ['title' => __('Agents warning')]); - $agent_data[3] = "".format_numeric($data['agent_warning']).''; + $agent_data[3] = "".format_numeric($data['agent_warning']).''; $table_agent->data[] = $agent_data; $agent_data = []; $agent_data[0] = html_print_image('images/agent_ok.png', true, ['title' => __('Agents ok')]); - $agent_data[1] = "".format_numeric($data['agent_ok']).''; + $agent_data[1] = "".format_numeric($data['agent_ok']).''; $agent_data[2] = html_print_image('images/agent_unknown.png', true, ['title' => __('Agents unknown')]); $agent_data[3] = "".format_numeric($data['agent_unknown']).''; @@ -4367,13 +4475,13 @@ function reporting_get_events($data, $links=false) } if (defined('METACONSOLE')) { - $table_events->style[0] = 'background-color:#FC4444'; + $table_events->style[0] = 'background-color:#e63c52'; $table_events->data[0][0] = html_print_image('images/module_event_critical.png', true, ['title' => __('Critical events')]); $table_events->data[0][0] .= '   '."".format_numeric($data['critical']).''; - $table_events->style[1] = 'background-color:#FAD403'; + $table_events->style[1] = 'background-color:#f3b200'; $table_events->data[0][1] = html_print_image('images/module_event_warning.png', true, ['title' => __('Warning events')]); $table_events->data[0][1] .= '   '."".format_numeric($data['warning']).''; - $table_events->style[2] = 'background-color:#80BA27'; + $table_events->style[2] = 'background-color:#82b92e'; $table_events->data[0][2] = html_print_image('images/module_event_ok.png', true, ['title' => __('OK events')]); $table_events->data[0][2] .= '   '."".format_numeric($data['normal']).''; $table_events->style[3] = 'background-color:#B2B2B2'; @@ -4381,11 +4489,11 @@ function reporting_get_events($data, $links=false) $table_events->data[0][3] .= '   '."".format_numeric($data['unknown']).''; } else { $table_events->data[0][0] = html_print_image('images/module_critical.png', true, ['title' => __('Critical events')]); - $table_events->data[0][0] .= '   '."".format_numeric($data['critical']).''; + $table_events->data[0][0] .= '   '."".format_numeric($data['critical']).''; $table_events->data[0][1] = html_print_image('images/module_warning.png', true, ['title' => __('Warning events')]); - $table_events->data[0][1] .= '   '."".format_numeric($data['warning']).''; + $table_events->data[0][1] .= '   '."".format_numeric($data['warning']).''; $table_events->data[0][2] = html_print_image('images/module_ok.png', true, ['title' => __('OK events')]); - $table_events->data[0][2] .= '   '."".format_numeric($data['normal']).''; + $table_events->data[0][2] .= '   '."".format_numeric($data['normal']).''; $table_events->data[0][3] = html_print_image('images/module_unknown.png', true, ['title' => __('Unknown events')]); $table_events->data[0][3] .= '   '."".format_numeric($data['unknown']).''; } diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index 0850dcbfac..4049df62c9 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -32,9 +32,9 @@ require_once __DIR__.'/constants.php'; /** * Get a server. * - * @param int Server id to get. - * @param array Extra filter. - * @param array Fields to get. + * @param integer $id_server Server id to get. + * @param array $filter Extra filter. + * @param array $fields Fields to get. * * @return Server with the given id. False if not available. */ @@ -61,7 +61,12 @@ function servers_get_server($id_server, $filter=false, $fields=false) */ function servers_get_names() { - $all_servers = @db_get_all_rows_filter('tserver', false, ['DISTINCT(name) as name']); + $all_servers = db_get_all_rows_sql( + 'SELECT DISTINCT(`name`) as name + FROM tserver + WHERE server_type <> 13' + ); + if ($all_servers === false) { return []; } @@ -76,7 +81,11 @@ function servers_get_names() /** - * This function forces a recon task to be queued by the server asap + * This function forces a recon task to be queued by the server asap. + * + * @param integer $id_recon_task Id. + * + * @return void */ function servers_force_recon_task($id_recon_task) { @@ -141,9 +150,10 @@ function servers_get_total_modules() /** - * This function will get several metrics from the database to get info about server performance + * This function will get several metrics from the database + * to get info about server performance. * - * @return array with several data + * @return array with several data. */ function servers_get_performance() { @@ -161,18 +171,20 @@ function servers_get_performance() if ($config['realtimestats'] == 1) { $counts = db_get_all_rows_sql( - ' - SELECT tagente_modulo.id_modulo, + 'SELECT tagente_modulo.id_modulo, COUNT(tagente_modulo.id_agente_modulo) modules FROM tagente_modulo, tagente_estado, tagente WHERE tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 AND delete_pending = 0 - AND (utimestamp > 0 OR (id_tipo_modulo = 100 OR (id_tipo_modulo > 21 AND id_tipo_modulo < 23))) + AND (utimestamp > 0 + OR (id_tipo_modulo = 100 + OR (id_tipo_modulo > 21 + AND id_tipo_modulo < 23) + ) + ) AND tagente.disabled = 0 - GROUP BY tagente_modulo.id_modulo' ); @@ -205,6 +217,10 @@ function servers_get_performance() case MODULE_WEB: $data['total_web_modules'] = $c['modules']; break; + + default: + // Not possible. + break; } if ($c['id_modulo'] != MODULE_DATA) { @@ -259,6 +275,8 @@ function servers_get_performance() case SERVER_TYPE_EVENT: case SERVER_TYPE_DISCOVERY: case SERVER_TYPE_SYSLOG: + default: + // Nothing. break; } @@ -272,17 +290,22 @@ function servers_get_performance() $interval_avgs = []; - // Avg of modules interval when modules have module_interval > 0 + // Avg of modules interval when modules have module_interval > 0. $interval_avgs_modules = db_get_all_rows_sql( - ' - SELECT count(tagente_modulo.id_modulo) modules , + 'SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente_modulo.module_interval) avg_interval FROM tagente_modulo, tagente_estado, tagente WHERE tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_modulo.disabled = 0 AND module_interval > 0 - AND (utimestamp > 0 OR (id_tipo_modulo = 100 OR (id_tipo_modulo > 21 AND id_tipo_modulo < 23))) + AND (utimestamp > 0 OR ( + id_tipo_modulo = 100 + OR (id_tipo_modulo > 21 + AND id_tipo_modulo < 23 + ) + ) + ) AND delete_pending = 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -293,16 +316,15 @@ function servers_get_performance() $interval_avgs_modules = []; } - // Transform into a easily format + // Transform into a easily format. foreach ($interval_avgs_modules as $iamodules) { $interval_avgs[$iamodules['id_modulo']]['avg_interval'] = $iamodules['avg_interval']; $interval_avgs[$iamodules['id_modulo']]['modules'] = $iamodules['modules']; } - // Avg of agents interval when modules have module_interval == 0 + // Avg of agents interval when modules have module_interval == 0. $interval_avgs_agents = db_get_all_rows_sql( - ' - SELECT count(tagente_modulo.id_modulo) modules , + 'SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente.intervalo) avg_interval FROM tagente_modulo, tagente_estado, tagente WHERE tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo @@ -319,50 +341,89 @@ function servers_get_performance() $interval_avgs_agents = []; } - // Merge with the previous calculated array + // Merge with the previous calculated array. foreach ($interval_avgs_agents as $iaagents) { if (!isset($interval_avgs[$iaagents['id_modulo']]['modules'])) { $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = $iaagents['avg_interval']; $interval_avgs[$iaagents['id_modulo']]['modules'] = $iaagents['modules']; } else { - $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval($interval_avgs[$iaagents['id_modulo']], $iaagents); + $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval( + $interval_avgs[$iaagents['id_modulo']], + $iaagents + ); $interval_avgs[$iaagents['id_modulo']]['modules'] += $iaagents['modules']; } } + $info_servers = array_reduce( + servers_get_info(), + function ($carry, $item) { + $carry[$item['server_type']] = $item; + return $carry; + } + ); foreach ($interval_avgs as $id_modulo => $ia) { + $module_lag = 0; switch ($id_modulo) { case MODULE_DATA: + $module_lag = $info_servers[SERVER_TYPE_DATA]['module_lag']; $data['avg_interval_local_modules'] = $ia['avg_interval']; - $data['local_modules_rate'] = servers_get_rate($data['avg_interval_local_modules'], $data['total_local_modules']); + $data['local_modules_rate'] = servers_get_rate( + $data['avg_interval_local_modules'], + ($data['total_local_modules'] - $module_lag) + ); break; case MODULE_NETWORK: + $module_lag = $info_servers[SERVER_TYPE_NETWORK]['module_lag']; + $module_lag += $info_servers[SERVER_TYPE_SNMP]['module_lag']; + $module_lag += $info_servers[SERVER_TYPE_ENTERPRISE_ICMP]['module_lag']; + $module_lag += $info_servers[SERVER_TYPE_ENTERPRISE_SNMP]['module_lag']; $data['avg_interval_network_modules'] = $ia['avg_interval']; $data['network_modules_rate'] = servers_get_rate( $data['avg_interval_network_modules'], - $data['total_network_modules'] + ($data['total_network_modules'] - $module_lag) ); break; case MODULE_PLUGIN: + $module_lag = $info_servers[SERVER_TYPE_PLUGIN]['module_lag']; $data['avg_interval_plugin_modules'] = $ia['avg_interval']; - $data['plugin_modules_rate'] = servers_get_rate($data['avg_interval_plugin_modules'], $data['total_plugin_modules']); + $data['plugin_modules_rate'] = servers_get_rate( + $data['avg_interval_plugin_modules'], + ($data['total_plugin_modules'] - $module_lag) + ); break; case MODULE_PREDICTION: + $module_lag = $info_servers[SERVER_TYPE_PREDICTION]['module_lag']; $data['avg_interval_prediction_modules'] = $ia['avg_interval']; - $data['prediction_modules_rate'] = servers_get_rate($data['avg_interval_prediction_modules'], $data['total_prediction_modules']); + $data['prediction_modules_rate'] = servers_get_rate( + $data['avg_interval_prediction_modules'], + ($data['total_prediction_modules'] - $module_lag) + ); break; case MODULE_WMI: + $module_lag = $info_servers[SERVER_TYPE_WMI]['module_lag']; $data['avg_interval_wmi_modules'] = $ia['avg_interval']; - $data['wmi_modules_rate'] = servers_get_rate($data['avg_interval_wmi_modules'], $data['total_wmi_modules']); + $data['wmi_modules_rate'] = servers_get_rate( + $data['avg_interval_wmi_modules'], + ($data['total_wmi_modules'] - $module_lag) + ); break; case MODULE_WEB: + $module_lag = $info_servers[SERVER_TYPE_WEB]['module_lag']; $data['avg_interval_web_modules'] = $ia['avg_interval']; - $data['web_modules_rate'] = servers_get_rate($data['avg_interval_web_modules'], $data['total_web_modules']); + $data['web_modules_rate'] = servers_get_rate( + $data['avg_interval_web_modules'], + ($data['total_web_modules'] - $module_lag) + ); + break; + + default: + // Not possible. break; } @@ -385,25 +446,55 @@ function servers_get_performance() $data['avg_interval_total_modules'] = (array_sum($data['avg_interval_total_modules']) / count($data['avg_interval_total_modules'])); } - $data['remote_modules_rate'] = servers_get_rate($data['avg_interval_remote_modules'], $data['total_remote_modules']); - $data['total_modules_rate'] = servers_get_rate($data['avg_interval_total_modules'], $data['total_modules']); + $total_modules_lag = 0; + foreach ($info_servers as $key => $value) { + switch ($key) { + case SERVER_TYPE_DATA: + case SERVER_TYPE_NETWORK: + case SERVER_TYPE_SNMP: + case SERVER_TYPE_ENTERPRISE_ICMP: + case SERVER_TYPE_ENTERPRISE_SNMP: + case SERVER_TYPE_PLUGIN: + case SERVER_TYPE_PREDICTION: + case SERVER_TYPE_WMI: + case SERVER_TYPE_WEB: + $total_modules_lag += $value['module_lag']; + break; + + default: + // Not possible. + break; + } + } + + $data['remote_modules_rate'] = servers_get_rate( + $data['avg_interval_remote_modules'], + $data['total_remote_modules'] + ); + + $data['total_modules_rate'] = servers_get_rate( + $data['avg_interval_total_modules'], + ($data['total_modules'] - $total_modules_lag) + ); return ($data); } /** - * Get avg interval + * Get avg interval. * - * @param mixed Array with avg and count data of first part - * @param mixed Array with avg and count data of second part + * @param array $modules_avg_interval1 Array with avg and count + * data of first part. + * @param array $modules_avg_interval2 Array with avg and count + * data of second part. * - * @return float number of avg modules between two parts + * @return float number of avg modules between two parts. */ - - -function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2) -{ +function servers_get_avg_interval( + $modules_avg_interval1, + $modules_avg_interval2 +) { $total_modules = ($modules_avg_interval1['modules'] + $modules_avg_interval2['modules']); $parcial1 = ($modules_avg_interval1['avg_interval'] * $modules_avg_interval1['modules']); @@ -416,21 +507,23 @@ function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2 /** * Get server rate * - * @param float avg of interval of these modules - * @param int number of modules + * @param float $avg_interval Avg of interval of these modules. + * @param integer $num_modules Number of modules. * * @return float number of modules processed by second */ function servers_get_rate($avg_interval, $num_modules) { - return $avg_interval > 0 ? ($num_modules / $avg_interval) : 0; + return ($avg_interval > 0) ? ($num_modules / $avg_interval) : 0; } /** - * This function will get all the server information in an array or a specific server + * This function will get all the server information in an array + * or a specific server. * - * @param mixed An optional integer or array of integers to select specific servers + * @param integer $id_server An optional integer or array of integers + * to select specific servers. * * @return mixed False in case the server doesn't exist or an array with info. */ @@ -461,127 +554,211 @@ function servers_get_info($id_server=-1) foreach ($result as $server) { switch ($server['server_type']) { case SERVER_TYPE_DATA: - $server['img'] = html_print_image('images/data.png', true, ['title' => __('Data server')]); + $server['img'] = html_print_image( + 'images/data.png', + true, + ['title' => __('Data server')] + ); $server['type'] = 'data'; $id_modulo = 1; break; case SERVER_TYPE_NETWORK: - $server['img'] = html_print_image('images/network.png', true, ['title' => __('Network server')]); + $server['img'] = html_print_image( + 'images/network.png', + true, + ['title' => __('Network server')] + ); $server['type'] = 'network'; $id_modulo = 2; break; case SERVER_TYPE_SNMP: - $server['img'] = html_print_image('images/snmp.png', true, ['title' => __('SNMP Trap server')]); + $server['img'] = html_print_image( + 'images/snmp.png', + true, + ['title' => __('SNMP Trap server')] + ); $server['type'] = 'snmp'; $id_modulo = 0; break; case SERVER_TYPE_DISCOVERY: - $server['img'] = html_print_image('images/recon.png', true, ['title' => __('Discovery server')]); + $server['img'] = html_print_image( + 'images/recon.png', + true, + ['title' => __('Discovery server')] + ); $server['type'] = 'recon'; $id_modulo = 0; break; case SERVER_TYPE_PLUGIN: - $server['img'] = html_print_image('images/plugin.png', true, ['title' => __('Plugin server')]); + $server['img'] = html_print_image( + 'images/plugin.png', + true, + ['title' => __('Plugin server')] + ); $server['type'] = 'plugin'; $id_modulo = 4; break; case SERVER_TYPE_PREDICTION: - $server['img'] = html_print_image('images/chart_bar.png', true, ['title' => __('Prediction server')]); + $server['img'] = html_print_image( + 'images/chart_bar.png', + true, + ['title' => __('Prediction server')] + ); $server['type'] = 'prediction'; $id_modulo = 5; break; case SERVER_TYPE_WMI: - $server['img'] = html_print_image('images/wmi.png', true, ['title' => __('WMI server')]); + $server['img'] = html_print_image( + 'images/wmi.png', + true, + ['title' => __('WMI server')] + ); $server['type'] = 'wmi'; $id_modulo = 6; break; case SERVER_TYPE_EXPORT: - $server['img'] = html_print_image('images/server_export.png', true, ['title' => __('Export server')]); + $server['img'] = html_print_image( + 'images/server_export.png', + true, + ['title' => __('Export server')] + ); $server['type'] = 'export'; $id_modulo = 0; break; case SERVER_TYPE_INVENTORY: - $server['img'] = html_print_image('images/page_white_text.png', true, ['title' => __('Inventory server')]); + $server['img'] = html_print_image( + 'images/page_white_text.png', + true, + ['title' => __('Inventory server')] + ); $server['type'] = 'inventory'; $id_modulo = 0; break; case SERVER_TYPE_WEB: - $server['img'] = html_print_image('images/world.png', true, ['title' => __('Web server')]); + $server['img'] = html_print_image( + 'images/world.png', + true, + ['title' => __('Web server')] + ); $server['type'] = 'web'; $id_modulo = 0; break; case SERVER_TYPE_EVENT: - $server['img'] = html_print_image('images/lightning_go.png', true, ['title' => __('Event server')]); + $server['img'] = html_print_image( + 'images/lightning_go.png', + true, + ['title' => __('Event server')] + ); $server['type'] = 'event'; $id_modulo = 2; break; case SERVER_TYPE_ENTERPRISE_ICMP: - $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise ICMP server')]); + $server['img'] = html_print_image( + 'images/network.png', + true, + ['title' => __('Enterprise ICMP server')] + ); $server['type'] = 'enterprise icmp'; $id_modulo = 2; break; case SERVER_TYPE_ENTERPRISE_SNMP: - $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise SNMP server')]); + $server['img'] = html_print_image( + 'images/network.png', + true, + ['title' => __('Enterprise SNMP server')] + ); $server['type'] = 'enterprise snmp'; $id_modulo = 2; break; case SERVER_TYPE_ENTERPRISE_SATELLITE: - $server['img'] = html_print_image('images/satellite.png', true, ['title' => __('Enterprise Satellite server')]); + $server['img'] = html_print_image( + 'images/satellite.png', + true, + ['title' => __('Enterprise Satellite server')] + ); $server['type'] = 'enterprise satellite'; $id_modulo = 0; break; case SERVER_TYPE_ENTERPRISE_TRANSACTIONAL: - $server['img'] = html_print_image('images/transactional_map.png', true, ['title' => __('Enterprise Transactional server')]); + $server['img'] = html_print_image( + 'images/transactional_map.png', + true, + ['title' => __('Enterprise Transactional server')] + ); $server['type'] = 'enterprise transactional'; $id_modulo = 0; break; case SERVER_TYPE_MAINFRAME: - $server['img'] = html_print_image('images/mainframe.png', true, ['title' => __('Mainframe server')]); + $server['img'] = html_print_image( + 'images/mainframe.png', + true, + ['title' => __('Mainframe server')] + ); $server['type'] = 'mainframe'; $id_modulo = 0; break; case SERVER_TYPE_SYNC: - $server['img'] = html_print_image('images/sync.png', true, ['title' => __('Sync server')]); + $server['img'] = html_print_image( + 'images/sync.png', + true, + ['title' => __('Sync server')] + ); $server['type'] = 'sync'; $id_modulo = 0; break; case SERVER_TYPE_WUX: - $server['img'] = html_print_image('images/icono-wux.png', true, ['title' => __('Wux server')]); + $server['img'] = html_print_image( + 'images/icono-wux.png', + true, + ['title' => __('Wux server')] + ); $server['type'] = 'wux'; $id_modulo = 0; break; case SERVER_TYPE_SYSLOG: - $server['img'] = html_print_image('images/syslog.png', true, ['title' => __('Syslog server')]); + $server['img'] = html_print_image( + 'images/syslog.png', + true, + ['title' => __('Log server')] + ); $server['type'] = 'syslog'; $id_modulo = 0; break; case SERVER_TYPE_AUTOPROVISION: - $server['img'] = html_print_image('images/autoprovision.png', true, ['title' => __('Autoprovision server')]); + $server['img'] = html_print_image( + 'images/autoprovision.png', + true, + ['title' => __('Autoprovision server')] + ); $server['type'] = 'autoprovision'; $id_modulo = 0; break; case SERVER_TYPE_MIGRATION: - $server['img'] = html_print_image('images/migration.png', true, ['title' => __('Migration server')]); + $server['img'] = html_print_image( + 'images/migration.png', + true, + ['title' => __('Migration server')] + ); $server['type'] = 'migration'; $id_modulo = 0; break; @@ -594,31 +771,54 @@ function servers_get_info($id_server=-1) } if ($config['realtimestats'] == 0) { - // --------------------------------------------------------------- - // Take data from database if not realtime stats - // --------------------------------------------------------------- - $server['lag'] = db_get_sql('SELECT lag_time FROM tserver WHERE id_server = '.$server['id_server']); - $server['module_lag'] = db_get_sql('SELECT lag_modules FROM tserver WHERE id_server = '.$server['id_server']); - $server['modules'] = db_get_sql('SELECT my_modules FROM tserver WHERE id_server = '.$server['id_server']); - $server['modules_total'] = db_get_sql('SELECT total_modules_running FROM tserver WHERE id_server = '.$server['id_server']); + // Take data from database if not realtime stats. + $server['lag'] = db_get_sql( + 'SELECT lag_time + FROM tserver + WHERE id_server = '.$server['id_server'] + ); + $server['module_lag'] = db_get_sql( + 'SELECT lag_modules + FROM tserver + WHERE id_server = '.$server['id_server'] + ); + $server['modules'] = db_get_sql( + 'SELECT my_modules + FROM tserver + WHERE id_server = '.$server['id_server'] + ); + $server['modules_total'] = db_get_sql( + 'SELECT total_modules_running + FROM tserver + WHERE id_server = '.$server['id_server'] + ); } else { - // --------------------------------------------------------------- - // Take data in realtime - // --------------------------------------------------------------- + // Take data in realtime. $server['module_lag'] = 0; $server['lag'] = 0; - // Inventory server + // Inventory server. if ($server['server_type'] == SERVER_TYPE_INVENTORY) { - // Get modules exported by this server - $server['modules'] = db_get_sql("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente AND tagente.server_name = '".$server['name']."'"); + // Get modules exported by this server. + $server['modules'] = db_get_sql( + "SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) + FROM tagente, tagent_module_inventory + WHERE tagente.disabled=0 + AND tagent_module_inventory.id_agente = tagente.id_agente + AND tagente.server_name = '".$server['name']."'" + ); - // Get total exported modules - $server['modules_total'] = db_get_sql('SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente'); + // Get total exported modules. + $server['modules_total'] = db_get_sql( + 'SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) + FROM tagente, tagent_module_inventory + WHERE tagente.disabled=0 + AND tagent_module_inventory.id_agente = tagente.id_agente' + ); $interval_esc = db_escape_key_identifier('interval'); - // Get the module lag + // Get the module lag. $server['module_lag'] = db_get_sql( 'SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) AS module_lag FROM tagente, tagent_module_inventory @@ -630,7 +830,7 @@ function servers_get_info($id_server=-1) AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc ); - // Get the lag + // Get the lag. $server['lag'] = db_get_sql( 'SELECT AVG(UNIX_TIMESTAMP() - utimestamp - tagent_module_inventory.'.$interval_esc.') FROM tagente, tagent_module_inventory @@ -641,162 +841,119 @@ function servers_get_info($id_server=-1) AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory.".$interval_esc.' * 10) AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc ); - // Export server + // Export server. } else if ($server['server_type'] == SERVER_TYPE_EXPORT) { - // Get modules exported by this server - $server['modules'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo, tserver_export WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export = tserver_export.id AND tserver_export.id_export_server = '.$server['id_server']); + // Get modules exported by this server. + $server['modules'] = db_get_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) + FROM tagente, tagente_modulo, tserver_export + WHERE tagente.disabled=0 + AND tagente_modulo.id_agente = tagente.id_agente + AND tagente_modulo.id_export = tserver_export.id + AND tserver_export.id_export_server = '.$server['id_server'] + ); - // Get total exported modules - $server['modules_total'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export != 0'); + // Get total exported modules. + $server['modules_total'] = db_get_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) + FROM tagente, tagente_modulo + WHERE tagente.disabled=0 + AND tagente_modulo.id_agente = tagente.id_agente + AND tagente_modulo.id_export != 0' + ); $server['lag'] = 0; $server['module_lag'] = 0; - } - // Discovery server - else if ($server['server_type'] == SERVER_TYPE_DISCOVERY) { + } else if ($server['server_type'] == SERVER_TYPE_DISCOVERY) { + // Discovery server. $server['name'] = ''.$server['name'].''; - // Total jobs running on this Discovery server + // Total jobs running on this Discovery server. $server['modules'] = db_get_sql( 'SELECT COUNT(id_rt) FROM trecon_task WHERE id_recon_server = '.$server['id_server'] ); - // Total recon jobs (all servers) - $server['modules_total'] = db_get_sql('SELECT COUNT(status) FROM trecon_task'); + // Total recon jobs (all servers). + $server['modules_total'] = db_get_sql( + 'SELECT COUNT(status) FROM trecon_task' + ); - // Lag (take average active time of all active tasks) + // Lag (take average active time of all active tasks). $server['module_lag'] = 0; - - switch ($config['dbtype']) { - case 'mysql': - $server['lag'] = db_get_sql('SELECT UNIX_TIMESTAMP() - utimestamp from trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); - - $server['module_lag'] = db_get_sql('SELECT COUNT(id_rt) FROM trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); - break; - - case 'postgresql': - $server['lag'] = db_get_sql("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp from trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); - - $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); - break; - - case 'oracle': - $server['lag'] = db_get_sql("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp from trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); - - $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); - break; - } + $server['lag'] = db_get_sql( + 'SELECT UNIX_TIMESTAMP() - utimestamp + FROM trecon_task + WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) + AND id_recon_server = '.$server['id_server'] + ); + $server['module_lag'] = db_get_sql( + 'SELECT COUNT(id_rt) + FROM trecon_task + WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) + AND id_recon_server = '.$server['id_server'] + ); } else { - // --------------------------------------------------------------- - // Data, Plugin, WMI, Network and Others - $server['modules'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = '.$server['id_server']); + // Data, Plugin, WMI, Network and Others. + $server['modules'] = db_get_sql( + 'SELECT count(tagente_estado.id_agente_modulo) + FROM tagente_estado, tagente_modulo, tagente + WHERE tagente.disabled=0 + AND tagente_modulo.id_agente = tagente.id_agente + AND tagente_modulo.disabled = 0 + AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo + AND tagente_estado.running_by = '.$server['id_server'] + ); - $server['modules_total'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tserver, tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = tserver.id_server AND tserver.server_type = '.$server['server_type']); + $server['modules_total'] = db_get_sql( + 'SELECT count(tagente_estado.id_agente_modulo) + FROM tserver, tagente_estado, tagente_modulo, tagente + WHERE tagente.disabled=0 + AND tagente_modulo.id_agente = tagente.id_agente + AND tagente_modulo.disabled = 0 + AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo + AND tagente_estado.running_by = tserver.id_server + AND tserver.server_type = '.$server['server_type'] + ); - // Remote servers LAG Calculation (server_type != 0) + // Remote servers LAG Calculation (server_type != 0). if ($server['server_type'] != 0) { - switch ($config['dbtype']) { - case 'mysql': - $result = db_get_row_sql( - 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND running_by = '.$server['id_server'].' - AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > current_interval' - ); - break; - - case 'postgresql': - $result = db_get_row_sql( - "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND running_by = ".$server['id_server']." - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > current_interval" - ); - break; - - case 'oracle': - $result = db_get_row_sql( - "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND running_by = '.$server['id_server']." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp) < ( current_interval * 10) - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) - utimestamp) * (".SECONDS_1DAY.')) > current_interval' - ); - break; - } + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, + AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag + FROM tagente_estado, tagente_modulo, tagente + WHERE utimestamp > 0 + AND tagente.disabled = 0 + AND tagente.id_agente = tagente_estado.id_agente + AND tagente_modulo.disabled = 0 + AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo + AND current_interval > 0 + AND running_by = '.$server['id_server'].' + AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) + AND (UNIX_TIMESTAMP() - utimestamp) > current_interval' + ); } else { - // Local/Dataserver server LAG calculation: - switch ($config['dbtype']) { - case 'mysql': - $result = db_get_row_sql( - 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_tipo_modulo < 5 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND running_by = '.$server['id_server'].' - AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)' - ); - break; - - case 'postgresql': - $result = db_get_row_sql( - "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_tipo_modulo < 5 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND running_by = ".$server['id_server']." - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > (current_interval * 1.1)" - ); - break; - - case 'oracle': - $result = db_get_row_sql( - "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente - WHERE utimestamp > 0 - AND tagente.disabled = 0 - AND tagente.id_agente = tagente_estado.id_agente - AND tagente_modulo.disabled = 0 - AND tagente_modulo.id_tipo_modulo < 5 - AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo - AND current_interval > 0 - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) < ( current_interval * 10) - AND running_by = '.$server['id_server']." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) > (current_interval * 1.1)' - ); - break; - } + // Local/Dataserver server LAG calculation. + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, + AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag + FROM tagente_estado, tagente_modulo, tagente + WHERE utimestamp > 0 + AND tagente.disabled = 0 + AND tagente.id_agente = tagente_estado.id_agente + AND tagente_modulo.disabled = 0 + AND tagente_modulo.id_tipo_modulo < 5 + AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo + AND current_interval > 0 + AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) + AND running_by = '.$server['id_server'].' + AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)' + ); } - // Lag over current_interval * 2 is not lag, it's a timed out module + // Lag over current_interval * 2 is not lag, + // it's a timed out module. if (!empty($result['lag'])) { $server['lag'] = $result['lag']; } @@ -805,28 +962,37 @@ function servers_get_info($id_server=-1) $server['module_lag'] = $result['module_lag']; } } - } //end if + } if (isset($server['module_lag'])) { - $server['lag_txt'] = ($server['lag'] == 0 ? '-' : human_time_description_raw($server['lag'])).' / '.$server['module_lag']; + $server['lag_txt'] = (($server['lag'] == 0) ? '-' : human_time_description_raw($server['lag'])).' / '.$server['module_lag']; } else { $server['lag_txt'] = ''; } if ($server['modules_total'] > 0) { - $server['load'] = round(($server['modules'] / $server['modules_total'] * 100)); + $server['load'] = round( + ($server['modules'] / $server['modules_total'] * 100) + ); } else { $server['load'] = 0; } - // Push the raw data on the return stack + // Push the raw data on the return stack. $return[$server['id_server']] = $server; - } //end foreach + } return $return; } +/** + * Get server type + * + * @param integer $type Type. + * + * @return array Result. + */ function servers_get_servers_type($type) { return db_get_all_rows_filter('tserver', ['server_type' => $type]); @@ -836,25 +1002,28 @@ function servers_get_servers_type($type) /** * Get the server name. * - * @param int Server id. + * @param integer $id_server Server id. * * @return string Name of the given server */ function servers_get_name($id_server) { - return (string) db_get_value('name', 'tserver', 'id_server', (int) $id_server); + return (string) db_get_value( + 'name', + 'tserver', + 'id_server', + (int) $id_server + ); } /** - * Get the presence of .conf and .md5 into remote_config dir + * Get the presence of .conf and .md5 into remote_config dir. * - * @param string Agent name + * @param string $server_name Agent name. * - * @return true if files exist and are writable + * @return true If files exist and are writable. */ - - function servers_check_remote_config($server_name) { global $config; @@ -862,8 +1031,12 @@ function servers_check_remote_config($server_name) $server_md5 = md5($server_name, false); $filenames = []; - $filenames['md5'] = io_safe_output($config['remote_config']).'/md5/'.$server_md5.'.srv.md5'; - $filenames['conf'] = io_safe_output($config['remote_config']).'/conf/'.$server_md5.'.srv.conf'; + $filenames['md5'] = io_safe_output( + $config['remote_config'] + ).'/md5/'.$server_md5.'.srv.md5'; + $filenames['conf'] = io_safe_output( + $config['remote_config'] + ).'/conf/'.$server_md5.'.srv.conf'; if (! isset($filenames['conf'])) { return false; @@ -881,14 +1054,15 @@ function servers_check_remote_config($server_name) /** - * Return a string containing image tag for a given target id (server) - * TODO: Make this print_servertype_icon and move to functions_ui.php. Make XHTML compatible. Make string translatable + * Return a string containing image tag for a given target id (server). + * TODO: Make this print_servertype_icon and move to functions_ui.php. + * Make XHTML compatible. Make string translatable. * - * @deprecated Use print_servertype_icon instead + * @param integer $id Server type id. * - * @param int Server type id + * @deprecated Use print_servertype_icon instead. * - * @return string Fully formatted IMG HTML tag with icon + * @return string Fully formatted IMG HTML tag with icon. */ function servers_show_type($id) { @@ -896,37 +1070,67 @@ function servers_show_type($id) switch ($id) { case 1: - return html_print_image('images/database.png', true, ['title' => get_product_name().' Data server']); + $return = html_print_image( + 'images/database.png', + true, + ['title' => get_product_name().' Data server'] + ); + break; - break; case 2: - return html_print_image('images/network.png', true, ['title' => get_product_name().' Network server']); + $return = html_print_image( + 'images/network.png', + true, + ['title' => get_product_name().' Network server'] + ); + break; - break; case 4: - return html_print_image('images/plugin.png', true, ['title' => get_product_name().' Plugin server']); + $return = html_print_image( + 'images/plugin.png', + true, + ['title' => get_product_name().' Plugin server'] + ); + break; - break; case 5: - return html_print_image('images/chart_bar.png', true, ['title' => get_product_name().' Prediction server']); + $return = html_print_image( + 'images/chart_bar.png', + true, + ['title' => get_product_name().' Prediction server'] + ); + break; - break; case 6: - return html_print_image('images/wmi.png', true, ['title' => get_product_name().' WMI server']); + $return = html_print_image( + 'images/wmi.png', + true, + ['title' => get_product_name().' WMI server'] + ); + break; - break; case 7: - return html_print_image('images/server_web.png', true, ['title' => get_product_name().' WEB server']); + $return = html_print_image( + 'images/server_web.png', + true, + ['title' => get_product_name().' WEB server'] + ); + break; - break; case 8: - return html_print_image('images/module-wux.png', true, ['title' => get_product_name().' WUX server']); + $return = html_print_image( + 'images/module-wux.png', + true, + ['title' => get_product_name().' WUX server'] + ); + break; - break; default: - return '--'; - break; + $return = '--'; + break; } + + return $return; } @@ -941,28 +1145,10 @@ function servers_check_status() { global $config; - switch ($config['dbtype']) { - case 'mysql': - $sql = 'SELECT COUNT(id_server) - FROM tserver - WHERE status = 1 - AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND'; - break; - - case 'postgresql': - $sql = "SELECT COUNT(id_server) - FROM tserver - WHERE status = 1 - AND keepalive > NOW() - INTERVAL 'server_keepalive*2 SECOND'"; - break; - - case 'oracle': - $sql = "SELECT COUNT(id_server) - FROM tserver - WHERE status = 1 - AND keepalive > systimestamp - INTERVAL 'server_keepalive*2' SECOND"; - break; - } + $sql = 'SELECT COUNT(id_server) + FROM tserver + WHERE status = 1 + AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND'; $status = (int) db_get_sql($sql); // Cast as int will assure a number value @@ -972,10 +1158,9 @@ function servers_check_status() /** - * @deprecated use servers_get_info instead * Get statistical information for a given server * - * @param int Server id to get status. + * @param integer $id_server Server id to get status. * * @return array Server info array */ @@ -1036,7 +1221,7 @@ function servers_get_server_string_name(int $server) return __('Discovery server'); case SERVER_TYPE_SYSLOG: - return __('Syslog server'); + return __('Log server'); case SERVER_TYPE_WUX: return __('WUX server'); diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php index ca2b2d055b..dc423481f2 100644 --- a/pandora_console/include/functions_snmp_browser.php +++ b/pandora_console/include/functions_snmp_browser.php @@ -96,7 +96,6 @@ function snmp_browser_get_html_tree( foreach ($tree['__LEAVES__'] as $level => $sub_level) { // Id used to expand leafs. $sub_id = time().rand(0, getrandmax()); - // Display the branch. $output .= '
  • '; @@ -174,7 +173,6 @@ function snmp_browser_get_html_tree( $last_array, $sufix, $checked, - $return, $descriptive_ids, $previous_id ); @@ -225,7 +223,6 @@ function snmp_browser_print_tree( $last_array, $sufix, $checked, - $return, $descriptive_ids, $previous_id ); @@ -597,7 +594,7 @@ function snmp_browser_print_oid( * * @return string The container div. */ -function snmp_browser_print_container($return=false, $width='100%', $height='500px', $display='') +function snmp_browser_print_container($return=false, $width='100%', $height='60%', $display='') { // Target selection $table = new stdClass(); @@ -756,10 +753,10 @@ function snmp_browser_print_container($return=false, $width='100%', $height='500 $output .= ''; $output .= '
    '; - $output .= ui_toggle(html_print_table($table2, true), __('Search options'), '', true, true); + $output .= ui_toggle(html_print_table($table2, true), __('Search options'), '', '', true, true); $output .= '
    '; // SNMP tree container @@ -773,7 +770,7 @@ function snmp_browser_print_container($return=false, $width='100%', $height='500 $output .= ''; $output .= ''; - $output .= '
    '; + $output .= '
    '; $output .= '
    '; $output .= ''; $output .= ''; diff --git a/pandora_console/include/functions_tactical.php b/pandora_console/include/functions_tactical.php index c10f194386..39f44a9beb 100644 --- a/pandora_console/include/functions_tactical.php +++ b/pandora_console/include/functions_tactical.php @@ -444,7 +444,7 @@ function tactical_monitor_fired_alerts($group_array, $strict_user=false, $id_gro WHERE tagente.id_grupo IN $group_clause_strict AND tagente_modulo.id_agente = tagente.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo - AND times_fired > 0 "; + AND times_fired > 0 AND talert_template_modules.disabled = 0"; $count = db_get_sql($sql); return $count; @@ -456,7 +456,7 @@ function tactical_monitor_fired_alerts($group_array, $strict_user=false, $id_gro WHERE tagente.id_grupo IN $group_clause AND tagente_modulo.id_agente = tagente.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo - AND times_fired > 0" + AND times_fired > 0 AND talert_template_modules.disabled = 0" ); } diff --git a/pandora_console/include/functions_tags.php b/pandora_console/include/functions_tags.php index 952677ce66..aad6d78efd 100644 --- a/pandora_console/include/functions_tags.php +++ b/pandora_console/include/functions_tags.php @@ -744,7 +744,9 @@ function tags_get_acl_tags( $query_table='', $meta=false, $childrens_ids=[], - $force_group_and_tag=false + $force_group_and_tag=false, + $id_grupo_table_pretag='', + $alt_id_grupo_table_pretag='' ) { global $config; @@ -814,7 +816,14 @@ function tags_get_acl_tags( case 'event_condition': // Return the condition of the tags for tevento table. - $condition = tags_get_acl_tags_event_condition($acltags, $meta, $force_group_and_tag); + $condition = tags_get_acl_tags_event_condition( + $acltags, + $meta, + $force_group_and_tag, + false, + $id_grupo_table_pretag, + $alt_id_grupo_table_pretag + ); if (!empty($condition)) { return " $query_prefix ".'('.$condition.')'; @@ -905,8 +914,14 @@ function tags_get_acl_tags_module_condition($acltags, $modules_table='', $force_ */ -function tags_get_acl_tags_event_condition($acltags, $meta=false, $force_group_and_tag=false, $force_equal=false) -{ +function tags_get_acl_tags_event_condition( + $acltags, + $meta=false, + $force_group_and_tag=false, + $force_equal=false, + $id_grupo_table_pretag='', + $alt_id_grupo_table_pretag='' +) { global $config; $condition = []; @@ -923,7 +938,7 @@ function tags_get_acl_tags_event_condition($acltags, $meta=false, $force_group_a // Group condition (The module belongs to an agent of the group X) // $group_condition = sprintf('id_grupo IN (%s)', implode(',', array_values(groups_get_id_recursive($group_id, true))));. - $group_condition = "(id_grupo = $group_id OR id_group = $group_id)"; + $group_condition = '('.$id_grupo_table_pretag.'id_grupo = '.$group_id.' OR '.$alt_id_grupo_table_pretag.'id_group = '.$group_id.')'; // Tags condition (The module has at least one of the restricted tags). $tags_condition = ''; @@ -959,7 +974,7 @@ function tags_get_acl_tags_event_condition($acltags, $meta=false, $force_group_a } $in_group = implode(',', $without_tags); - $condition .= sprintf('(id_grupo IN (%s) OR id_group IN (%s))', $in_group, $in_group); + $condition .= sprintf('('.$id_grupo_table_pretag.'id_grupo IN (%s) OR '.$alt_id_grupo_table_pretag.'id_group IN (%s))', $in_group, $in_group); } $condition = !empty($condition) ? "($condition)" : ''; @@ -1097,6 +1112,12 @@ function tags_get_user_tags($id_user=false, $access='AR', $return_tag_any=false) if (empty($user_tags_id)) { $user_tags_id = $t; } else { + if (empty($t)) { + // Empty is 'all of them'. + // TODO: Review this... + $t = []; + } + $user_tags_id = array_unique(array_merge($t, $user_tags_id)); } } diff --git a/pandora_console/include/functions_treeview.php b/pandora_console/include/functions_treeview.php index 5341424efa..c8b893c091 100755 --- a/pandora_console/include/functions_treeview.php +++ b/pandora_console/include/functions_treeview.php @@ -327,7 +327,7 @@ function treeview_printModuleTable($id_module, $server_data=false, $no_head=fals if ($user_access_node && check_acl($config['id_user'], $id_group, 'AW')) { // Actions table - echo '
    '; + echo '
    '; echo ''; html_print_submit_button(__('Go to module edition'), 'upd_button', false, 'class="sub config"'); echo ''; @@ -637,7 +637,13 @@ function treeview_printTable($id_agente, $server_data=[], $no_head=false) $row = []; $row['title'] = __('Next agent contact'); - $row['data'] = progress_bar($progress, 150, 20); + $row['data'] = ui_progress( + $progress, + '100%', + '1.5', + '#82b92e', + true + ); $table->data['next_contact'] = $row; // End of table @@ -664,7 +670,7 @@ function treeview_printTable($id_agente, $server_data=[], $no_head=false) $agent_table .= '
    '; // print agent data toggle - ui_toggle($agent_table, __('Agent data'), '', false); + ui_toggle($agent_table, __('Agent data'), '', '', false); // Advanced data $table = new StdClass(); diff --git a/pandora_console/include/functions_ui.php b/pandora_console/include/functions_ui.php index c81148b9c9..008c05b8d7 100755 --- a/pandora_console/include/functions_ui.php +++ b/pandora_console/include/functions_ui.php @@ -48,15 +48,16 @@ if (isset($config['homedir'])) { */ function ui_bbcode_to_html($text, $allowed_tags=['[url]']) { - $return = $text; - if (array_search('[url]', $allowed_tags) !== false) { - $return = preg_replace( - '/\[url=([^\]]*)\]/', - '', - $return - ); - $return = str_replace('[/url]', '', $return); + // If link hasn't http, add it. + if (preg_match('/https?:\/\//', $text)) { + $html_bbcode = '$2'; + } else { + $html_bbcode = '$2'; + } + + // Replace bbcode format [url=www.example.org] String [/url] with or without http and slashes + $return = preg_replace('/\[url(?|](((?:https?:\/\/)?[^[]+))|(?:=[\'"]?((?:https?:\/\/)?[^]]+?)[\'"]?)](.+?))\[\/url]/', $html_bbcode, $text); } return $return; @@ -760,6 +761,12 @@ function ui_print_os_icon( $subfolder .= '/so_big_icons'; } + if (is_metaconsole()) { + $no_in_meta = true; + } else { + $no_in_meta = false; + } + $icon = (string) db_get_value('icon_name', 'tconfig_os', 'id_os', (int) $id_os); $os_name = get_os_name($id_os); if (empty($icon)) { @@ -770,7 +777,7 @@ function ui_print_os_icon( $options, true, $relative, - false, + $no_in_meta, true ); } else { @@ -778,13 +785,13 @@ function ui_print_os_icon( } } else if ($apply_skin) { if ($only_src) { - $output = html_print_image('images/'.$subfolder.'/'.$icon, true, $options, true, $relative, false, true); + $output = html_print_image('images/'.$subfolder.'/'.$icon, true, $options, true, $relative, $no_in_meta, true); } else { if (!isset($options['title'])) { $options['title'] = $os_name; } - $output = html_print_image('images/'.$subfolder.'/'.$icon, true, $options, false, $relative, false, true); + $output = html_print_image('images/'.$subfolder.'/'.$icon, true, $options, false, $relative, $no_in_meta, true); } } else { // $output = "" . $os_name . ""; @@ -1441,11 +1448,16 @@ function ui_require_css_file($name, $path='include/styles/') if (! file_exists($filename) && ! file_exists($config['homedir'].'/'.$filename) + && ! file_exists($config['homedir'].'/'.ENTERPRISE_DIR.'/'.$filename) ) { return false; } - $config['css'][$name] = $filename; + if (is_metaconsole()) { + $config['css'][$name] = '/../../'.$filename; + } else { + $config['css'][$name] = $filename; + } return true; } @@ -1476,7 +1488,7 @@ function ui_require_javascript_file($name, $path='include/javascript/', $echo_ta $filename = $path.$name.'.js'; if ($echo_tag) { - echo ''; + echo ''; return null; } @@ -1493,7 +1505,7 @@ function ui_require_javascript_file($name, $path='include/javascript/', $echo_ta return false; } - if (defined('METACONSOLE')) { + if (is_metaconsole()) { $config['js'][$name] = '../../'.$filename; } else { $config['js'][$name] = $filename; @@ -1738,11 +1750,18 @@ function ui_process_page_head($string, $bitfield) // Add the jquery UI styles CSS. $config['css']['jquery-UI'] = 'include/styles/js/jquery-ui.min.css'; + $config['css']['jquery-UI-custom'] = 'include/styles/js/jquery-ui_custom.css'; // Add the dialog styles CSS. $config['css']['dialog'] = 'include/styles/dialog.css'; // Add the dialog styles CSS. $config['css']['dialog'] = 'include/styles/js/introjs.css'; + // If the theme is the default, we don't load it twice. + if ($config['style'] !== 'pandora') { + // It loads the last of all. + $config['css']['theme'] = 'include/styles/'.$config['style'].'.css'; + } + // If skin's css files exists then add them. if ($exists_css) { foreach ($skin_styles as $filename => $name) { @@ -1754,9 +1773,10 @@ function ui_process_page_head($string, $bitfield) // User style should go last so it can rewrite common styles. $config['css'] = array_merge( [ - 'common' => 'include/styles/common.css', - 'menu' => 'include/styles/menu.css', - $config['style'] => 'include/styles/'.$config['style'].'.css', + 'common' => 'include/styles/common.css', + 'menu' => 'include/styles/menu.css', + 'tables' => 'include/styles/tables.css', + 'general' => 'include/styles/pandora.css', ], $config['css'] ); @@ -1775,7 +1795,7 @@ function ui_process_page_head($string, $bitfield) array_push($loaded, $name); - $url_css = ui_get_full_url($filename); + $url_css = ui_get_full_url($filename, false, false, false); $output .= ''."\n\t"; } @@ -1783,47 +1803,6 @@ function ui_process_page_head($string, $bitfield) * End load CSS */ - /* - * Load JS - */ - - if (empty($config['js'])) { - $config['js'] = []; - // If it's empty, false or not init set array to empty just in case. - } - - // Pandora specific JavaScript should go first. - $config['js'] = array_merge(['pandora' => 'include/javascript/pandora.js'], $config['js']); - // Load base64 javascript library. - $config['js']['base64'] = 'include/javascript/encode_decode_base64.js'; - // Load webchat javascript library. - $config['js']['webchat'] = 'include/javascript/webchat.js'; - // Load qrcode library. - $config['js']['qrcode'] = 'include/javascript/qrcode.js'; - // Load intro.js library (for bubbles and clippy). - $config['js']['intro'] = 'include/javascript/intro.js'; - $config['js']['clippy'] = 'include/javascript/clippy.js'; - // Load Underscore.js library. - $config['js']['underscore'] = 'include/javascript/underscore-min.js'; - - // Load other javascript. - // We can't load empty. - $loaded = ['']; - foreach ($config['js'] as $name => $filename) { - if (in_array($name, $loaded)) { - continue; - } - - array_push($loaded, $name); - - $url_js = ui_get_full_url($filename); - $output .= ''."\n\t"; - } - - /* - * End load JS - */ - /* * Load jQuery */ @@ -1873,7 +1852,7 @@ function ui_process_page_head($string, $bitfield) array_push($loaded, $name); - $url_js = ui_get_full_url($filename); + $url_js = ui_get_full_url($filename, false, false, false); $output .= ''."\n\t"; } @@ -1881,6 +1860,47 @@ function ui_process_page_head($string, $bitfield) * End load JQuery */ + /* + * Load JS + */ + + if (empty($config['js'])) { + $config['js'] = []; + // If it's empty, false or not init set array to empty just in case. + } + + // Pandora specific JavaScript should go first. + $config['js'] = array_merge(['pandora' => 'include/javascript/pandora.js'], $config['js']); + // Load base64 javascript library. + $config['js']['base64'] = 'include/javascript/encode_decode_base64.js'; + // Load webchat javascript library. + $config['js']['webchat'] = 'include/javascript/webchat.js'; + // Load qrcode library. + $config['js']['qrcode'] = 'include/javascript/qrcode.js'; + // Load intro.js library (for bubbles and clippy). + $config['js']['intro'] = 'include/javascript/intro.js'; + $config['js']['clippy'] = 'include/javascript/clippy.js'; + // Load Underscore.js library. + $config['js']['underscore'] = 'include/javascript/underscore-min.js'; + + // Load other javascript. + // We can't load empty. + $loaded = ['']; + foreach ($config['js'] as $name => $filename) { + if (in_array($name, $loaded)) { + continue; + } + + array_push($loaded, $name); + + $url_js = ui_get_full_url($filename, false, false, false); + $output .= ''."\n\t"; + } + + /* + * End load JS + */ + include_once __DIR__.'/graphs/functions_flot.php'; $output .= include_javascript_dependencies_flot_graph(true); @@ -2036,7 +2056,7 @@ function ui_pagination( $actual_page = floor($offset / $pagination); $ini_page = (floor($actual_page / $block_limit) * $block_limit); $end_page = ($ini_page + $block_limit - 1); - if ($end_page > $number_of_pages) { + if ($end_page >= $number_of_pages) { $end_page = ($number_of_pages - 1); } @@ -2585,12 +2605,12 @@ function ui_get_status_images_path() /** * Prints an image representing a status. * - * @param string $type Type. - * @param string $title Title. - * @param boolean $return Whether to return an output string or echo now (optional, echo by default). - * @param array $options Options to set image attributes: I.E.: style. - * @param string $path Path of the image, if not provided use the status path. - * @param boolean $rounded_image Round. + * @param string $type Type. + * @param string $title Title. + * @param boolean $return Whether to return an output string or echo now (optional, echo by default). + * @param array $options Options to set image attributes: I.E.: style. + * @param string $path Path of the image, if not provided use the status path. + * @param boolean $image_with_css Don't use an image. Draw an image with css styles. * * @return string HTML code if return parameter is true. */ @@ -2600,37 +2620,8 @@ function ui_print_status_image( $return=false, $options=false, $path=false, - $rounded_image=false + $image_with_css=false ) { - // This is for the List of Modules in Agent View. - if ($rounded_image === true) { - switch ($type) { - case 'module_ok.png': - $type = 'module_ok_rounded.png'; - break; - - case 'module_critical.png': - $type = 'module_critical_rounded.png'; - break; - - case 'module_warning.png': - $type = 'module_warning_rounded.png'; - break; - - case 'module_no_data.png': - $type = 'module_no_data_rounded.png'; - break; - - case 'module_unknown.png': - $type = 'module_unknown_rounded.png'; - break; - - default: - $type = $type; - break; - } - } - if ($path === false) { $imagepath_array = ui_get_status_images_path(); $imagepath = $imagepath_array[0]; @@ -2638,35 +2629,112 @@ function ui_print_status_image( $imagepath = $path; } - $imagepath .= '/'.$type; - - if ($options === false) { - $options = []; + if ($imagepath == 'images/status_sets/default') { + $image_with_css = true; } - $options['title'] = $title; + $imagepath .= '/'.$type; - return html_print_image($imagepath, $return, $options, false, false, false, true); + if ($image_with_css === true) { + $shape_status = get_shape_status_set($type); + return ui_print_status_sets($type, $title, $return, $shape_status); + } else { + if ($options === false) { + $options = []; + } + + $options['title'] = $title; + + return html_print_image($imagepath, $return, $options, false, false, false, true); + } +} + + +/** + * Get the shape of an image by assigning it a CSS class. Prints an image with CSS representing a status. + * + * @param string $type Module/Agent/Alert status. + * + * @return array With CSS class. + */ +function get_shape_status_set($type) +{ + switch ($type) { + // Small rectangles. + case STATUS_ALERT_NOT_FIRED: + case STATUS_ALERT_FIRED: + case STATUS_ALERT_DISABLED: + $return = ['class' => 'status_small_rectangles']; + break; + + // Rounded rectangles. + case STATUS_MODULE_OK: + case STATUS_AGENT_OK: + case STATUS_MODULE_NO_DATA: + case STATUS_AGENT_NO_DATA: + case STATUS_MODULE_CRITICAL: + case STATUS_AGENT_CRITICAL: + case STATUS_MODULE_WARNING: + case STATUS_AGENT_WARNING: + case STATUS_MODULE_UNKNOWN: + case STATUS_AGENT_UNKNOWN: + case STATUS_AGENT_DOWN: + $return = ['class' => 'status_rounded_rectangles']; + break; + + // Small squares. + case STATUS_SERVER_OK: + case STATUS_SERVER_DOWN: + $return = ['class' => 'status_small_squares']; + break; + + // Balls. + case STATUS_AGENT_CRITICAL_BALL: + case STATUS_AGENT_WARNING_BALL: + case STATUS_AGENT_DOWN_BALL: + case STATUS_AGENT_UNKNOWN_BALL: + case STATUS_AGENT_OK_BALL: + case STATUS_AGENT_NO_DATA_BALL: + case STATUS_AGENT_NO_MONITORS_BALL: + $return = ['class' => 'status_balls']; + break; + + // Small Balls. + case STATUS_MODULE_OK_BALL: + case STATUS_MODULE_CRITICAL_BALL: + case STATUS_MODULE_WARNING_BALL: + case STATUS_MODULE_NO_DATA_BALL: + case STATUS_MODULE_UNKNOWN_BALL: + case STATUS_ALERT_FIRED_BALL: + case STATUS_ALERT_NOT_FIRED_BALL: + case STATUS_ALERT_DISABLED_BALL: + $return = ['class' => 'status_small_balls']; + break; + + default: + // Ignored. + break; + } + + return $return; } /** * Prints an image representing a status. * - * @param string $status Module status. - * @param string $title Title. - * @param boolean $return Whether to return an output string or echo now (optional, echo by default). - * @param array $options Options to set image attributes: I.E.: style. - * @param boolean $rounded_image Round. + * @param string $status Module status. + * @param string $title Title. + * @param boolean $return Whether to return an output string or echo now (optional, echo by default). + * @param array $options Options to set image attributes: I.E.: style. * * @return string HTML. */ -function ui_print_module_status( +function ui_print_status_sets( $status, $title='', $return=false, - $options=false, - $rounded_image=false + $options=false ) { global $config; @@ -2674,21 +2742,26 @@ function ui_print_module_status( $options = []; } - $options['style'] .= 'width: 50px;'; - $options['style'] .= 'height: 2em;'; - $options['style'] .= 'display: inline-block;'; - - include_once __DIR__.'/functions_modules.php'; - $options['style'] .= 'background: '.modules_get_color_status($status).';'; - - if ($rounded_image === true) { - $options['style'] .= 'border-radius: 5px;'; + if (isset($options['style'])) { + $options['style'] .= ' background: '.modules_get_color_status($status).'; display: inline-block;'; + } else { + $options['style'] = 'background: '.modules_get_color_status($status).'; display: inline-block;'; } - $options['title'] = $title; - $options['data-title'] = $title; - $options['data-use_title_for_force_title'] = 1; - $options['class'] = 'forced_title'; + if (isset($options['class'])) { + $options['class'] = $options['class']; + } + + if ($title != '') { + $options['title'] = $title; + $options['data-title'] = $title; + $options['data-use_title_for_force_title'] = 1; + if (isset($options['class'])) { + $options['class'] .= ' forced_title'; + } else { + $options['class'] = 'forced_title'; + } + } $output = '
    $v) { @@ -2717,6 +2790,15 @@ function ui_print_module_status( * @param string $color Color. * @param boolean $return Return or paint (if false). * @param boolean $text Text to be displayed,by default progress %. + * @param array $ajax Ajax: [ 'page' => 'page', 'data' => 'data' ] Sample: + * [ + * 'page' => 'operation/agentes/ver_agente', Target page. + * 'interval' => 100 / $agent["intervalo"], Ask every interval seconds. + * 'data' => [ Data to be sent to target page. + * 'id_agente' => $id_agente, + * 'refresh_contact' => 1, + * ], + * ]. * * @return string HTML code. */ @@ -2724,9 +2806,10 @@ function ui_progress( $progress, $width='100%', $height='2.5', - $color='#80ba27', + $color='#82b92e', $return=true, - $text='' + $text='', + $ajax=false ) { if (!$progress) { $progress = 0; @@ -2745,10 +2828,56 @@ function ui_progress( } ui_require_css_file('progress'); - $output .= '
    '; - $output .= ''.$text.''; - $output .= '
    '; - $output .= '
    '; + $output .= ''; + $output .= ''; + $output .= ''; + + if ($ajax !== false && is_array($ajax)) { + $output .= ''; + } if (!$return) { echo $output; @@ -2758,6 +2887,441 @@ function ui_progress( } +/** + * Generate needed code to print a datatables jquery plugin. + * + * @param array $parameters All desired data using following format: + * [ + * 'print' => true (by default printed) + * 'id' => datatable id. + * 'class' => datatable class. + * 'style' => datatable style. + * 'order' => [ + * 'field' => column name + * 'direction' => asc or desc + * ], + * 'default_pagination' => integer, default pagination is set to block_size + * 'ajax_url' => 'include/ajax.php' ajax_url. + * 'ajax_data' => [ operation => 1 ] extra info to be sent. + * 'ajax_postprocess' => a javscript function to postprocess data received + * by ajax call. It is applied foreach row and must + * use following format: + * * [code] + * * function (item) { + * * // Process received item, for instance, name: + * * tmp = '' + item.name + ''; + * * item.name = tmp; + * * } + * * [/code] + * 'columns_names' => [ + * 'column1' :: Used as th text. Direct text entry. It could be array: + * OR + * [ + * 'id' => th id. + * 'class' => th class. + * 'style' => th style. + * 'text' => 'column1'. + * ] + * ], + * 'columns' => [ + * 'column1', + * 'column2', + * ... + * ], + * 'no_sortable_columns' => [ indexes ] 1,2... -1 etc. Avoid sorting. + * 'form' => [ + * 'html' => 'html code' a directly defined inputs in HTML. + * 'extra_buttons' => [ + * [ + * 'id' => button id, + * 'class' => button class, + * 'style' => button style, + * 'text' => button text, + * 'onclick' => button onclick, + * ] + * ], + * 'search_button_class' => search button class. + * 'class' => form class. + * 'id' => form id. + * 'style' => form style. + * 'js' => optional extra actions onsubmit. + * 'inputs' => [ + * 'label' => Input label. + * 'type' => Input type. + * 'value' => Input value. + * 'name' => Input name. + * 'id' => Input id. + * 'options' => [ + * 'option1' + * 'option2' + * ... + * ] + * ] + * ], + * 'extra_html' => HTML content to be placed after 'filter' section. + * 'drawCallback' => function to be called after draw. Sample in: + * https://datatables.net/examples/advanced_init/row_grouping.html + * ] + * End. + * + * @return string HTML code with datatable. + * @throws Exception On error. + */ +function ui_print_datatable(array $parameters) +{ + global $config; + + if (isset($parameters['id'])) { + $table_id = $parameters['id']; + $form_id = 'form_'.$parameters['id']; + } else { + $table_id = uniqid('datatable_'); + $form_id = uniqid('datatable_filter_'); + } + + if (!isset($parameters['columns']) || !is_array($parameters['columns'])) { + throw new Exception('[ui_print_datatable]: You must define columns for datatable'); + } + + if (!isset($parameters['ajax_url'])) { + throw new Exception('[ui_print_datatable]: Parameter ajax_url is required'); + } + + if (!isset($parameters['default_pagination'])) { + $parameters['default_pagination'] = $config['block_size']; + } + + $no_sortable_columns = []; + if (isset($parameters['no_sortable_columns'])) { + $no_sortable_columns = json_encode($parameters['no_sortable_columns']); + } + + if (!is_array($parameters['order'])) { + $order = '0, "asc"'; + } else { + if (!isset($parameters['order']['direction'])) { + $direction = 'asc'; + } + + if (!isset($parameters['order']['field'])) { + $order = 0; + } else { + $order = array_search( + $parameters['order']['field'], + $parameters['columns'] + ); + + if ($order === false) { + $order = 0; + } + } + + $order .= ', "'.$parameters['order']['direction'].'"'; + } + + if (!isset($parameters['ajax_data'])) { + $parameters['ajax_data'] = ''; + } + + $search_button_class = 'sub filter'; + if (isset($parameters['search_button_class'])) { + $search_button_class = $parameters['search_button_class']; + } + + if (isset($parameters['pagination_options'])) { + $pagination_options = $parameters['pagination_options']; + } else { + $pagination_options = [ + [ + $parameters['default_pagination'], + 10, + 25, + 100, + 200, + 500, + 1000, + -1, + ], + [ + $parameters['default_pagination'], + 10, + 25, + 100, + 200, + 500, + 1000, + 'All', + ], + ]; + } + + if (!is_array($parameters['datacolumns'])) { + $parameters['datacolumns'] = $parameters['columns']; + } + + // Datatable filter. + if (isset($parameters['form']) && is_array($parameters['form'])) { + if (isset($parameters['form']['id'])) { + $form_id = $parameters['form']['id']; + } + + if (isset($parameters['form']['class'])) { + $form_class = $parameters['form']['class']; + } else { + $form_class = ''; + } + + if (isset($parameters['form']['style'])) { + $form_style = $parameters['form']['style']; + } else { + $form_style = ''; + } + + if (isset($parameters['form']['js'])) { + $form_js = $parameters['form']['js']; + } else { + $form_js = ''; + } + + $filter = '
    '; + + if (isset($parameters['form']['html'])) { + $filter .= $parameters['form']['html']; + } + + $filter .= '
      '; + + foreach ($parameters['form']['inputs'] as $input) { + $filter .= html_print_input(($input + ['return' => true]), 'li'); + } + + $filter .= '
    • '; + // Search button. + $filter .= ''; + + // Extra buttons. + if (is_array($parameters['form']['extra_buttons'])) { + foreach ($parameters['form']['extra_buttons'] as $button) { + $filter .= ''; + } + } + + $filter .= '
    • '; + + $filter .= '
    '; + $filter = ui_toggle( + $filter, + __('Filter'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border' + ); + } else if (isset($parameters['form_html'])) { + $filter = ui_toggle( + $parameters['form_html'], + __('Filter'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border' + ); + } + + // Extra html. + $extra = ''; + if (isset($parameters['extra_html']) && !empty($parameters['extra_html'])) { + $extra = $parameters['extra_html']; + } + + // Base table. + $table = '
  • '.__('Generated').': '.$date_today.'
    '; + $table .= ''; + + if (isset($parameters['column_names']) + && is_array($parameters['column_names']) + ) { + $names = $parameters['column_names']; + } else { + $names = $parameters['columns']; + } + + foreach ($names as $column) { + if (is_array($column)) { + $table .= ''; + } else { + $table .= ''; + } + } + + $table .= ''; + $table .= '
    '.__($column['text']); + $table .= $column['extra']; + $table .= ''.__($column).'
    '; + + $pagination_class = 'pandora_pagination'; + if (!empty($parameters['pagination_class'])) { + $pagination_class = $parameters['pagination_class']; + } + + // Javascript controller. + $js = ''; + + // Order. + $err_msg = '
    '; + $output = $err_msg.$filter.$extra.$table.$js; + + ui_require_css_file('datatables.min', 'include/styles/js/'); + ui_require_javascript_file('datatables.min'); + ui_require_javascript_file('buttons.dataTables.min'); + ui_require_javascript_file('dataTables.buttons.min'); + ui_require_javascript_file('buttons.html5.min'); + ui_require_javascript_file('buttons.print.min'); + + $output = $include.$output; + + // Print datatable if needed. + if (!(isset($parameters['print']) && $parameters['print'] === false)) { + echo $output; + } + + return $output; +} + + /** * Returns a div wich represents the type received. * @@ -2919,12 +3483,15 @@ function ui_print_event_priority( /** * Print a code into a DIV and enable a toggle to show and hide it. * - * @param string $code Html code. - * @param string $name Name of the link. - * @param string $title Title of the link. - * @param boolean $hidden_default If the div will be hidden by default (default: true). - * @param boolean $return Whether to return an output string or echo now (default: true). - * @param string $toggle_class Toggle class. + * @param string $code Html code. + * @param string $name Name of the link. + * @param string $title Title of the link. + * @param string $id Block id. + * @param boolean $hidden_default If the div will be hidden by default (default: true). + * @param boolean $return Whether to return an output string or echo now (default: true). + * @param string $toggle_class Toggle class. + * @param string $container_class Container class. + * @param string $main_class Main object class. * * @return string HTML. */ @@ -2932,10 +3499,12 @@ function ui_toggle( $code, $name, $title='', + $id='', $hidden_default=true, $return=false, $toggle_class='', - $container_class='white-box-content' + $container_class='white-box-content', + $main_class='box-shadow white_table_graph' ) { // Generate unique Id. $uniqid = uniqid(''); @@ -2952,7 +3521,7 @@ function ui_toggle( } // Link to toggle. - $output = '
    '; + $output = '
    '; $output .= '
    '.html_print_image( $original, true, @@ -3124,13 +3693,31 @@ function ui_get_url_refresh($params=false, $relative=true, $add_post=true) $url = htmlspecialchars($url); if (! $relative) { - return ui_get_full_url($url); + return ui_get_full_url($url, false, false, false); } return $url; } +/** + * Checks if public_url usage is being forced to target 'visitor'. + * + * @return boolean + */ +function ui_forced_public_url() +{ + global $config; + $exclusions = preg_split("/[\n\s,]+/", io_safe_output($config['public_url_exclusions'])); + + if (in_array($_SERVER['REMOTE_ADDR'], $exclusions)) { + return false; + } + + return (bool) $config['force_public_url']; +} + + /** * Returns a full URL in Pandora. (with the port and https in some systems) * @@ -3177,13 +3764,27 @@ function ui_get_full_url($url='', $no_proxy=false, $add_name_php_file=false, $me } if (!$no_proxy) { - // Check if the PandoraFMS runs across the proxy like as - // mod_proxy of Apache - // and check if public_url is set. - if (!empty($config['public_url']) + // Check proxy. + $proxy = false; + if (ui_forced_public_url()) { + $proxy = true; + $fullurl = $config['public_url']; + if (substr($fullurl, -1) != '/') { + $fullurl .= '/'; + } + + if ($url == 'index.php' && is_metaconsole()) { + $fullurl .= ENTERPRISE_DIR.'/meta'; + } + } else if (!empty($config['public_url']) && (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) ) { + // Forced to use public url when being forwarder by a reverse proxy. $fullurl = $config['public_url']; + if (substr($fullurl, -1) != '/') { + $fullurl .= '/'; + } + $proxy = true; } else { $fullurl = $protocol.'://'.$_SERVER['SERVER_NAME']; @@ -3214,7 +3815,7 @@ function ui_get_full_url($url='', $no_proxy=false, $add_name_php_file=false, $me $url = $config['homeurl_static'].'/'; } - if (defined('METACONSOLE') && $metaconsole_root) { + if (is_metaconsole() && $metaconsole_root) { $url .= 'enterprise/meta/'; } } else if (!strstr($url, '.php')) { @@ -3224,7 +3825,7 @@ function ui_get_full_url($url='', $no_proxy=false, $add_name_php_file=false, $me $fullurl .= $config['homeurl_static'].'/'; } - if (defined('METACONSOLE') && $metaconsole_root) { + if (is_metaconsole() && $metaconsole_root) { $fullurl .= 'enterprise/meta/'; } } else { @@ -3236,7 +3837,7 @@ function ui_get_full_url($url='', $no_proxy=false, $add_name_php_file=false, $me } else { $fullurl .= $config['homeurl_static'].'/'; - if (defined('METACONSOLE') && $metaconsole_root) { + if (is_metaconsole() && $metaconsole_root) { $fullurl .= 'enterprise/meta/'; } } @@ -3295,11 +3896,11 @@ function ui_print_page_header( if ($godmode == true) { $type = 'view'; - $type2 = (empty($breadcrumbs)) ? 'menu_tab_frame_view' : 'menu_tab_frame_view_bc'; + $type2 = 'menu_tab_frame_view'; $separator_class = 'separator'; } else { $type = 'view'; - $type2 = (empty($breadcrumbs)) ? 'menu_tab_frame_view' : 'menu_tab_frame_view_bc'; + $type2 = 'menu_tab_frame_view'; $separator_class = 'separator_view'; } @@ -3844,6 +4445,10 @@ function ui_print_agent_autocomplete_input($parameters) $get_only_string_modules = true; } + if (isset($parameters['no_disabled_modules'])) { + $no_disabled_modules = $parameters['no_disabled_modules']; + } + $spinner_image = html_print_image('images/spinner.gif', true, false, true); if (isset($parameters['spinner_image'])) { $spinner_image = $parameters['spinner_image']; @@ -3851,7 +4456,7 @@ function ui_print_agent_autocomplete_input($parameters) // Javascript configurations // ------------------------------------------------------------------. - $javascript_ajax_page = ui_get_full_url('ajax.php', false, false, false, false); + $javascript_ajax_page = ui_get_full_url('ajax.php', false, false, false); // Default value. if (isset($parameters['javascript_ajax_page'])) { $javascript_ajax_page = $parameters['javascript_ajax_page']; @@ -3991,7 +4596,11 @@ function ui_print_agent_autocomplete_input($parameters) if ('.((int) $get_only_string_modules).') { inputs.push ("get_only_string_modules=1"); } - + + if ('.((int) $no_disabled_modules).') { + inputs.push ("disabled=0"); + } + if ('.((int) $metaconsole_enabled).') { if (('.((int) $use_input_server).') || ('.((int) $print_input_server).')) { diff --git a/pandora_console/include/functions_update_manager.php b/pandora_console/include/functions_update_manager.php index cc148be7b9..73a654a50d 100755 --- a/pandora_console/include/functions_update_manager.php +++ b/pandora_console/include/functions_update_manager.php @@ -468,7 +468,7 @@ function registration_wiz_modal( __('Cancel'), 'cancel_registration', false, - 'class="ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel" style="color: red; width:100px;"', + 'class="ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel"', true ); $output .= '
    '; diff --git a/pandora_console/include/functions_users.php b/pandora_console/include/functions_users.php index 2a29155228..97d97c7273 100755 --- a/pandora_console/include/functions_users.php +++ b/pandora_console/include/functions_users.php @@ -249,13 +249,13 @@ function groups_combine_acl($acl_group_a, $acl_group_b) /** * Get all the groups a user has reading privileges. * - * @param string User id - * @param string The privilege to evaluate, and it is false then no check ACL. - * @param boolean $returnAllGroup Flag the return group, by default true. - * @param boolean $returnAllColumns Flag to return all columns of groups. - * @param array $id_groups The list of group to scan to bottom child. By default null. - * @param string $keys_field The field of the group used in the array keys. By default ID - * @param boolean $cache Set it to false to not use cache + * @param string $id_user User id + * @param string $privilege The privilege to evaluate, and it is false then no check ACL. + * @param boolean $returnAllGroup Flag the return group, by default true. + * @param boolean $returnAllColumns Flag to return all columns of groups. + * @param array $id_groups The list of group to scan to bottom child. By default null. + * @param string $keys_field The field of the group used in the array keys. By default ID + * @param boolean $cache Set it to false to not use cache * * @return array A list of the groups the user has certain privileges. */ @@ -293,7 +293,7 @@ function users_get_groups( } // Per-group permissions. else { - $query = 'SELECT * FROM tgrupo ORDER BY parent,id_grupo DESC'; + $query = 'SELECT * FROM tgrupo ORDER BY nombre'; $raw_groups = db_get_all_rows_sql($query); $query = sprintf( @@ -617,16 +617,21 @@ function users_save_login() $user_list = json_decode($user_list_json, true); if (empty($user_list)) { - $user_list = []; - } - - if (isset($user_list[$config['id_user']])) { - $user_list[$config['id_user']]['count']++; - } else { $user_list[$config['id_user']] = [ 'name' => $user['fullname'], 'count' => 1, ]; + } else if (isset($user_list[$config['id_user']])) { + $user_list[$config['id_user']] = [ + 'name' => $user['fullname'], + 'count' => $user_list[$config['id_user']]['count'], + ]; + } else { + $users_count = count($user_list); + $user_list[$config['id_user']] = [ + 'name' => $user['fullname'], + 'count' => ++$users_count, + ]; } // Clean the file @@ -704,17 +709,7 @@ function users_save_logout($user=false, $delete=false) $user_list = []; } - if ($delete) { - unset($user_list[$user['id_user']]); - } else { - if (isset($user_list[$config['id_user']])) { - $user_list[$config['id_user']]['count']--; - } - - if ($user_list[$config['id_user']]['count'] <= 0) { - unset($user_list[$user['id_user']]); - } - } + unset($user_list[$user['id_user']]); // Clean the file ftruncate($fp_user_list, 0); @@ -1052,6 +1047,13 @@ function users_check_users() 'users' => '', ]; + $users_with_session = db_get_all_rows_sql('SELECT tsessions_php.data FROM pandora.tsessions_php;'); + $users_logged_now = []; + foreach ($users_with_session as $user_with_session) { + $tmp_id_user = explode('"', $user_with_session['data']); + array_push($users_logged_now, $tmp_id_user[1]); + } + $file_global_user_list = $config['attachment_store'].'/pandora_chat.user_list.json.txt'; // First lock the file @@ -1082,13 +1084,32 @@ function users_check_users() $user_list = []; } - fclose($fp_user_list); - + // Compare both user list. Meanwhile the user from chat file have an active + // session, his continue in the list of active chat users $user_name_list = []; - foreach ($user_list as $user) { - $user_name_list[] = $user['name']; + foreach ($user_list as $key => $user) { + if (in_array($key, $users_logged_now)) { + array_push($user_name_list, $user['name']); + } else { + unset($user_list[$key]); + } } + // Clean the file + ftruncate($fp_user_list, 0); + + // Update the file with the correct list of users + $status = fwrite($fp_user_list, json_encode($user_list)); + + /* + if ($status === false) { + fclose($fp_user_list); + + return; + } */ + // Closing the resource + fclose($fp_user_list); + $return['correct'] = true; $return['users'] = implode('
    ', $user_name_list); echo json_encode($return); diff --git a/pandora_console/include/functions_visual_map.php b/pandora_console/include/functions_visual_map.php index 680d6e3ce9..1c6afb9eed 100755 --- a/pandora_console/include/functions_visual_map.php +++ b/pandora_console/include/functions_visual_map.php @@ -1966,7 +1966,7 @@ function visual_map_print_item( echo '
    '; - echo "
    ".remove_right_zeros(number_format($stat_agent_cr, 2)).'%
    '; + echo "
    ".remove_right_zeros(number_format($stat_agent_cr, 2)).'%
    '; echo "
    Critical
    "; echo "
    ".remove_right_zeros(number_format($stat_agent_wa, 2)).'%
    '; echo "
    Warning
    "; @@ -3611,11 +3611,6 @@ function visual_map_print_visual_map( global $config; - $metaconsole_hack = '/'; - if (defined('METACONSOLE')) { - $metaconsole_hack = '../../'; - } - enterprise_include_once('meta/include/functions_ui_meta.php'); include_once $config['homedir'].'/include/functions_custom_graphs.php'; @@ -3681,11 +3676,11 @@ function visual_map_print_visual_map( $mapHeight = $layout['height']; $backgroundImage = ''; if ($layout['background'] != 'None.png') { - $backgroundImage = $metaconsole_hack.'images/console/background/'.$layout['background']; + $backgroundImage = 'images/console/background/'.$layout['background']; } } - if (defined('METACONSOLE')) { + if (is_metaconsole()) { echo "
    "; } @@ -3698,7 +3693,7 @@ function visual_map_print_visual_map( background-color:'.$layout['background_color'].';">'; if ($layout['background'] != 'None.png') { - echo ""; + echo ""; } $layout_datas = db_get_all_rows_field_filter( @@ -3776,7 +3771,7 @@ function visual_map_print_visual_map( // End main div echo '
    '; - if (defined('METACONSOLE')) { + if (is_metaconsole()) { echo ''; } } @@ -4271,7 +4266,7 @@ function visual_map_create_internal_name_item($label=null, $type, $image, $agent case 'static_graph': case STATIC_GRAPH: - $text = __('Static graph').' - '.$image; + $text = __('Static Image').' - '.$image; break; case 'simple_value': diff --git a/pandora_console/include/functions_visual_map_editor.php b/pandora_console/include/functions_visual_map_editor.php index 7e7cffeca4..0e678c6111 100755 --- a/pandora_console/include/functions_visual_map_editor.php +++ b/pandora_console/include/functions_visual_map_editor.php @@ -1294,7 +1294,7 @@ function visual_map_editor_print_toolbox() } echo '
    '; - visual_map_print_button_editor('static_graph', __('Static Graph'), 'left', false, 'camera_min', true); + visual_map_print_button_editor('static_graph', __('Static Image'), 'left', false, 'camera_min', true); visual_map_print_button_editor('percentile_item', __('Percentile Item'), 'left', false, 'percentile_item_min', true); visual_map_print_button_editor('module_graph', __('Module Graph'), 'left', false, 'graph_min', true); visual_map_print_button_editor('donut_graph', __('Serialized pie graph'), 'left', false, 'donut_graph_min', true); diff --git a/pandora_console/include/graphs/fgraph.php b/pandora_console/include/graphs/fgraph.php index 9fabfeef64..d8012c15dd 100644 --- a/pandora_console/include/graphs/fgraph.php +++ b/pandora_console/include/graphs/fgraph.php @@ -21,6 +21,7 @@ if (empty($config['homedir'])) { } require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/graphs/functions_flot.php'; $ttl = get_parameter('ttl', 1); $graph_type = get_parameter('graph_type', ''); diff --git a/pandora_console/include/graphs/flot/jquery.flot.pie.js b/pandora_console/include/graphs/flot/jquery.flot.pie.js index 9c19db998b..37a8135e08 100644 --- a/pandora_console/include/graphs/flot/jquery.flot.pie.js +++ b/pandora_console/include/graphs/flot/jquery.flot.pie.js @@ -56,765 +56,897 @@ More detail and specific examples can be found in the included HTML file. */ (function($) { + // Maximum redraw attempts when fitting labels within the plot - // Maximum redraw attempts when fitting labels within the plot + var REDRAW_ATTEMPTS = 10; - var REDRAW_ATTEMPTS = 10; + // Factor by which to shrink the pie when fitting labels within the plot - // Factor by which to shrink the pie when fitting labels within the plot + var REDRAW_SHRINK = 0.95; - var REDRAW_SHRINK = 0.95; + function init(plot) { + var canvas = null, + target = null, + options = null, + maxRadius = null, + centerLeft = null, + centerTop = null, + processed = false, + ctx = null; - function init(plot) { + // interactive variables - var canvas = null, - target = null, - options = null, - maxRadius = null, - centerLeft = null, - centerTop = null, - processed = false, - ctx = null; + var highlights = []; - // interactive variables + // add hook to determine if pie plugin in enabled, and then perform necessary operations - var highlights = []; + plot.hooks.processOptions.push(function(plot, options) { + if (options.series.pie.show) { + options.grid.show = false; - // add hook to determine if pie plugin in enabled, and then perform necessary operations + // set labels.show - plot.hooks.processOptions.push(function(plot, options) { - if (options.series.pie.show) { + if (options.series.pie.label.show == "auto") { + if (options.legend.show) { + options.series.pie.label.show = false; + } else { + options.series.pie.label.show = true; + } + } - options.grid.show = false; + // set radius - // set labels.show + if (options.series.pie.radius == "auto") { + if (options.series.pie.label.show) { + options.series.pie.radius = 3 / 4; + } else { + options.series.pie.radius = 1; + } + } - if (options.series.pie.label.show == "auto") { - if (options.legend.show) { - options.series.pie.label.show = false; - } else { - options.series.pie.label.show = true; - } - } + // ensure sane tilt - // set radius + if (options.series.pie.tilt > 1) { + options.series.pie.tilt = 1; + } else if (options.series.pie.tilt < 0) { + options.series.pie.tilt = 0; + } + } + }); - if (options.series.pie.radius == "auto") { - if (options.series.pie.label.show) { - options.series.pie.radius = 3/4; - } else { - options.series.pie.radius = 1; - } - } + plot.hooks.bindEvents.push(function(plot, eventHolder) { + var options = plot.getOptions(); + if (options.series.pie.show) { + if (options.grid.hoverable) { + eventHolder.unbind("mousemove").mousemove(onMouseMove); + } + if (options.grid.clickable) { + eventHolder.unbind("click").click(onClick); + } + } + }); - // ensure sane tilt + plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { + var options = plot.getOptions(); + if (options.series.pie.show) { + processDatapoints(plot, series, data, datapoints); + } + }); - if (options.series.pie.tilt > 1) { - options.series.pie.tilt = 1; - } else if (options.series.pie.tilt < 0) { - options.series.pie.tilt = 0; - } - } - }); + plot.hooks.drawOverlay.push(function(plot, octx) { + var options = plot.getOptions(); + if (options.series.pie.show) { + drawOverlay(plot, octx); + } + }); - plot.hooks.bindEvents.push(function(plot, eventHolder) { - var options = plot.getOptions(); - if (options.series.pie.show) { - if (options.grid.hoverable) { - eventHolder.unbind("mousemove").mousemove(onMouseMove); - } - if (options.grid.clickable) { - eventHolder.unbind("click").click(onClick); - } - } - }); + plot.hooks.draw.push(function(plot, newCtx) { + var options = plot.getOptions(); + if (options.series.pie.show) { + draw(plot, newCtx); + } + }); - plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { - var options = plot.getOptions(); - if (options.series.pie.show) { - processDatapoints(plot, series, data, datapoints); - } - }); + function processDatapoints(plot) { + if (!processed) { + processed = true; + canvas = plot.getCanvas(); + target = $(canvas).parent(); + options = plot.getOptions(); + plot.setData(combine(plot.getData())); + } + } - plot.hooks.drawOverlay.push(function(plot, octx) { - var options = plot.getOptions(); - if (options.series.pie.show) { - drawOverlay(plot, octx); - } - }); + function combine(data) { + var total = 0, + combined = 0, + numCombined = 0, + color = options.series.pie.combine.color, + newdata = []; - plot.hooks.draw.push(function(plot, newCtx) { - var options = plot.getOptions(); - if (options.series.pie.show) { - draw(plot, newCtx); - } - }); + // Fix up the raw data from Flot, ensuring the data is numeric - function processDatapoints(plot, series, datapoints) { - if (!processed) { - processed = true; - canvas = plot.getCanvas(); - target = $(canvas).parent(); - options = plot.getOptions(); - plot.setData(combine(plot.getData())); - } - } + for (var i = 0; i < data.length; ++i) { + var value = data[i].data; - function combine(data) { + // If the data is an array, we'll assume that it's a standard + // Flot x-y pair, and are concerned only with the second value. - var total = 0, - combined = 0, - numCombined = 0, - color = options.series.pie.combine.color, - newdata = []; + // Note how we use the original array, rather than creating a + // new one; this is more efficient and preserves any extra data + // that the user may have stored in higher indexes. - // Fix up the raw data from Flot, ensuring the data is numeric + if ($.isArray(value) && value.length == 1) { + value = value[0]; + } - for (var i = 0; i < data.length; ++i) { + if ($.isArray(value)) { + // Equivalent to $.isNumeric() but compatible with jQuery < 1.7 + if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) { + value[1] = +value[1]; + } else { + value[1] = 0; + } + } else if (!isNaN(parseFloat(value)) && isFinite(value)) { + value = [1, +value]; + } else { + value = [1, 0]; + } - var value = data[i].data; + data[i].data = [value]; + } - // If the data is an array, we'll assume that it's a standard - // Flot x-y pair, and are concerned only with the second value. + // Sum up all the slices, so we can calculate percentages for each - // Note how we use the original array, rather than creating a - // new one; this is more efficient and preserves any extra data - // that the user may have stored in higher indexes. + for (var i = 0; i < data.length; ++i) { + total += data[i].data[0][1]; + } - if ($.isArray(value) && value.length == 1) { - value = value[0]; - } + // Count the number of slices with percentages below the combine + // threshold; if it turns out to be just one, we won't combine. - if ($.isArray(value)) { - // Equivalent to $.isNumeric() but compatible with jQuery < 1.7 - if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) { - value[1] = +value[1]; - } else { - value[1] = 0; - } - } else if (!isNaN(parseFloat(value)) && isFinite(value)) { - value = [1, +value]; - } else { - value = [1, 0]; - } + for (var i = 0; i < data.length; ++i) { + var value = data[i].data[0][1]; + if (value / total <= options.series.pie.combine.threshold) { + combined += value; + numCombined++; + if (!color) { + color = data[i].color; + } + } + } - data[i].data = [value]; - } - - // Sum up all the slices, so we can calculate percentages for each - - for (var i = 0; i < data.length; ++i) { - total += data[i].data[0][1]; - } - - // Count the number of slices with percentages below the combine - // threshold; if it turns out to be just one, we won't combine. - - for (var i = 0; i < data.length; ++i) { - var value = data[i].data[0][1]; - if (value / total <= options.series.pie.combine.threshold) { - combined += value; - numCombined++; - if (!color) { - color = data[i].color; - } - } - } - - for (var i = 0; i < data.length; ++i) { - var value = data[i].data[0][1]; - if (numCombined < 2 || value / total > options.series.pie.combine.threshold) { - newdata.push( - $.extend(data[i], { /* extend to allow keeping all other original data values + for (var i = 0; i < data.length; ++i) { + var value = data[i].data[0][1]; + if ( + numCombined < 2 || + value / total > options.series.pie.combine.threshold + ) { + newdata.push( + $.extend(data[i], { + /* extend to allow keeping all other original data values and using them e.g. in labelFormatter. */ - data: [[1, value]], - color: data[i].color, - label: data[i].label, - angle: value * Math.PI * 2 / total, - percent: value / (total / 100) - }) - ); - } - } - - if (numCombined > 1) { - newdata.push({ - data: [[1, combined]], - color: color, - label: options.series.pie.combine.label, - angle: combined * Math.PI * 2 / total, - percent: combined / (total / 100) - }); - } - - return newdata; - } - - function draw(plot, newCtx) { - - if (!target) { - return; // if no series were passed - } - - var canvasWidth = plot.getPlaceholder().width(), - canvasHeight = plot.getPlaceholder().height(), - legendWidth = target.children().filter(".legend").children().width() || 0; - - ctx = newCtx; - - // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE! - - // When combining smaller slices into an 'other' slice, we need to - // add a new series. Since Flot gives plugins no way to modify the - // list of series, the pie plugin uses a hack where the first call - // to processDatapoints results in a call to setData with the new - // list of series, then subsequent processDatapoints do nothing. - - // The plugin-global 'processed' flag is used to control this hack; - // it starts out false, and is set to true after the first call to - // processDatapoints. - - // Unfortunately this turns future setData calls into no-ops; they - // call processDatapoints, the flag is true, and nothing happens. - - // To fix this we'll set the flag back to false here in draw, when - // all series have been processed, so the next sequence of calls to - // processDatapoints once again starts out with a slice-combine. - // This is really a hack; in 0.9 we need to give plugins a proper - // way to modify series before any processing begins. - - processed = false; - - // calculate maximum radius and center point - - maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2; - centerTop = canvasHeight / 2 + options.series.pie.offset.top; - centerLeft = canvasWidth / 2; - - if (options.series.pie.offset.left == "auto") { - if (options.legend.position.match("w")) { - centerLeft += legendWidth / 2; - } else { - centerLeft -= legendWidth / 2; - } - if (centerLeft < maxRadius) { - centerLeft = maxRadius; - } else if (centerLeft > canvasWidth - maxRadius) { - centerLeft = canvasWidth - maxRadius; - } - } else { - centerLeft += options.series.pie.offset.left; - } - - var slices = plot.getData(), - attempts = 0; - - // Keep shrinking the pie's radius until drawPie returns true, - // indicating that all the labels fit, or we try too many times. - - do { - if (attempts > 0) { - maxRadius *= REDRAW_SHRINK; - } - attempts += 1; - clear(); - if (options.series.pie.tilt <= 0.8) { - drawShadow(); - } - } while (!drawPie() && attempts < REDRAW_ATTEMPTS) - - if (attempts >= REDRAW_ATTEMPTS) { - clear(); - target.prepend("
    Could not draw pie with labels contained inside canvas
    "); - } - - if (plot.setSeries && plot.insertLegend) { - plot.setSeries(slices); - plot.insertLegend(); - } - - // we're actually done at this point, just defining internal functions at this point - - function clear() { - ctx.clearRect(0, 0, canvasWidth, canvasHeight); - target.children().filter(".pieLabel, .pieLabelBackground").remove(); - } - - function drawShadow() { - - var shadowLeft = options.series.pie.shadow.left; - var shadowTop = options.series.pie.shadow.top; - var edge = 10; - var alpha = options.series.pie.shadow.alpha; - var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; - - if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) { - return; // shadow would be outside canvas, so don't draw it - } - - ctx.save(); - ctx.translate(shadowLeft,shadowTop); - ctx.globalAlpha = alpha; - ctx.fillStyle = "#000"; - - // center and rotate to starting position - - ctx.translate(centerLeft,centerTop); - ctx.scale(1, options.series.pie.tilt); - - //radius -= edge; - - for (var i = 1; i <= edge; i++) { - ctx.beginPath(); - ctx.arc(0, 0, radius, 0, Math.PI * 2, false); - ctx.fill(); - radius -= i; - } - - ctx.restore(); - } - - function drawPie() { - - var startAngle = Math.PI * options.series.pie.startAngle; - var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; - - // center and rotate to starting position - - ctx.save(); - ctx.translate(centerLeft,centerTop); - ctx.scale(1, options.series.pie.tilt); - //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera - - // draw slices - - ctx.save(); - var currentAngle = startAngle; - for (var i = 0; i < slices.length; ++i) { - slices[i].startAngle = currentAngle; - drawSlice(slices[i].angle, slices[i].color, true); - } - ctx.restore(); - - // draw slice outlines - - if (options.series.pie.stroke.width > 0) { - ctx.save(); - ctx.lineWidth = options.series.pie.stroke.width; - currentAngle = startAngle; - for (var i = 0; i < slices.length; ++i) { - drawSlice(slices[i].angle, options.series.pie.stroke.color, false); - } - ctx.restore(); - } - - // draw donut hole - - drawDonutHole(ctx); - - ctx.restore(); - - // Draw the labels, returning true if they fit within the plot - - if (options.series.pie.label.show) { - return drawLabels(); - } else return true; - - function drawSlice(angle, color, fill) { - - if (angle <= 0 || isNaN(angle)) { - return; - } - - if (fill) { - ctx.fillStyle = color; - } else { - ctx.strokeStyle = color; - ctx.lineJoin = "round"; - } - - ctx.beginPath(); - if (Math.abs(angle - Math.PI * 2) > 0.000000001) { - ctx.moveTo(0, 0); // Center of the pie - } - - //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera - ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false); - ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false); - ctx.closePath(); - //ctx.rotate(angle); // This doesn't work properly in Opera - currentAngle += angle; - - if (fill) { - ctx.fill(); - } else { - ctx.stroke(); - } - } - - function drawLabels() { - - var currentAngle = startAngle; - var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius; - - for (var i = 0; i < slices.length; ++i) { - if (slices[i].percent >= options.series.pie.label.threshold * 100) { - if (!drawLabel(slices[i], currentAngle, i)) { - return false; - } - } - currentAngle += slices[i].angle; - } - - return true; - - function drawLabel(slice, startAngle, index) { - - if (slice.data[0][1] == 0) { - return true; - } - - // format label text - - var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; - - if (lf) { - text = lf(slice.label, slice); - } else { - text = slice.label; - } - - if (plf) { - text = plf(text, slice); - } - - var halfAngle = ((startAngle + slice.angle) + startAngle) / 2; - var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); - var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; - - var html = "" + text + ""; - target.append(html); - - var label = target.children("#pieLabel" + index); - var labelTop = (y - label.height() / 2); - var labelLeft = (x - label.width() / 2); - - label.css("top", labelTop); - label.css("left", labelLeft); - - // check to make sure that the label is not outside the canvas - - if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) { - return false; - } - - if (options.series.pie.label.background.opacity != 0) { - - // put in the transparent background separately to avoid blended labels and label boxes - - var c = options.series.pie.label.background.color; - - if (c == null) { - c = slice.color; - } - - var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;"; - $("
    ") - .css("opacity", options.series.pie.label.background.opacity) - .insertBefore(label); - } - - return true; - } // end individual label function - } // end drawLabels function - } // end drawPie function - } // end draw function - - // Placed here because it needs to be accessed from multiple locations - - function drawDonutHole(layer) { - if (options.series.pie.innerRadius > 0) { - - // subtract the center - - layer.save(); - var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; - layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color - layer.beginPath(); - layer.fillStyle = options.series.pie.stroke.color; - layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); - layer.fill(); - layer.closePath(); - layer.restore(); - - // add inner stroke - - layer.save(); - layer.beginPath(); - layer.strokeStyle = options.series.pie.stroke.color; - layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); - layer.stroke(); - layer.closePath(); - layer.restore(); - - // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. - } - } - - //-- Additional Interactive related functions -- - - function isPointInPoly(poly, pt) { - for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) - ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) - && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) - && (c = !c); - return c; - } - - function findNearbySlice(mouseX, mouseY) { - - var slices = plot.getData(), - options = plot.getOptions(), - radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius, - x, y; - - for (var i = 0; i < slices.length; ++i) { - - var s = slices[i]; - - if (s.pie.show) { - - ctx.save(); - ctx.beginPath(); - ctx.moveTo(0, 0); // Center of the pie - //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. - ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false); - ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false); - ctx.closePath(); - x = mouseX - centerLeft; - y = mouseY - centerTop; - - if (ctx.isPointInPath) { - if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) { - ctx.restore(); - return { - datapoint: [s.percent, s.data], - dataIndex: 0, - series: s, - seriesIndex: i - }; - } - } else { - - // excanvas for IE doesn;t support isPointInPath, this is a workaround. - - var p1X = radius * Math.cos(s.startAngle), - p1Y = radius * Math.sin(s.startAngle), - p2X = radius * Math.cos(s.startAngle + s.angle / 4), - p2Y = radius * Math.sin(s.startAngle + s.angle / 4), - p3X = radius * Math.cos(s.startAngle + s.angle / 2), - p3Y = radius * Math.sin(s.startAngle + s.angle / 2), - p4X = radius * Math.cos(s.startAngle + s.angle / 1.5), - p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5), - p5X = radius * Math.cos(s.startAngle + s.angle), - p5Y = radius * Math.sin(s.startAngle + s.angle), - arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]], - arrPoint = [x, y]; - - // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? - - if (isPointInPoly(arrPoly, arrPoint)) { - ctx.restore(); - return { - datapoint: [s.percent, s.data], - dataIndex: 0, - series: s, - seriesIndex: i - }; - } - } - - ctx.restore(); - } - } - - return null; - } - - function onMouseMove(e) { - triggerClickHoverEvent("plothover", e); - } - - function onClick(e) { - triggerClickHoverEvent("plotclick", e); - } - - // trigger click or hover event (they send the same parameters so we share their code) - - function triggerClickHoverEvent(eventname, e) { - - var offset = plot.offset(); - var canvasX = parseInt(e.pageX - offset.left); - var canvasY = parseInt(e.pageY - offset.top); - var item = findNearbySlice(canvasX, canvasY); - - if (options.grid.autoHighlight) { - - // clear auto-highlights - - for (var i = 0; i < highlights.length; ++i) { - var h = highlights[i]; - if (h.auto == eventname && !(item && h.series == item.series)) { - unhighlight(h.series); - } - } - } - - // highlight the slice - - if (item) { - highlight(item.series, eventname); - } - - // trigger any hover bind events - - var pos = { pageX: e.pageX, pageY: e.pageY }; - target.trigger(eventname, [pos, item]); - } - - function highlight(s, auto) { - //if (typeof s == "number") { - // s = series[s]; - //} - - var i = indexOfHighlight(s); - - if (i == -1) { - highlights.push({ series: s, auto: auto }); - plot.triggerRedrawOverlay(); - } else if (!auto) { - highlights[i].auto = false; - } - } - - function unhighlight(s) { - if (s == null) { - highlights = []; - plot.triggerRedrawOverlay(); - } - - //if (typeof s == "number") { - // s = series[s]; - //} - - var i = indexOfHighlight(s); - - if (i != -1) { - highlights.splice(i, 1); - plot.triggerRedrawOverlay(); - } - } - - function indexOfHighlight(s) { - for (var i = 0; i < highlights.length; ++i) { - var h = highlights[i]; - if (h.series == s) - return i; - } - return -1; - } - - function drawOverlay(plot, octx) { - - var options = plot.getOptions(); - - var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; - - octx.save(); - octx.translate(centerLeft, centerTop); - octx.scale(1, options.series.pie.tilt); - - for (var i = 0; i < highlights.length; ++i) { - drawHighlight(highlights[i].series); - } - - drawDonutHole(octx); - - octx.restore(); - - function drawHighlight(series) { - - if (series.angle <= 0 || isNaN(series.angle)) { - return; - } - - //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); - octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor - octx.beginPath(); - if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) { - octx.moveTo(0, 0); // Center of the pie - } - octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false); - octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false); - octx.closePath(); - octx.fill(); - } - } - } // end init (plugin body) - - // define pie specific options and their default values - - var options = { - series: { - pie: { - show: false, - radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) - innerRadius: 0, /* for donut */ - startAngle: 3/2, - tilt: 1, - shadow: { - left: 5, // shadow left offset - top: 15, // shadow top offset - alpha: 0.02 // shadow alpha - }, - offset: { - top: 0, - left: "auto" - }, - stroke: { - color: "#fff", - width: 1 - }, - label: { - show: "auto", - formatter: function(label, slice) { - return "
    " + label + "
    " + Math.round(slice.percent) + "%
    "; - }, // formatter function - radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) - background: { - color: null, - opacity: 0 - }, - threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) - }, - combine: { - threshold: -1, // percentage at which to combine little slices into one larger slice - color: null, // color to give the new slice (auto-generated if null) - label: "Other" // label to give the new slice - }, - highlight: { - //color: "#fff", // will add this functionality once parseColor is available - opacity: 0.5 - } - } - } - }; - - $.plot.plugins.push({ - init: init, - options: options, - name: "pie", - version: "1.1" - }); - + data: [[1, value]], + color: data[i].color, + label: data[i].label, + angle: (value * Math.PI * 2) / total, + percent: value / (total / 100) + }) + ); + } + } + + if (numCombined > 1) { + newdata.push({ + data: [[1, combined]], + color: color, + label: options.series.pie.combine.label, + angle: (combined * Math.PI * 2) / total, + percent: combined / (total / 100) + }); + } + + return newdata; + } + + function draw(plot, newCtx) { + if (!target) { + return; // if no series were passed + } + + var canvasWidth = plot.getPlaceholder().width(), + canvasHeight = plot.getPlaceholder().height(), + legendWidth = + target + .children() + .filter(".legend") + .children() + .width() || 0; + + ctx = newCtx; + + // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE! + + // When combining smaller slices into an 'other' slice, we need to + // add a new series. Since Flot gives plugins no way to modify the + // list of series, the pie plugin uses a hack where the first call + // to processDatapoints results in a call to setData with the new + // list of series, then subsequent processDatapoints do nothing. + + // The plugin-global 'processed' flag is used to control this hack; + // it starts out false, and is set to true after the first call to + // processDatapoints. + + // Unfortunately this turns future setData calls into no-ops; they + // call processDatapoints, the flag is true, and nothing happens. + + // To fix this we'll set the flag back to false here in draw, when + // all series have been processed, so the next sequence of calls to + // processDatapoints once again starts out with a slice-combine. + // This is really a hack; in 0.9 we need to give plugins a proper + // way to modify series before any processing begins. + + processed = false; + + // calculate maximum radius and center point + + maxRadius = + Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2; + centerTop = canvasHeight / 2 + options.series.pie.offset.top; + centerLeft = canvasWidth / 2; + + if (options.series.pie.offset.left == "auto") { + if (options.legend.position.match("w")) { + centerLeft += legendWidth / 2; + } else { + centerLeft -= legendWidth / 2; + } + if (centerLeft < maxRadius) { + centerLeft = maxRadius; + } else if (centerLeft > canvasWidth - maxRadius) { + centerLeft = canvasWidth - maxRadius; + } + } else { + centerLeft += options.series.pie.offset.left; + } + + var slices = plot.getData(), + attempts = 0; + + // Keep shrinking the pie's radius until drawPie returns true, + // indicating that all the labels fit, or we try too many times. + + do { + if (attempts > 0) { + maxRadius *= REDRAW_SHRINK; + } + attempts += 1; + clear(); + if (options.series.pie.tilt <= 0.8) { + drawShadow(); + } + } while (!drawPie() && attempts < REDRAW_ATTEMPTS); + + if (attempts >= REDRAW_ATTEMPTS) { + clear(); + target.prepend( + "
    Could not draw pie with labels contained inside canvas
    " + ); + } + + if (plot.setSeries && plot.insertLegend) { + plot.setSeries(slices); + plot.insertLegend(); + } + + // we're actually done at this point, just defining internal functions at this point + + function clear() { + ctx.clearRect(0, 0, canvasWidth, canvasHeight); + target + .children() + .filter(".pieLabel, .pieLabelBackground") + .remove(); + } + + function drawShadow() { + var shadowLeft = options.series.pie.shadow.left; + var shadowTop = options.series.pie.shadow.top; + var edge = 10; + var alpha = options.series.pie.shadow.alpha; + var radius = + options.series.pie.radius > 1 + ? options.series.pie.radius + : maxRadius * options.series.pie.radius; + + if ( + radius >= canvasWidth / 2 - shadowLeft || + radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || + radius <= edge + ) { + return; // shadow would be outside canvas, so don't draw it + } + + ctx.save(); + ctx.translate(shadowLeft, shadowTop); + ctx.globalAlpha = alpha; + ctx.fillStyle = "#000"; + + // center and rotate to starting position + + ctx.translate(centerLeft, centerTop); + ctx.scale(1, options.series.pie.tilt); + + //radius -= edge; + + for (var i = 1; i <= edge; i++) { + ctx.beginPath(); + ctx.arc(0, 0, radius, 0, Math.PI * 2, false); + ctx.fill(); + radius -= i; + } + + ctx.restore(); + } + + function drawPie() { + var startAngle = Math.PI * options.series.pie.startAngle; + var radius = + options.series.pie.radius > 1 + ? options.series.pie.radius + : maxRadius * options.series.pie.radius; + + // center and rotate to starting position + + ctx.save(); + ctx.translate(centerLeft, centerTop); + ctx.scale(1, options.series.pie.tilt); + //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera + + // draw slices + + ctx.save(); + var currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) { + slices[i].startAngle = currentAngle; + drawSlice(slices[i].angle, slices[i].color, true); + } + ctx.restore(); + + // draw slice outlines + + if (options.series.pie.stroke.width > 0) { + ctx.save(); + ctx.lineWidth = options.series.pie.stroke.width; + currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) { + drawSlice(slices[i].angle, options.series.pie.stroke.color, false); + } + ctx.restore(); + } + + // draw donut hole + + drawDonutHole(ctx); + + ctx.restore(); + + // Draw the labels, returning true if they fit within the plot + + if (options.series.pie.label.show) { + return drawLabels(); + } else return true; + + function drawSlice(angle, color, fill) { + if (angle <= 0 || isNaN(angle)) { + return; + } + + if (fill) { + ctx.fillStyle = color; + } else { + ctx.strokeStyle = color; + ctx.lineJoin = "round"; + } + + ctx.beginPath(); + if (Math.abs(angle - Math.PI * 2) > 0.000000001) { + ctx.moveTo(0, 0); // Center of the pie + } + + //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera + ctx.arc(0, 0, radius, currentAngle, currentAngle + angle / 2, false); + ctx.arc( + 0, + 0, + radius, + currentAngle + angle / 2, + currentAngle + angle, + false + ); + ctx.closePath(); + //ctx.rotate(angle); // This doesn't work properly in Opera + currentAngle += angle; + + if (fill) { + ctx.fill(); + } else { + ctx.stroke(); + } + } + + function drawLabels() { + var labels = []; + var currentAngle = startAngle; + var radius = + options.series.pie.label.radius > 1 + ? options.series.pie.label.radius + : maxRadius * options.series.pie.label.radius; + + for (var i = 0; i < slices.length; ++i) { + if (slices[i].percent >= options.series.pie.label.threshold * 100) { + if (!drawLabel(slices[i], currentAngle, i)) { + return false; + } + } + currentAngle += slices[i].angle; + } + + return true; + + function drawLabel(slice, startAngle, index) { + if (slice.data[0][1] == 0) { + return true; + } + + // format label text + + var lf = options.legend.labelFormatter, + text, + plf = options.series.pie.label.formatter; + + if (lf) { + text = lf(slice.label, slice); + } else { + text = slice.label; + } + + if (plf) { + text = plf(text, slice); + } + + var halfAngle = (startAngle + slice.angle + startAngle) / 2; + var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); + var y = + centerTop + + Math.round(Math.sin(halfAngle) * radius) * + options.series.pie.tilt; + + var html = + "" + + text + + ""; + target.append(html); + + var label = target.children("#pieLabel" + index); + var labelTop = y - label.height() / 2; + var labelLeft = x - label.width() / 2; + + label.css("top", labelTop); + label.css("left", labelLeft); + + // check to make sure that the label doesn't overlap one of the other labels + var label_pos = getPositions(label); + for (var j = 0; j < labels.length; j++) { + var tmpPos = getPositions(labels[j]); + var horizontalMatch = comparePositions(label_pos[0], tmpPos[0]); + var verticalMatch = comparePositions(label_pos[1], tmpPos[1]); + var match = horizontalMatch && verticalMatch; + if (match) { + var newTop = tmpPos[1][0] - (label.height() + 1); + label.css("top", newTop); + labelTop = newTop; + } + } + + function getPositions(box) { + var $box = $(box); + var pos = $box.position(); + var width = $box.width(); + var height = $box.height(); + return [ + [pos.left, pos.left + width], + [pos.top, pos.top + height] + ]; + } + + function comparePositions(p1, p2) { + var x1 = p1[0] < p2[0] ? p1 : p2; + var x2 = p1[0] < p2[0] ? p2 : p1; + return x1[1] > x2[0] || x1[0] === x2[0] ? true : false; + } + labels.push(label); + + // check to make sure that the label is not outside the canvas + + if ( + 0 - labelTop > 0 || + 0 - labelLeft > 0 || + canvasHeight - (labelTop + label.height()) < 0 || + canvasWidth - (labelLeft + label.width()) < 0 + ) { + return false; + } + + if (options.series.pie.label.background.opacity != 0) { + // put in the transparent background separately to avoid blended labels and label boxes + + var c = options.series.pie.label.background.color; + + if (c == null) { + c = slice.color; + } + + var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;"; + $( + "
    " + ) + .css("opacity", options.series.pie.label.background.opacity) + .insertBefore(label); + } + + return true; + } // end individual label function + } // end drawLabels function + } // end drawPie function + } // end draw function + + // Placed here because it needs to be accessed from multiple locations + + function drawDonutHole(layer) { + if (options.series.pie.innerRadius > 0) { + // subtract the center + + layer.save(); + var innerRadius = + options.series.pie.innerRadius > 1 + ? options.series.pie.innerRadius + : maxRadius * options.series.pie.innerRadius; + layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color + layer.beginPath(); + layer.fillStyle = options.series.pie.stroke.color; + layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); + layer.fill(); + layer.closePath(); + layer.restore(); + + // add inner stroke + + layer.save(); + layer.beginPath(); + layer.strokeStyle = options.series.pie.stroke.color; + layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); + layer.stroke(); + layer.closePath(); + layer.restore(); + + // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. + } + } + + //-- Additional Interactive related functions -- + + function isPointInPoly(poly, pt) { + for (var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) + ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || + (poly[j][1] <= pt[1] && pt[1] < poly[i][1])) && + pt[0] < + ((poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1])) / + (poly[j][1] - poly[i][1]) + + poly[i][0] && + (c = !c); + return c; + } + + function findNearbySlice(mouseX, mouseY) { + var slices = plot.getData(), + options = plot.getOptions(), + radius = + options.series.pie.radius > 1 + ? options.series.pie.radius + : maxRadius * options.series.pie.radius, + x, + y; + + for (var i = 0; i < slices.length; ++i) { + var s = slices[i]; + + if (s.pie.show) { + ctx.save(); + ctx.beginPath(); + ctx.moveTo(0, 0); // Center of the pie + //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. + ctx.arc( + 0, + 0, + radius, + s.startAngle, + s.startAngle + s.angle / 2, + false + ); + ctx.arc( + 0, + 0, + radius, + s.startAngle + s.angle / 2, + s.startAngle + s.angle, + false + ); + ctx.closePath(); + x = mouseX - centerLeft; + y = mouseY - centerTop; + + if (ctx.isPointInPath) { + if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) { + ctx.restore(); + return { + datapoint: [s.percent, s.data], + dataIndex: 0, + series: s, + seriesIndex: i + }; + } + } else { + // excanvas for IE doesn;t support isPointInPath, this is a workaround. + + var p1X = radius * Math.cos(s.startAngle), + p1Y = radius * Math.sin(s.startAngle), + p2X = radius * Math.cos(s.startAngle + s.angle / 4), + p2Y = radius * Math.sin(s.startAngle + s.angle / 4), + p3X = radius * Math.cos(s.startAngle + s.angle / 2), + p3Y = radius * Math.sin(s.startAngle + s.angle / 2), + p4X = radius * Math.cos(s.startAngle + s.angle / 1.5), + p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5), + p5X = radius * Math.cos(s.startAngle + s.angle), + p5Y = radius * Math.sin(s.startAngle + s.angle), + arrPoly = [ + [0, 0], + [p1X, p1Y], + [p2X, p2Y], + [p3X, p3Y], + [p4X, p4Y], + [p5X, p5Y] + ], + arrPoint = [x, y]; + + // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? + + if (isPointInPoly(arrPoly, arrPoint)) { + ctx.restore(); + return { + datapoint: [s.percent, s.data], + dataIndex: 0, + series: s, + seriesIndex: i + }; + } + } + + ctx.restore(); + } + } + + return null; + } + + function onMouseMove(e) { + triggerClickHoverEvent("plothover", e); + } + + function onClick(e) { + triggerClickHoverEvent("plotclick", e); + } + + // trigger click or hover event (they send the same parameters so we share their code) + + function triggerClickHoverEvent(eventname, e) { + var offset = plot.offset(); + var canvasX = parseInt(e.pageX - offset.left); + var canvasY = parseInt(e.pageY - offset.top); + var item = findNearbySlice(canvasX, canvasY); + + if (options.grid.autoHighlight) { + // clear auto-highlights + + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.auto == eventname && !(item && h.series == item.series)) { + unhighlight(h.series); + } + } + } + + // highlight the slice + + if (item) { + highlight(item.series, eventname); + } + + // trigger any hover bind events + + var pos = { pageX: e.pageX, pageY: e.pageY }; + target.trigger(eventname, [pos, item]); + } + + function highlight(s, auto) { + //if (typeof s == "number") { + // s = series[s]; + //} + + var i = indexOfHighlight(s); + + if (i == -1) { + highlights.push({ series: s, auto: auto }); + plot.triggerRedrawOverlay(); + } else if (!auto) { + highlights[i].auto = false; + } + } + + function unhighlight(s) { + if (s == null) { + highlights = []; + plot.triggerRedrawOverlay(); + } + + //if (typeof s == "number") { + // s = series[s]; + //} + + var i = indexOfHighlight(s); + + if (i != -1) { + highlights.splice(i, 1); + plot.triggerRedrawOverlay(); + } + } + + function indexOfHighlight(s) { + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.series == s) return i; + } + return -1; + } + + function drawOverlay(plot, octx) { + var options = plot.getOptions(); + + var radius = + options.series.pie.radius > 1 + ? options.series.pie.radius + : maxRadius * options.series.pie.radius; + + octx.save(); + octx.translate(centerLeft, centerTop); + octx.scale(1, options.series.pie.tilt); + + for (var i = 0; i < highlights.length; ++i) { + drawHighlight(highlights[i].series); + } + + drawDonutHole(octx); + + octx.restore(); + + function drawHighlight(series) { + if (series.angle <= 0 || isNaN(series.angle)) { + return; + } + + //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); + octx.fillStyle = + "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor + octx.beginPath(); + if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) { + octx.moveTo(0, 0); // Center of the pie + } + octx.arc( + 0, + 0, + radius, + series.startAngle, + series.startAngle + series.angle / 2, + false + ); + octx.arc( + 0, + 0, + radius, + series.startAngle + series.angle / 2, + series.startAngle + series.angle, + false + ); + octx.closePath(); + octx.fill(); + } + } + } // end init (plugin body) + + // define pie specific options and their default values + + var options = { + series: { + pie: { + show: false, + radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) + innerRadius: 0 /* for donut */, + startAngle: 3 / 2, + tilt: 1, + shadow: { + left: 5, // shadow left offset + top: 15, // shadow top offset + alpha: 0.02 // shadow alpha + }, + offset: { + top: 0, + left: "auto" + }, + stroke: { + color: "#fff", + width: 1 + }, + label: { + show: "auto", + formatter: function(label, slice) { + return ( + "
    " + + label + + "
    " + + Math.round(slice.percent) + + "%
    " + ); + }, // formatter function + radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) + background: { + color: null, + opacity: 0 + }, + threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) + }, + combine: { + threshold: -1, // percentage at which to combine little slices into one larger slice + color: null, // color to give the new slice (auto-generated if null) + label: "Other" // label to give the new slice + }, + highlight: { + //color: "#fff", // will add this functionality once parseColor is available + opacity: 0.5 + } + } + } + }; + + $.plot.plugins.push({ + init: init, + options: options, + name: "pie", + version: "1.1" + }); })(jQuery); diff --git a/pandora_console/include/graphs/flot/pandora.flot.js b/pandora_console/include/graphs/flot/pandora.flot.js index 55cc748261..c62614ccd3 100644 --- a/pandora_console/include/graphs/flot/pandora.flot.js +++ b/pandora_console/include/graphs/flot/pandora.flot.js @@ -1,4 +1,5 @@ /* global $ */ +/* exported pandoraFlotPie, pandoraFlotPieCustom */ function pandoraFlotPie( graph_id, @@ -14,7 +15,7 @@ function pandoraFlotPie( colors, hide_labels ) { - var labels = labels.split(separator); + labels = labels.split(separator); var data = values.split(separator); if (colors != "") { @@ -92,7 +93,7 @@ function pandoraFlotPie( function pieHover(event, pos, obj) { if (!obj) return; - index = obj.seriesIndex; + var index = obj.seriesIndex; legends.css("color", "#3F3F3D"); legends.eq(index).css("color", ""); } @@ -144,21 +145,14 @@ function pandoraFlotPieCustom( .pop() .split(".") .shift(); - var labels = labels.split(separator); - var legend = legend.split(separator); + labels = labels.split(separator); + legend = legend.split(separator); var data = values.split(separator); var no_data = 0; if (colors != "") { colors = colors.split(separator); } - var colors_data = [ - "#FC4444", - "#FFA631", - "#FAD403", - "#5BB6E5", - "#F2919D", - "#80BA27" - ]; + var color = null; for (var i = 0; i < data.length; i++) { if (colors != "") { @@ -174,28 +168,31 @@ function pandoraFlotPieCustom( if (width <= 450) { show_legend = false; - label_conf = { - show: false - }; - } else { label_conf = { show: true, - radius: 0.75, + radius: 5 / 8, formatter: function(label, series) { + console.log(series); return ( '
    ' + - series.percent.toFixed(2) + - "%
    " + "pt; font-weight:bolder;" + + "text-align:center;padding:2px;color:rgb(63, 63, 61)" + + '">' + + label + + ":
    " + + series.data[0][1] + + "
    " ); }, background: { - opacity: 0.5, - color: "" + opacity: 0.5 } }; + } else { + label_conf = { + show: false + }; } var conf_pie = { @@ -203,8 +200,8 @@ function pandoraFlotPieCustom( pie: { show: true, radius: 3 / 4, - innerRadius: 0.4 - //label: label_conf + innerRadius: 0.4, + label: label_conf } }, legend: { @@ -234,7 +231,7 @@ function pandoraFlotPieCustom( var legends = $("#" + graph_id + " .legendLabel"); var j = 0; legends.each(function() { - //$(this).css('width', $(this).width()); + //$(this).css("width", $(this).width()); $(this).css("font-size", font_size + "pt"); $(this).removeClass("legendLabel"); $(this).addClass(font); @@ -264,19 +261,6 @@ function pandoraFlotPieCustom( return false; }); - var pielegends = $("#" + graph_id + " .pieLabelBackground"); - pielegends.each(function() { - $(this) - .css("transform", "rotate(-35deg)") - .css("color", "black"); - }); - var labelpielegends = $("#" + graph_id + " .pieLabel"); - labelpielegends.each(function() { - $(this) - .css("transform", "rotate(-35deg)") - .css("color", "black"); - }); - // Events $("#" + graph_id).bind("plothover", pieHover); $("#" + graph_id).bind("plotclick", Clickpie); @@ -287,16 +271,17 @@ function pandoraFlotPieCustom( function pieHover(event, pos, obj) { if (!obj) return; - index = obj.seriesIndex; + var index = obj.seriesIndex; legends.css("color", "#3F3F3D"); legends.eq(index).css("color", ""); } function Clickpie(event, pos, obj) { if (!obj) return; - percent = parseFloat(obj.series.percent).toFixed(2); - valor = parseFloat(obj.series.data[0][1]); + var percent = parseFloat(obj.series.percent).toFixed(2); + var valor = parseFloat(obj.series.data[0][1]); + var value = ""; if (valor > 1000000) { value = Math.round((valor / 1000000) * 100) / 100; value = value + "M"; @@ -325,42 +310,6 @@ function pandoraFlotPieCustom( $("#watermark_image_" + graph_id).attr("src") ); } - /* - window.onresize = function(event) { - $.plot($('#' + graph_id), data, conf_pie); - if (no_data == data.length) { - $('#'+graph_id+' .overlay').remove(); - $('#'+graph_id+' .base').remove(); - $('#'+graph_id).prepend(""); - } - var legends = $('#'+graph_id+' .legendLabel'); - var j = 0; - legends.each(function () { - //$(this).css('width', $(this).width()); - $(this).css('font-size', font_size+'pt'); - $(this).removeClass("legendLabel"); - $(this).addClass(font); - $(this).text(legend[j]); - j++; - }); - - if ($('input[name="custom_graph"]').val()) { - $('.legend>div').css('right',($('.legend>div').height()*-1)); - $('.legend>table').css('right',($('.legend>div').height()*-1)); - } - //$('.legend>table').css('border',"1px solid #E2E2E2"); - $('.legend>table').css('background-color',"transparent"); - - var pielegends = $('#'+graph_id+' .pieLabelBackground'); - pielegends.each(function () { - $(this).css('transform', "rotate(-35deg)").css('color', 'black'); - }); - var labelpielegends = $('#'+graph_id+' .pieLabel'); - labelpielegends.each(function () { - $(this).css('transform', "rotate(-35deg)").css('color', 'black'); - }); - } -*/ } function pandoraFlotHBars( @@ -380,12 +329,12 @@ function pandoraFlotHBars( max ) { var colors_data = [ - "#FC4444", + "#e63c52", "#FFA631", - "#FAD403", + "#f3b200", "#5BB6E5", "#F2919D", - "#80BA27" + "#82b92e" ]; values = values.split(separator2); font = font @@ -639,7 +588,7 @@ function pandoraFlotVBars( var colors_data = colors.length > 0 ? colors - : ["#FFA631", "#FC4444", "#FAD403", "#5BB6E5", "#F2919D", "#80BA27"]; + : ["#FFA631", "#e63c52", "#f3b200", "#5BB6E5", "#F2919D", "#82b92e"]; var datas = new Array(); for (i = 0; i < values.length; i++) { @@ -869,7 +818,7 @@ function pandoraFlotSlicebar( var datas = new Array(); - for (i = 0; i < values.length; i++) { + for (var i = 0; i < values.length; i++) { var serie = values[i].split(separator); var aux = new Array(); @@ -1938,6 +1887,8 @@ function pandoraFlotArea( switch (type) { case "line": case 2: + stacked = null; + filled_s = false; break; case 3: stacked = "stack"; @@ -2681,13 +2632,13 @@ function pandoraFlotArea( if (events_data.event_type.search("alert") >= 0) { extra_color = "#FFA631"; } else if (events_data.event_type.search("critical") >= 0) { - extra_color = "#FC4444"; + extra_color = "#e63c52"; } else if (events_data.event_type.search("warning") >= 0) { - extra_color = "#FAD403"; + extra_color = "#f3b200"; } else if (events_data.event_type.search("unknown") >= 0) { - extra_color = "#3BA0FF"; + extra_color = "#4a83f3"; } else if (events_data.event_type.search("normal") >= 0) { - extra_color = "#80BA27"; + extra_color = "#82b92e"; } else { extra_color = "#ffffff"; } @@ -2789,14 +2740,16 @@ function pandoraFlotArea( if (short_data) { formatted = number_format(v, force_integer, "", short_data); } else { - // It is an integer + // It is an integer. if (v - Math.floor(v) == 0) { formatted = number_format(v, force_integer, "", 2); } } - // Get only two decimals - formatted = round_with_decimals(formatted, 100); + // Get only two decimals. + if (typeof formatted != "string") { + formatted = Math.round(formatted * 100) / 100; + } return formatted; } diff --git a/pandora_console/include/graphs/functions_d3.php b/pandora_console/include/graphs/functions_d3.php index 129baaa54e..fea1273015 100644 --- a/pandora_console/include/graphs/functions_d3.php +++ b/pandora_console/include/graphs/functions_d3.php @@ -190,8 +190,8 @@ function d3_bullet_chart( } .bullet { font: 7px sans-serif; } - .bullet .marker.s0 { stroke: #FC4444; stroke-width: 2px; } - .bullet .marker.s1 { stroke: #FAD403; stroke-width: 2px; } + .bullet .marker.s0 { stroke: #e63c52; stroke-width: 2px; } + .bullet .marker.s1 { stroke: #f3b200; stroke-width: 2px; } .bullet .marker.s2 { stroke: steelblue; stroke-width: 2px; } .bullet .tick line { stroke: #666; stroke-width: .5px; } .bullet .range.s0 { fill: #ddd; } @@ -740,6 +740,8 @@ function print_donut_narrow_graph( array $data, $data_total ) { + global $config; + if (empty($data)) { return graph_nodata_image($width, $height, 'pie'); } @@ -754,10 +756,31 @@ function print_donut_narrow_graph( $graph_id = uniqid('graph_'); + // This is for "Style template" in visual styles. + switch ($config['style']) { + case 'pandora': + $textColor = '#000'; + $strokeColor = '#fff'; + break; + + case 'pandora_black': + $textColor = '#fff'; + $strokeColor = '#222'; + break; + + default: + $textColor = '#000'; + $strokeColor = '#fff'; + break; + } + + $textColor = json_encode($textColor); + $strokeColor = json_encode($strokeColor); + $out = "
    "; $out .= include_javascript_d3(true); $out .= "'; // Parent layer. @@ -428,11 +453,9 @@ function flot_pie_chart( include_javascript_dependencies_flot_graph(); $return .= "'; return $return; @@ -508,11 +531,9 @@ function flot_custom_pie_chart( $colors = implode($separator, $temp_colors); $return .= "'; return $return; @@ -608,10 +629,8 @@ function flot_hcolumn_chart($graph_data, $width, $height, $water_mark, $font='', // Javascript code $return .= "'; return $return; @@ -701,7 +720,6 @@ function flot_vcolumn_chart($graph_data, $width, $height, $color, $legend, $long // Javascript code $return .= "'; return $return; @@ -887,9 +904,7 @@ function flot_slicesbar_graph( // Javascript code $return .= "'; diff --git a/pandora_console/include/graphs/pandora.d3.js b/pandora_console/include/graphs/pandora.d3.js index 427de827e3..a334a85357 100644 --- a/pandora_console/include/graphs/pandora.d3.js +++ b/pandora_console/include/graphs/pandora.d3.js @@ -1614,9 +1614,9 @@ function print_phases_donut(recipient, phases) { .insert("path") .style("fill", function(d) { if (d.data.value == 0) { - return "#80BA27"; + return "#82b92e"; } else { - return "#FC4444"; + return "#e63c52"; } }) .attr("class", "slice"); @@ -2762,7 +2762,14 @@ function valueToBytes(value) { return value.toFixed(2) + shorts[pos] + "B"; } -function donutNarrowGraph(colores, width, height, total) { +function donutNarrowGraph( + colores, + width, + height, + total, + textColor, + strokeColor +) { // Default settings var donutbody = d3.select("body"); var data = {}; @@ -2848,8 +2855,7 @@ function donutNarrowGraph(colores, width, height, total) { this._current = d; }) .attr("d", arc) - .attr("stroke", "white") - .style("stroke-width", 2) + .attr("stroke", strokeColor) .style("fill", function(d) { return color(d.data.key); }); @@ -2873,9 +2879,7 @@ function donutNarrowGraph(colores, width, height, total) { .attr("y", 0 + radius / 10) .attr("class", "text-tooltip") .style("text-anchor", "middle") - .attr("font-weight", "bold") - .style("font-family", "Arial, Verdana") - //.attr("fill", "#82b92e") + .attr("fill", textColor) .style("font-size", function(d) { if (normal_status) { percentage_normal = (normal_status * 100) / total; @@ -2905,6 +2909,7 @@ function donutNarrowGraph(colores, width, height, total) { /* .attr("fill", function(d) { return color(obj.data.key); })*/ + .attr("fill", textColor) .style("font-size", function(d) { percentage = (d[obj.data.key] * 100) / total; if (Number.isInteger(percentage)) { diff --git a/pandora_console/include/help/clippy/module_unknow.php b/pandora_console/include/help/clippy/module_unknow.php index 28656c9ba2..d3a6245032 100644 --- a/pandora_console/include/help/clippy/module_unknow.php +++ b/pandora_console/include/help/clippy/module_unknow.php @@ -32,7 +32,7 @@ function clippy_module_unknow() $return_tours['tours']['module_unknow']['steps'] = []; $return_tours['tours']['module_unknow']['steps'][] = [ 'init_step_context' => true, - 'intro' => ''.''.''.''.''.''.''.'
    '.__('You have unknown modules in this agent.').'
    '.__('Unknown modules are modules which receive data normally at least in one occassion, but at this time are not receving data. Please check our troubleshoot help page to help you determine why you have unknown modules.').ui_print_help_icon('context_module_unknow', true, '', 'images/help.png').'
    ', + 'intro' => ''.''.''.''.''.''.''.'
    '.__('You have unknown modules in this agent.').'
    '.__('Unknown modules are modules which receive data normally at least in one occassion, but at this time are not receving data. Please check our troubleshoot help page to help you determine why you have unknown modules.').'
    ', ]; $return_tours['tours']['module_unknow']['conf'] = []; $return_tours['tours']['module_unknow']['conf']['autostart'] = false; diff --git a/pandora_console/include/javascript/buttons.dataTables.min.js b/pandora_console/include/javascript/buttons.dataTables.min.js new file mode 100644 index 0000000000..90389767ac --- /dev/null +++ b/pandora_console/include/javascript/buttons.dataTables.min.js @@ -0,0 +1,5 @@ +/*! + DataTables styling wrapper for Buttons + ©2018 SpryMedia Ltd - datatables.net/license +*/ +(function(c){"function"===typeof define&&define.amd?define(["jquery","datatables.net-dt","datatables.net-buttons"],function(a){return c(a,window,document)}):"object"===typeof exports?module.exports=function(a,b){a||(a=window);b&&b.fn.dataTable||(b=require("datatables.net-dt")(a,b).$);b.fn.dataTable.Buttons||require("datatables.net-buttons")(a,b);return c(b,a,a.document)}:c(jQuery,window,document)})(function(c,a,b,d){return c.fn.dataTable}); diff --git a/pandora_console/include/javascript/buttons.html5.min.js b/pandora_console/include/javascript/buttons.html5.min.js new file mode 100644 index 0000000000..deee7fee68 --- /dev/null +++ b/pandora_console/include/javascript/buttons.html5.min.js @@ -0,0 +1,35 @@ +/*! + HTML5 export buttons for Buttons and DataTables. + 2016 SpryMedia Ltd - datatables.net/license + + FileSaver.js (1.3.3) - MIT license + Copyright © 2016 Eli Grey - http://eligrey.com +*/ +(function(f){"function"===typeof define&&define.amd?define(["jquery","datatables.net","datatables.net-buttons"],function(g){return f(g,window,document)}):"object"===typeof exports?module.exports=function(g,p,z,t){g||(g=window);p&&p.fn.dataTable||(p=require("datatables.net")(g,p).$);p.fn.dataTable.Buttons||require("datatables.net-buttons")(g,p);return f(p,g,g.document,z,t)}:f(jQuery,window,document)})(function(f,g,p,z,t,w){function A(a){for(var b="";0<=a;)b=String.fromCharCode(a%26+65)+b,a=Math.floor(a/ +26)-1;return b}function E(a,b){y===w&&(y=-1===C.serializeToString(f.parseXML(F["xl/worksheets/sheet1.xml"])).indexOf("xmlns:r"));f.each(b,function(b,c){if(f.isPlainObject(c))b=a.folder(b),E(b,c);else{if(y){var d=c.childNodes[0],e,h=[];for(e=d.attributes.length-1;0<=e;e--){var m=d.attributes[e].nodeName;var k=d.attributes[e].nodeValue;-1!==m.indexOf(":")&&(h.push({name:m,value:k}),d.removeAttribute(m))}e=0;for(m=h.length;e'+c),c=c.replace(/_dt_b_namespace_token_/g,":"),c=c.replace(/xmlns:NS[\d]+="" NS[\d]+:/g,""));c=c.replace(/<([^<>]*?) xmlns=""([^<>]*?)>/g,"<$1 $2>");a.file(b,c)}})}function r(a,b,d){var c=a.createElement(b);d&&(d.attr&&f(c).attr(d.attr),d.children&&f.each(d.children,function(a,b){c.appendChild(b)}),null!==d.text&&d.text!==w&&c.appendChild(a.createTextNode(d.text))); +return c}function L(a,b){var d=a.header[b].length;a.footer&&a.footer[b].length>d&&(d=a.footer[b].length);for(var c=0,f=a.body.length;cd&&(d=e);if(401*a[1]?!0:!1};try{var C=new XMLSerializer,y}catch(a){}var F={"_rels/.rels":'', +"xl/_rels/workbook.xml.rels":'',"[Content_Types].xml":'', +"xl/workbook.xml":'', +"xl/worksheets/sheet1.xml":'',"xl/styles.xml":''}, +K=[{match:/^\-?\d+\.\d%$/,style:60,fmt:function(a){return a/100}},{match:/^\-?\d+\.?\d*%$/,style:56,fmt:function(a){return a/100}},{match:/^\-?\$[\d,]+.?\d*$/,style:57},{match:/^\-?£[\d,]+.?\d*$/,style:58},{match:/^\-?€[\d,]+.?\d*$/,style:59},{match:/^\-?\d+$/,style:65},{match:/^\-?\d+\.\d{2}$/,style:66},{match:/^\([\d,]+\)$/,style:61,fmt:function(a){return-1*a.replace(/[\(\)]/g,"")}},{match:/^\([\d,]+\.\d{2}\)$/,style:62,fmt:function(a){return-1*a.replace(/[\(\)]/g,"")}},{match:/^\-?[\d,]+$/,style:63}, +{match:/^\-?[\d,]+\.\d{2}$/,style:64}];v.ext.buttons.copyHtml5={className:"buttons-copy buttons-html5",text:function(a){return a.i18n("buttons.copy","Copy")},action:function(a,b,d,c){this.processing(!0);var g=this;a=I(b,c);var e=b.buttons.exportInfo(c),h=H(c),m=a.str;d=f("
    ").css({height:1,width:1,overflow:"hidden",position:"fixed",top:0,left:0});e.title&&(m=e.title+h+h+m);e.messageTop&&(m=e.messageTop+h+h+m);e.messageBottom&&(m=m+h+h+e.messageBottom);c.customize&&(m=c.customize(m,c,b));c=f("",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w("'; // This tag is included in the buffer passed to ui_process_page_head so -// technically it can be stripped +// technically it can be stripped. echo ''."\n"; require_once 'include/functions_themes.php'; @@ -212,13 +232,13 @@ $config['remote_addr'] = $_SERVER['REMOTE_ADDR']; $sec2 = get_parameter_get('sec2'); $sec2 = safe_url_extraclean($sec2); $page = $sec2; -// Reference variable for old time sake +// Reference variable for old time sake. $sec = get_parameter_get('sec'); $sec = safe_url_extraclean($sec); $process_login = false; -// Update user password +// Update user password. $change_pass = get_parameter_post('renew_password', 0); if ($change_pass == 1) { @@ -235,14 +255,14 @@ $searchPage = false; $search = get_parameter_get('head_search_keywords'); if (strlen($search) > 0) { $config['search_keywords'] = io_safe_input(trim(io_safe_output(get_parameter('keywords')))); - // If not search category providad, we'll use an agent search + // If not search category providad, we'll use an agent search. $config['search_category'] = get_parameter('search_category', 'all'); if (($config['search_keywords'] != 'Enter keywords to search') && (strlen($config['search_keywords']) > 0)) { $searchPage = true; } } -// Login process +// Login process. if (! isset($config['id_user'])) { // Clear error messages. unset($_COOKIE['errormsg']); @@ -250,50 +270,53 @@ if (! isset($config['id_user'])) { if (isset($_GET['login'])) { include_once 'include/functions_db.php'; - // Include it to use escape_string_sql function + // Include it to use escape_string_sql function. $config['auth_error'] = ''; - // Set this to the error message from the authorization mechanism + // Set this to the error message from the authorization mechanism. $nick = get_parameter_post('nick'); - // This is the variable with the login + // This is the variable with the login. $pass = get_parameter_post('pass'); - // This is the variable with the password + // This is the variable with the password. $nick = db_escape_string_sql($nick); $pass = db_escape_string_sql($pass); - // Since now, only the $pass variable are needed + // Since now, only the $pass variable are needed. unset($_GET['pass'], $_POST['pass'], $_REQUEST['pass']); - // If the auth_code exists, we assume the user has come through the double auth page + // If the auth_code exists, we assume the user has come from + // double authorization page. if (isset($_POST['auth_code'])) { $double_auth_success = false; - // The double authentication is activated and the user has surpassed the first step (the login). + // The double authentication is activated and the user has + // surpassed the first step (the login). // Now the authentication code provided will be checked. if (isset($_SESSION['prepared_login_da'])) { if (isset($_SESSION['prepared_login_da']['id_user']) && isset($_SESSION['prepared_login_da']['timestamp']) ) { - // The user has a maximum of 5 minutes to introduce the double auth code + // The user has a maximum of 5 minutes to introduce + // the double auth code. $dauth_period = SECONDS_2MINUTES; $now = time(); $dauth_time = $_SESSION['prepared_login_da']['timestamp']; if (($now - $dauth_period) < $dauth_time) { - // Nick + // Nick. $nick = $_SESSION['prepared_login_da']['id_user']; - // Code + // Code. $code = (string) get_parameter_post('auth_code'); if (!empty($code)) { $result = validate_double_auth_code($nick, $code); if ($result === true) { - // Double auth success + // Double auth success. $double_auth_success = true; } else { - // Screen + // Screen. $login_screen = 'double_auth'; - // Error message + // Error message. $config['auth_error'] = __('Invalid code'); if (!isset($_SESSION['prepared_login_da']['attempts'])) { @@ -303,9 +326,9 @@ if (! isset($config['id_user'])) { $_SESSION['prepared_login_da']['attempts']++; } } else { - // Screen + // Screen. $login_screen = 'double_auth'; - // Error message + // Error message. $config['auth_error'] = __("The code shouldn't be empty"); if (!isset($_SESSION['prepared_login_da']['attempts'])) { @@ -315,27 +338,27 @@ if (! isset($config['id_user'])) { $_SESSION['prepared_login_da']['attempts']++; } } else { - // Expired login + // Expired login. unset($_SESSION['prepared_login_da']); - // Error message + // Error message. $config['auth_error'] = __('Expired login'); } } else { - // If the code doesn't exist, remove the prepared login + // If the code doesn't exist, remove the prepared login. unset($_SESSION['prepared_login_da']); - // Error message + // Error message. $config['auth_error'] = __('Login error'); } - } - // If $_SESSION['prepared_login_da'] doesn't exist, the user have to do the login again - else { - // Error message + } else { + // If $_SESSION['prepared_login_da'] doesn't exist, the user + // must login again. + // Error message. $config['auth_error'] = __('Login error'); } - // Remove the authenticator code + // Remove the authenticator code. unset($_POST['auth_code'], $code); if (!$double_auth_success) { @@ -347,6 +370,8 @@ if (! isset($config['id_user'])) { $_SERVER['REMOTE_ADDR'] ); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -355,18 +380,28 @@ if (! isset($config['id_user'])) { $login_button_saml = get_parameter('login_button_saml', false); if (isset($double_auth_success) && $double_auth_success) { - // This values are true cause there are checked before complete the 2nd auth step + // This values are true cause there are checked before complete + // the 2nd auth step. $nick_in_db = $_SESSION['prepared_login_da']['id_user']; $expired_pass = false; } else if (($config['auth'] == 'saml') && ($login_button_saml)) { - include_once ENTERPRISE_DIR.'/include/auth/saml.php'; + $saml_configured = include_once $config['homedir'].'/'.ENTERPRISE_DIR.'/include/auth/saml.php'; + + if (!$saml_configured) { + include_once 'general/noaccesssaml.php'; + } $saml_user_id = saml_process_user_login(); + if (!$saml_user_id) { + include_once 'general/noaccesssaml.php'; + } + + $nick_in_db = $saml_user_id; if (!$nick_in_db) { include_once $config['saml_path'].'simplesamlphp/lib/_autoload.php'; - $as = new SimpleSAML_Auth_Simple('PandoraFMS'); + $as = new SimpleSAML_Auth_Simple($config['saml_source']); $as->logout(); } } else { @@ -391,28 +426,34 @@ if (! isset($config['id_user'])) { include_once 'general/login_page.php'; db_pandora_audit('Password expired', 'Password expired: '.$nick, $nick); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); } - // Checks if password has expired + // Checks if password has expired. $check_status = check_pass_status($nick, $pass); switch ($check_status) { case PASSSWORD_POLICIES_FIRST_CHANGE: - // first change + // First change. case PASSSWORD_POLICIES_EXPIRED: - // pass expired + // Pass expired. $expired_pass = true; login_change_password($nick, '', $check_status); break; + + default: + // Ignore. + break; } } } if (($nick_in_db !== false) && $expired_pass) { - // login ok and password has expired + // Login ok and password has expired. include_once 'general/login_page.php'; db_pandora_audit( 'Password expired', @@ -420,30 +461,38 @@ if (! isset($config['id_user'])) { $nick ); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); } else if (($nick_in_db !== false) && (!$expired_pass)) { - // login ok and password has not expired - // Double auth check - if ((!isset($double_auth_success) || !$double_auth_success) && is_double_auth_enabled($nick_in_db)) { - // Store this values in the session to know if the user login was correct + // Login ok and password has not expired. + // Double auth check. + if ((!isset($double_auth_success) + || !$double_auth_success) + && is_double_auth_enabled($nick_in_db) + ) { + // Store this values in the session to know if the user login + // was correct. $_SESSION['prepared_login_da'] = [ 'id_user' => $nick_in_db, 'timestamp' => time(), 'attempts' => 0, ]; - // Load the page to introduce the double auth code + // Load the page to introduce the double auth code. $login_screen = 'double_auth'; include_once 'general/login_page.php'; while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); } - // login ok and password has not expired + // Login ok and password has not expired. $process_login = true; if (is_user_admin($nick)) { @@ -455,7 +504,7 @@ if (! isset($config['id_user'])) { if (!isset($_GET['sec2']) && !isset($_GET['sec'])) { // Avoid the show homepage when the user go to // a specific section of pandora - // for example when timeout the sesion + // for example when timeout the sesion. unset($_GET['sec2']); $_GET['sec'] = 'general/logon_ok'; $home_page = ''; @@ -486,6 +535,7 @@ if (! isset($config['id_user'])) { break; case 'Default': + default: $_GET['sec'] = 'general/logon_ok'; break; @@ -521,11 +571,14 @@ if (! isset($config['id_user'])) { $_SESSION['id_usuario'] = $nick_in_db; $config['id_user'] = $nick_in_db; - // Check if connection goes through F5 balancer. If it does, then don't call config_prepare_session() or user will be back to login all the time + // Check if connection goes through F5 balancer. If it does, then + // don't call config_prepare_session() or user will be back to login + // all the time. $prepare_session = true; foreach ($_COOKIE as $key => $value) { if (preg_match('/BIGipServer*/', $key)) { $prepare_session = false; + break; } } @@ -534,9 +587,13 @@ if (! isset($config['id_user'])) { } if (is_user_admin($config['id_user'])) { - // PHP configuration values - $PHPupload_max_filesize = config_return_in_bytes(ini_get('upload_max_filesize')); - $PHPmemory_limit = config_return_in_bytes(ini_get('memory_limit')); + // PHP configuration values. + $PHPupload_max_filesize = config_return_in_bytes( + ini_get('upload_max_filesize') + ); + $PHPmemory_limit = config_return_in_bytes( + ini_get('memory_limit') + ); $PHPmax_execution_time = ini_get('max_execution_time'); if ($PHPmax_execution_time !== '0') { @@ -571,43 +628,60 @@ if (! isset($config['id_user'])) { $l10n = null; if (file_exists('./include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader(new CachedFileReader('./include/languages/'.$user_language.'.mo')); + $cacheFileReader = new CachedFileReader( + './include/languages/'.$user_language.'.mo' + ); + $l10n = new gettext_reader($cacheFileReader); $l10n->load_tables(); } } else { - // login wrong + // Login wrong. $blocked = false; - if ((!is_user_admin($nick) || $config['enable_pass_policy_admin']) && file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + if ((!is_user_admin($nick) || $config['enable_pass_policy_admin']) + && file_exists(ENTERPRISE_DIR.'/load_enterprise.php') + ) { $blocked = login_check_blocked($nick); } if (!$blocked) { if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + // Checks failed attempts. login_check_failed($nick); - // Checks failed attempts } $login_failed = true; include_once 'general/login_page.php'; - db_pandora_audit('Logon Failed', 'Invalid login: '.$nick, $nick); + db_pandora_audit( + 'Logon Failed', + 'Invalid login: '.$nick, + $nick + ); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); } else { include_once 'general/login_page.php'; - db_pandora_audit('Logon Failed', 'Invalid login: '.$nick, $nick); + db_pandora_audit( + 'Logon Failed', + 'Invalid login: '.$nick, + $nick + ); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); } } - // Form the url + // Form the url. $query_params_redirect = $_GET; - // Visual console do not want sec2 + // Visual console do not want sec2. if ($home_page == 'Visual console') { unset($query_params_redirect['sec2']); } @@ -621,15 +695,19 @@ if (! isset($config['id_user'])) { $redirect_url .= '&'.safe_url_extraclean($key).'='.safe_url_extraclean($value); } - header('Location: '.$config['homeurl'].'index.php'.$redirect_url); + header('Location: '.ui_get_full_url('index.php'.$redirect_url)); exit; // Always exit after sending location headers. } else if (isset($_GET['loginhash'])) { - // Hash login process + // Hash login process. $loginhash_data = get_parameter('loginhash_data', ''); $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); - if ($config['loginhash_pwd'] != '' && $loginhash_data == md5($loginhash_user.io_output_password($config['loginhash_pwd']))) { + if ($config['loginhash_pwd'] != '' + && $loginhash_data == md5( + $loginhash_user.io_output_password($config['loginhash_pwd']) + ) + ) { db_logon($loginhash_user, $_SERVER['REMOTE_ADDR']); $_SESSION['id_usuario'] = $loginhash_user; $config['id_user'] = $loginhash_user; @@ -637,6 +715,8 @@ if (! isset($config['id_user'])) { include_once 'general/login_page.php'; db_pandora_audit('Logon Failed (loginhash', '', 'system'); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -758,7 +838,7 @@ if (! isset($config['id_user'])) { $body .= '

    '; $body .= __('Please click the link below to reset your password'); $body .= '

    '; - $body .= ''.__('Reset your password').''; + $body .= ''.__('Reset your password').''; $body .= '

    '; $body .= get_product_name(); $body .= '

    '; @@ -781,6 +861,8 @@ if (! isset($config['id_user'])) { } while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -790,11 +872,20 @@ if (! isset($config['id_user'])) { $loginhash_data = get_parameter('loginhash_data', ''); $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); $iduser = $_SESSION['id_usuario']; - // logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); check why is not available + + /* + * Check why is not available. + * logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); + */ + unset($_SESSION['id_usuario']); unset($iduser); - if ($config['loginhash_pwd'] != '' && $loginhash_data == md5($loginhash_user.io_output_password($config['loginhash_pwd']))) { + if ($config['loginhash_pwd'] != '' + && $loginhash_data == md5( + $loginhash_user.io_output_password($config['loginhash_pwd']) + ) + ) { db_logon($loginhash_user, $_SERVER['REMOTE_ADDR']); $_SESSION['id_usuario'] = $loginhash_user; $config['id_user'] = $loginhash_user; @@ -802,6 +893,8 @@ if (! isset($config['id_user'])) { include_once 'general/login_page.php'; db_pandora_audit('Logon Failed (loginhash', '', 'system'); while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -814,7 +907,7 @@ if (! isset($config['id_user'])) { '*' ); if ($user_in_db == false) { - // logout + // Logout. $_REQUEST = []; $_GET = []; $_POST = []; @@ -825,6 +918,8 @@ if (! isset($config['id_user'])) { unset($iduser); include_once 'general/login_page.php'; while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -832,7 +927,7 @@ if (! isset($config['id_user'])) { if (((bool) $user_in_db['is_admin'] === false) && ((bool) $user_in_db['not_login'] === true) ) { - // logout + // Logout. $_REQUEST = []; $_GET = []; $_POST = []; @@ -843,6 +938,8 @@ if (! isset($config['id_user'])) { unset($iduser); include_once 'general/login_page.php'; while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -850,12 +947,12 @@ if (! isset($config['id_user'])) { } } -// Enterprise support +// Enterprise support. if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { include_once ENTERPRISE_DIR.'/load_enterprise.php'; } -// Log off +// Log off. if (isset($_GET['bye'])) { include 'general/logoff.php'; $iduser = $_SESSION['id_usuario']; @@ -873,6 +970,8 @@ if (isset($_GET['bye'])) { } while (@ob_end_flush()) { + // Dumping... + continue; } exit(''); @@ -880,10 +979,11 @@ if (isset($_GET['bye'])) { clear_pandora_error_for_header(); -// ---------------------------------------------------------------------- -// EXTENSIONS -// ---------------------------------------------------------------------- /* + * ---------------------------------------------------------------------- + * EXTENSIONS + * ---------------------------------------------------------------------- + * * Load the basic configurations of extension and add extensions into menu. * Load here, because if not, some extensions not load well, I don't why. */ @@ -892,7 +992,7 @@ $config['logged'] = false; extensions_load_extensions($process_login); if ($process_login) { - // Call all extensions login function + // Call all extensions login function. extensions_call_login_function(); unset($_SESSION['new_update']); @@ -983,7 +1083,7 @@ if (get_parameter('login', 0) !== 0) { } } -// Header +// Header. if ($config['pure'] == 0) { echo '

    '; - // main_pure + // Main pure. } echo '
    '; @@ -1189,27 +1292,30 @@ echo '
    '; if ($config['pure'] == 0) { echo '
    '; - // container div + // Container div. + echo '
    '; echo '
    '; + echo ''; } -// Clippy function +// Clippy function. require_once 'include/functions_clippy.php'; clippy_start($sec2); while (@ob_end_flush()) { + // Dumping... + continue; } db_print_database_debug(); echo ''; $run_time = format_numeric((microtime(true) - $config['start_time']), 3); -echo "\n\n"; +echo "\n\n"; -// Values from PHP to be recovered from JAVASCRIPT +// Values from PHP to be recovered from JAVASCRIPT. require 'include/php_to_js_values.php'; @@ -1217,12 +1323,16 @@ require 'include/php_to_js_values.php'; @@ -402,7 +403,7 @@ $alias = db_get_value('alias', 'tagente', 'id_agente', $id_agent); echo '
    '.html_print_image('images/arrow_down_green.png', true, ['class' => 'module_graph_menu_arrow', 'float' => 'left'], false, false, true).' - '.__('Graph configuration menu').ui_print_help_icon('graphs', true, $config['homeurl'], 'images/help_g.png', true).' + '.__('Graph configuration menu').' '.html_print_image('images/config.png', true, ['float' => 'right'], false, false, true).'
    diff --git a/pandora_console/operation/agentes/status_events.php b/pandora_console/operation/agentes/status_events.php index 5e6e060f82..df30d75dda 100755 --- a/pandora_console/operation/agentes/status_events.php +++ b/pandora_console/operation/agentes/status_events.php @@ -25,6 +25,7 @@ ui_toggle( "
    ".html_print_image('images/spinner.gif', true).'
    ', __('Latest events for this agent'), __('Latest events for this agent'), + '', false, false, '', diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 447baa3556..0f7257663a 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -421,7 +421,7 @@ if (!is_metaconsole()) { $table->data[0][5] = html_print_select($rows_select, 'modulegroup', $modulegroup, '', __('All'), -1, true, false, true, '', false, 'width: 120px;'); -$table->rowspan[0][6] = 2; +$table->rowspan[0][6] = 3; $table->data[0][6] = html_print_submit_button( __('Show'), 'uptbutton', @@ -705,13 +705,14 @@ if (is_metaconsole()) { html_print_table($table_custom_fields, true), __('Advanced Options'), '', + '', true, true ); $filters .= html_print_table($table, true); $filters .= ''; - ui_toggle($filters, __('Show Options'), '', false); + ui_toggle($filters, __('Show Options'), '', '', false); } else { $table->colspan[3][0] = 7; $table->cellstyle[3][0] = 'padding-left: 10px;'; @@ -722,8 +723,12 @@ if (is_metaconsole()) { ), __('Agent custom fields'), '', + '', true, - true + true, + '', + 'white-box-content', + 'white_table_graph' ); $filters .= html_print_table($table, true); @@ -1389,6 +1394,34 @@ if (!empty($result)) { true ); } + } else if ($row['estado'] == 3) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').': '.$row['datos'], + true + ); + } + } else if ($row['estado'] == 4) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_NO_DATA, + __('NO DATA').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_NO_DATA, + __('NO DATA').': '.$row['datos'], + true + ); + } } else { $last_status = modules_get_agentmodule_last_status( $row['id_agente_modulo'] diff --git a/pandora_console/operation/agentes/tactical.php b/pandora_console/operation/agentes/tactical.php index 10e4ff5736..1a54e84afc 100755 --- a/pandora_console/operation/agentes/tactical.php +++ b/pandora_console/operation/agentes/tactical.php @@ -116,13 +116,13 @@ if (!empty($all_data)) { } echo ''; -echo ''; echo '
    '; +echo ''; // --------------------------------------------------------------------- // The status horizontal bars (Global health, Monitor sanity... // --------------------------------------------------------------------- $table = new stdClass(); $table->width = '100%'; -$table->class = 'info_table no-td-borders'; +$table->class = 'info_table no-td-borders td-bg-white'; $table->cellpadding = 2; $table->cellspacing = 2; $table->border = 0; @@ -130,7 +130,6 @@ $table->head = []; $table->data = []; $table->style = []; -$table->head[0] = ''.__('Report of State').''; $stats = reporting_get_stats_indicators($data, 120, 10, false); $status = ''; foreach ($stats as $stat) { @@ -166,7 +165,13 @@ if ($is_admin) { $table->rowclass[] = ''; } -html_print_table($table); +ui_toggle( + html_print_table($table, true), + __('Report of State'), + '', + '', + false +); echo ''; // Left column @@ -190,7 +195,8 @@ if (check_acl($config['id_user'], 0, 'ER')) { ui_toggle( $events, __('Latest events'), - false, + '', + '', false ); } @@ -210,7 +216,15 @@ $out = '
    '.__('Event graph by agent').''.html_print_image('images/spinner.gif', true, ['id' => 'spinner_graphic_event_group']).''; $out .= '
    '; -echo $out; + + +ui_toggle( + $out, + __('Event graphs'), + '', + '', + false +); echo '
    '; diff --git a/pandora_console/operation/agentes/ver_agente.php b/pandora_console/operation/agentes/ver_agente.php index 9bed24a3db..7444dda595 100644 --- a/pandora_console/operation/agentes/ver_agente.php +++ b/pandora_console/operation/agentes/ver_agente.php @@ -62,6 +62,37 @@ if (is_ajax()) { $agent_alias = get_parameter('alias', ''); $agents_inserted = get_parameter('agents_inserted', []); $id_group = (int) get_parameter('id_group'); + + $refresh_contact = get_parameter('refresh_contact', 0); + + if ($refresh_contact) { + $id_agente = get_parameter('id_agente', 0); + if ($id_agente > 0) { + $last_contact = db_get_value_sql( + sprintf( + 'SELECT format(intervalo,2) - (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(IF(ultimo_contacto > ultimo_contacto_remoto, ultimo_contacto, ultimo_contacto_remoto))) as "val" + FROM `tagente` + WHERE id_agente = %d ', + $id_agente + ) + ); + + $progress = agents_get_next_contact($id_agente); + if ($progress < 0 || $progress > 100) { + $progress = 100; + } + + echo json_encode( + [ + 'progress' => $progress, + 'last_contact' => $last_contact, + ] + ); + } + + return; + } + if ($get_agents_group_json) { $id_group = (int) get_parameter('id_group'); $recursion = (bool) get_parameter('recursion'); @@ -1528,8 +1559,11 @@ switch ($tab) { include 'estado_monitores.php'; echo ""; include 'alerts_status.php'; - echo ""; - include 'status_events.php'; + // Check permissions to read events + if (check_acl($config['id_user'], 0, 'ER')) { + echo ""; + include 'status_events.php'; + } break; case 'data_view': diff --git a/pandora_console/operation/events/event_statistics.php b/pandora_console/operation/events/event_statistics.php index 437ec0f47c..00dd1f4bc6 100644 --- a/pandora_console/operation/events/event_statistics.php +++ b/pandora_console/operation/events/event_statistics.php @@ -1,30 +1,48 @@ '; @@ -44,7 +62,7 @@ echo ''; echo ''; echo "'; echo ''; @@ -65,7 +83,7 @@ if (!users_is_admin()) { echo ''; echo "'; echo "'; echo ''; diff --git a/pandora_console/operation/events/events.build_query.php b/pandora_console/operation/events/events.build_query.php index f915a5093b..7da35b6977 100755 --- a/pandora_console/operation/events/events.build_query.php +++ b/pandora_console/operation/events/events.build_query.php @@ -142,41 +142,43 @@ switch ($status) { break; } - -$events_wi_cdata = db_get_all_rows_sql('SELECT id_evento,custom_data from tevento WHERE custom_data != ""'); -$count_events = 0; -$events_wi_cdata_id = 'OR id_evento IN ('; -if ($events_wi_cdata === false) { - $events_wi_cdata = []; -} - -foreach ($events_wi_cdata as $key => $value) { - $needle = base64_decode($value['custom_data']); - if (($needle != '') && ($search != '')) { - if (strpos(strtolower($needle), strtolower($search)) != false) { - $events_wi_cdata_id .= $value['id_evento']; - $count_events++; - } - } - - if ($value !== end($events_wi_cdata) && $count_events > 0) { - $events_wi_cdata_id .= ','; - $events_wi_cdata_id = str_replace(',,', ',', $events_wi_cdata_id); - } -} - -$events_wi_cdata_id .= ')'; - -$events_wi_cdata_id = str_replace(',)', ')', $events_wi_cdata_id); - -if ($count_events == 0) { - $events_wi_cdata_id = ''; -} - +/* + * Never use things like this. + * + * $events_wi_cdata = db_get_all_rows_sql('SELECT id_evento,custom_data from tevento WHERE custom_data != ""'); + * $count_events = 0; + * $events_wi_cdata_id = 'OR id_evento IN ('; + * if ($events_wi_cdata === false) { + * $events_wi_cdata = []; + * } + * + * foreach ($events_wi_cdata as $key => $value) { + * $needle = base64_decode($value['custom_data']); + * if (($needle != '') && ($search != '')) { + * if (strpos(strtolower($needle), strtolower($search)) != false) { + * $events_wi_cdata_id .= $value['id_evento']; + * $count_events++; + * } + * } + * + * if ($value !== end($events_wi_cdata) && $count_events > 0) { + * $events_wi_cdata_id .= ','; + * $events_wi_cdata_id = str_replace(',,', ',', $events_wi_cdata_id); + * } + * } + * + * $events_wi_cdata_id .= ')'; + * + * $events_wi_cdata_id = str_replace(',)', ')', $events_wi_cdata_id); + * + * if ($count_events == 0) { + * $events_wi_cdata_id = ''; + * } + */ if ($search != '') { $filter_resume['free_search'] = $search; - $sql_post .= " AND (evento LIKE '%".$search."%' OR id_evento LIKE '%$search%' ".$events_wi_cdata_id.')'; + $sql_post .= " AND (evento LIKE '%".$search."%' OR id_evento LIKE '%$search%' )"; } if ($event_type != '') { diff --git a/pandora_console/operation/events/events.build_table.php b/pandora_console/operation/events/events.build_table.php index 3e112f3fb8..a07ec2a703 100644 --- a/pandora_console/operation/events/events.build_table.php +++ b/pandora_console/operation/events/events.build_table.php @@ -29,7 +29,7 @@ $table->id = 'eventtable'; $table->cellpadding = 4; $table->cellspacing = 4; if (!isset($table->class)) { - $table->class = 'databox data'; + $table->class = 'info_table'; } $table->head = []; @@ -91,11 +91,11 @@ if ($group_rep == 2) { if ($res['event_type'] == 'alert_fired') { $table->rowstyle[$key] = 'background: #FFA631;'; } else if ($res['event_type'] == 'going_up_critical' || $res['event_type'] == 'going_down_critical') { - $table->rowstyle[$key] = 'background: #FC4444;'; + $table->rowstyle[$key] = 'background: #e63c52;'; } else if ($res['event_type'] == 'going_up_warning' || $res['event_type'] == 'going_down_warning') { - $table->rowstyle[$key] = 'background: #FAD403;'; + $table->rowstyle[$key] = 'background: #f3b200;'; } else if ($res['event_type'] == 'going_up_normal' || $res['event_type'] == 'going_down_normal') { - $table->rowstyle[$key] = 'background: #80BA27;'; + $table->rowstyle[$key] = 'background: #82b92e;'; } else if ($res['event_type'] == 'going_unknown') { $table->rowstyle[$key] = 'background: #B2B2B2;'; } @@ -990,12 +990,12 @@ if ($group_rep == 2) { html_print_button(__('Execute event response'), 'submit_event_response', false, 'execute_event_response(true);', 'class="sub next"'); echo "'; echo ''; - echo '
    "; - echo grafico_eventos_usuario(320, 296); + echo grafico_eventos_usuario(320, 280); echo '
    "; - echo grafico_eventos_grupo(300, 200, $where); + echo grafico_eventos_grupo(300, 250, $where); echo '"; @@ -83,7 +101,7 @@ if (!users_is_admin()) { ]; } - echo graph_events_validated(320, 296, $extra_filter); + echo graph_events_validated(320, 250, $extra_filter); echo '
    '.''; + $string .= ''; } if ($group_by) { @@ -1060,7 +1095,7 @@ if ($traps !== false) { } } -// No matching traps +// No matching traps. if ($idx == 0) { echo '
    '.__('No matching traps found').'
    '; } else { diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index 9e267c5c2d..b8b42ad945 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -426,24 +426,25 @@ if (check_acl($config['id_user'], 0, 'ER')) { ).''; } +if (!$config['disabled_newsletter']) { + $newsletter = '

    '.__('Newsletter Subscribed').':

    '; + if ($user_info['middlename'] > 0) { + $newsletter .= ''.__('Already subscribed to %s newsletter', get_product_name()).''; + } else { + $newsletter .= ''.__('Subscribe to our newsletter').'
    '; + $newsletter_reminder = '

    '.__('Newsletter Reminder').':

    '; + $newsletter_reminder .= html_print_switch( + [ + 'name' => 'newsletter_reminder', + 'value' => $newsletter_reminder_value, + 'disabled' => false, + ] + ); + } -$newsletter = '

    '.__('Newsletter Subscribed').':

    '; -if ($user_info['middlename'] > 0) { - $newsletter .= ''.__('Already subscribed to %s newsletter', get_product_name()).''; -} else { - $newsletter .= ''.__('Subscribe to our newsletter').'
    '; - $newsletter_reminder = '

    '.__('Newsletter Reminder').':

    '; - $newsletter_reminder .= html_print_switch( - [ - 'name' => 'newsletter_reminder', - 'value' => $newsletter_reminder_value, - 'disabled' => false, - ] - ); + $newsletter_reminder .= '
    '; } -$newsletter_reminder .= '
    '; - $autorefresh_list_out = []; diff --git a/pandora_console/operation/users/webchat.php b/pandora_console/operation/users/webchat.php index db97864863..de59c5d3e8 100644 --- a/pandora_console/operation/users/webchat.php +++ b/pandora_console/operation/users/webchat.php @@ -79,10 +79,10 @@ $table->class = 'databox filters'; $table->style[0][1] = 'text-align: right; vertical-align: top;'; $table->data[0][0] = '
    '; $table->data[0][1] = '

    '.__('Users Online').'

    '.'
    '; $table->data[1][0] = ''.__('Message').'   '.html_print_input_text( 'message_box', @@ -115,16 +115,16 @@ echo "
    ".html_print_button( //Enter key. if (e.keyCode == 13) { send_message(); + check_users(); } }); init_webchat(); }); - - $(window).unload(function () { + $(window).on("beforeunload",function () { exit_webchat(); }); - + function init_webchat() { send_login_message(); long_polling_check_messages(); diff --git a/pandora_console/operation/visual_console/legacy_public_view.php b/pandora_console/operation/visual_console/legacy_public_view.php index 18d8e2ca55..7bea2a22c9 100644 --- a/pandora_console/operation/visual_console/legacy_public_view.php +++ b/pandora_console/operation/visual_console/legacy_public_view.php @@ -40,6 +40,9 @@ ob_start('ui_process_page_head'); // Enterprise main enterprise_include('index.php'); +$url_css = ui_get_full_url('include/styles/visual_maps.css', false, false, false); +echo ''; + require_once 'include/functions_visual_map.php'; $hash = get_parameter('hash'); @@ -96,31 +99,40 @@ if ($layout) { echo '
    '; } -// Floating menu - Start +// Floating menu - Start. echo '
    '; echo ''; echo '
    '; -// Floating menu - End -// QR code dialog + +// QR code dialog. echo ''; -ui_require_jquery_file('countdown'); -ui_require_javascript_file('wz_jsgraphics'); -ui_require_javascript_file('pandora_visual_console'); +ui_require_jquery_file('countdown', 'include/javascript/', true); +ui_require_javascript_file('wz_jsgraphics', 'include/javascript/', true); +ui_require_javascript_file('pandora_visual_console', 'include/javascript/', true); $ignored_params['refr'] = ''; ?> diff --git a/pandora_console/operation/visual_console/legacy_view.php b/pandora_console/operation/visual_console/legacy_view.php index f5eec24096..62ed4fbd18 100644 --- a/pandora_console/operation/visual_console/legacy_view.php +++ b/pandora_console/operation/visual_console/legacy_view.php @@ -15,6 +15,7 @@ global $config; // Login check require_once $config['homedir'].'/include/functions_visual_map.php'; +ui_require_css_file('visual_maps'); check_login(); diff --git a/pandora_console/operation/visual_console/public_view.php b/pandora_console/operation/visual_console/public_view.php index 90fe29a545..e31d6f9ed5 100644 --- a/pandora_console/operation/visual_console/public_view.php +++ b/pandora_console/operation/visual_console/public_view.php @@ -42,6 +42,9 @@ ob_start('ui_process_page_head'); // Enterprise main. enterprise_include('index.php'); +$url_css = ui_get_full_url('include/styles/visual_maps.css', false, false, false); +echo ''; + require_once 'include/functions_visual_map.php'; $hash = (string) get_parameter('hash'); @@ -83,7 +86,7 @@ echo '
    '; echo '
    '; echo '
    '.''.__('Variable bindings:').' '; if ($group_by) { - $new_url = 'index.php?sec=snmpconsole&sec2=operation/snmpconsole/snmp_view&'.'filter_severity='.$filter_severity.'&'.'filter_fired='.$filter_fired.'&'.'filter_status='.$filter_status.'&'.'refresh='.((int) get_parameter('refresh', 0)).'&'.'pure='.$config['pure'].'&'.'group_by=0&'.'free_search_string='.$free_search_string.'&'.'date_from_trap='.$date_from_trap.'&'.'date_to_trap='.$date_to_trap.'&'.'time_from_trap='.$time_from_trap.'&'.'time_to_trap='.$time_to_trap; + $new_url = 'index.php?sec=snmpconsole&sec2=operation/snmpconsole/snmp_view&filter_severity='.$filter_severity.'&filter_fired='.$filter_fired.'&filter_status='.$filter_status.'&refresh='.((int) get_parameter('refresh', 0)).'&pure='.$config['pure'].'&group_by=0&free_search_string='.$free_search_string.'&date_from_trap='.$date_from_trap.'&date_to_trap='.$date_to_trap.'&time_from_trap='.$time_from_trap.'&time_to_trap='.$time_to_trap; $string .= ''.__('See more details').''; } else { - // Print binding vars separately + // Print binding vars separately. $binding_vars = explode("\t", $trap['oid_custom']); foreach ($binding_vars as $var) { $string .= $var.'
    '; @@ -1007,7 +1042,7 @@ if ($traps !== false) { break; } - $string .= '
    '.''.__('Trap type:').''.''.$desc_trap_type.'
    '.__('Trap type:').''.$desc_trap_type.'