';
-if ($new_user) {
- if ($config['admin_can_add_user']) {
+if ($config['admin_can_add_user']) {
+ html_print_csrf_hidden();
+ if ($new_user) {
html_print_input_hidden ('create_user', 1);
html_print_submit_button (__('Create'), 'crtbutton', false, 'class="sub wand"');
- }
-}
-else {
- if ($config['user_can_update_info']) {
+ } else {
html_print_input_hidden ('update_user', 1);
html_print_submit_button (__('Update'), 'uptbutton', false, 'class="sub upd"');
}
@@ -730,8 +724,7 @@ echo '
';
/* Don't show anything else if we're creating an user */
if (!empty ($id) && !$new_user) {
- profile_print_profile_table($id, __('Profiles/Groups assigned to this user'));
- enterprise_hook('profile_print_profile_secondary_table', array($id));
+ profile_print_profile_table($id);
}
diff --git a/pandora_console/images/help/Acl_hierarchy_1.png b/pandora_console/images/help/Acl_hierarchy_1.png
new file mode 100644
index 0000000000..b5e8b5cae2
Binary files /dev/null and b/pandora_console/images/help/Acl_hierarchy_1.png differ
diff --git a/pandora_console/images/help/Acl_hierarchy_2.png b/pandora_console/images/help/Acl_hierarchy_2.png
new file mode 100644
index 0000000000..c3cc33f7b7
Binary files /dev/null and b/pandora_console/images/help/Acl_hierarchy_2.png differ
diff --git a/pandora_console/images/help/Acl_hierarchy_groups.png b/pandora_console/images/help/Acl_hierarchy_groups.png
new file mode 100644
index 0000000000..b7d9b935c8
Binary files /dev/null and b/pandora_console/images/help/Acl_hierarchy_groups.png differ
diff --git a/pandora_console/include/ajax/module.php b/pandora_console/include/ajax/module.php
index 6c7ea543a6..7f59e1f5d3 100755
--- a/pandora_console/include/ajax/module.php
+++ b/pandora_console/include/ajax/module.php
@@ -295,19 +295,8 @@ if ($get_module_detail) {
elseif (($config['command_snapshot'] == '0') && (preg_match ("/[\n]+/i", $row[$attr[0]]))) {
// Its a single-data, multiline data (data snapshot) ?
- // Detect string data with \n and convert to
's
- $datos = $row[$attr[0]];
-
- $datos = preg_replace ('/', '<', $datos);
- $datos = preg_replace ('/>/', '>', $datos);
- $datos = preg_replace ('/\n/i','
',$datos);
- $datos = preg_replace ('/\s/i',' ',$datos);
- $datos_format = "
";
- $datos_format .= $datos;
- $datos_format .= "
";
-
// I dont why, but using index (value) method, data is automatically converted to html entities ¿?
- $data[] = $datos_format;
+ $data[] = html_print_result_div($row[$attr[0]]);
}
elseif ($is_web_content_string) {
//Fixed the goliat sends the strings from web
@@ -315,11 +304,9 @@ if ($get_module_detail) {
$data[] = io_safe_input($row[$attr[0]]);
}
else {
- // Just a string of alphanumerical data... just do print
//Fixed the data from Selenium Plugin
if ($row[$attr[0]] != strip_tags($row[$attr[0]])) {
-
- $data[] = io_safe_input($row[$attr[0]]);
+ $data[] = html_print_result_div($row[$attr[0]]);
}
else if (is_numeric($row[$attr[0]]) && !modules_is_string_type($row['module_type']) ) {
switch($row['module_type']) {
@@ -334,7 +321,6 @@ if ($get_module_detail) {
}else{
$data[] = remove_right_zeros(number_format($row[$attr[0]], $config['graph_precision']));
}
-
break;
default:
$data_macro = modules_get_unit_macro($row[$attr[0]],$unit);
@@ -355,7 +341,7 @@ if ($get_module_detail) {
if($data_macro){
$data[] = $data_macro;
} else {
- $data[] = $row[$attr[0]];
+ $data[] = html_print_result_div($row[$attr[0]]);
}
}
}
diff --git a/pandora_console/include/ajax/tree.ajax.php b/pandora_console/include/ajax/tree.ajax.php
index 6e7a612171..07435d9109 100644
--- a/pandora_console/include/ajax/tree.ajax.php
+++ b/pandora_console/include/ajax/tree.ajax.php
@@ -38,7 +38,14 @@ if (is_ajax ()) {
}
require_once($config['homedir'] . "/include/class/Tree.class.php");
- enterprise_include_once("include/class/Tree.class.php");
+ require_once($config['homedir'] . "/include/class/TreeOS.class.php");
+ require_once($config['homedir'] . "/include/class/TreeModuleGroup.class.php");
+ require_once($config['homedir'] . "/include/class/TreeModule.class.php");
+ require_once($config['homedir'] . "/include/class/TreeTag.class.php");
+ require_once($config['homedir'] . "/include/class/TreeGroup.class.php");
+ require_once($config['homedir'] . "/include/class/TreeGroupEdition.class.php");
+ enterprise_include_once("include/class/TreePolicies.class.php");
+ enterprise_include_once("include/class/TreeGroupMeta.class.php");
require_once($config['homedir'] . "/include/functions_reporting.php");
require_once($config['homedir'] . "/include/functions_os.php");
@@ -67,17 +74,45 @@ if (is_ajax ()) {
'tagID' => 0,
);
$filter = get_parameter('filter', $default_filters);
-
+
$agent_a = check_acl ($config['id_user'], 0, "AR");
$agent_w = check_acl ($config['id_user'], 0, "AW");
$access = ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR');
- if (class_exists('TreeEnterprise')) {
- $tree = new TreeEnterprise($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ $switch_type = !empty($rootType) ? $rootType : $type;
+ switch ($switch_type) {
+ case 'os':
+ $tree = new TreeOS($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ case 'module_group':
+ $tree = new TreeModuleGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ case 'module':
+ $tree = new TreeModule($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ case 'tag':
+ $tree = new TreeTag($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ case 'group':
+ if(is_metaconsole()){
+ if (!class_exists('TreeGroupMeta')) break;
+ $tree = new TreeGroupMeta($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ }
+ else{
+ $tree = new TreeGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ }
+ break;
+ case 'policies':
+ if (!class_exists('TreePolicies')) break;
+ $tree = new TreePolicies($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ case 'group_edition':
+ $tree = new TreeGroupEdition($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
+ break;
+ default:
+ // FIXME. No error handler
+ return;
}
- else {
- $tree = new Tree($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access);
- }
-
+
$tree->setFilter($filter);
ob_clean();
echo json_encode(array('success' => 1, 'tree' => $tree->getArray()));
diff --git a/pandora_console/include/ajax/visual_console_builder.ajax.php b/pandora_console/include/ajax/visual_console_builder.ajax.php
index fab370763d..98be4f174b 100755
--- a/pandora_console/include/ajax/visual_console_builder.ajax.php
+++ b/pandora_console/include/ajax/visual_console_builder.ajax.php
@@ -100,7 +100,22 @@ $width = get_parameter('width', null);
$height = get_parameter('height', null);
$parent = get_parameter('parent', null);
$map_linked = get_parameter('map_linked', null);
+$linked_map_node_id = get_parameter('linked_map_node_id', null);
+$linked_map_status_calculation_type = get_parameter('linked_map_status_calculation_type', null);
+
$map_linked_weight = get_parameter('map_linked_weight', null);
+if ($map_linked_weight !== null) {
+ $map_linked_weight = (int) $map_linked_weight;
+}
+$linked_map_status_service_critical = get_parameter('linked_map_status_service_critical', null);
+if ($linked_map_status_service_critical !== null) {
+ $linked_map_status_service_critical = (float) $linked_map_status_service_critical;
+}
+$linked_map_status_service_warning = get_parameter('linked_map_status_service_warning', null);
+if ($linked_map_status_service_warning !== null) {
+ $linked_map_status_service_warning = (float) $linked_map_status_service_warning;
+}
+
$element_group = get_parameter('element_group', null);
$width_percentile = get_parameter('width_percentile', 0);
$bars_graph_height = get_parameter('bars_graph_height', null);
@@ -408,7 +423,7 @@ switch ($action) {
// Linked to other layout ?? - Only if not module defined
if ($layoutData['id_layout_linked'] != 0) {
- $status = visual_map_get_layout_status ($layoutData['id_layout_linked'], $layoutData['id_layout_linked_weight']);
+ $status = visual_map_get_layout_status($layoutData['id_layout_linked'], $layoutData);
// Single object
}
@@ -599,6 +614,10 @@ switch ($action) {
if ($id_agent !== null) {
$values['id_agent'] = $id_agent;
}
+
+ if ($linked_map_node_id !== null) {
+ $values['linked_layout_node_id'] = (int) $linked_map_node_id;
+ }
}
else if ($id_agent == 0) {
$values['id_agent'] = 0;
@@ -619,12 +638,27 @@ switch ($action) {
if ($map_linked !== null) {
$values['id_layout_linked'] = $map_linked;
}
- if ($element_group !== null) {
- $values['element_group'] = $element_group;
+ if ($linked_map_status_calculation_type !== null) {
+ $values['linked_layout_status_type'] = $linked_map_status_calculation_type;
}
if ($map_linked_weight !== null) {
+ if ($map_linked_weight > 100) $map_linked_weight = 100;
+ if ($map_linked_weight < 0) $map_linked_weight = 0;
$values['id_layout_linked_weight'] = $map_linked_weight;
}
+ if ($linked_map_status_service_critical !== null) {
+ if ($linked_map_status_service_critical > 100) $linked_map_status_service_critical = 100;
+ if ($linked_map_status_service_critical < 0) $linked_map_status_service_critical = 0;
+ $values['linked_layout_status_as_service_critical'] = $linked_map_status_service_critical;
+ }
+ if ($linked_map_status_service_warning !== null) {
+ if ($linked_map_status_service_warning > 100) $linked_map_status_service_warning = 100;
+ if ($linked_map_status_service_warning < 0) $linked_map_status_service_warning = 0;
+ $values['linked_layout_status_as_service_warning'] = $linked_map_status_service_warning;
+ }
+ if ($element_group !== null) {
+ $values['element_group'] = $element_group;
+ }
switch ($type) {
// -- line_item ------------------------------------
case 'handler_start':
@@ -944,6 +978,16 @@ switch ($action) {
if ($elementFields['id_metaconsole'] != 0) {
metaconsole_restore_db();
}
+
+ if (isset($elementFields["id_layout_linked_weight"])) {
+ $elementFields["id_layout_linked_weight"] = (int) $elementFields["id_layout_linked_weight"];
+ }
+ if (isset($elementFields["linked_layout_status_as_service_critical"])) {
+ $elementFields["linked_layout_status_as_service_critical"] = (float) $elementFields["linked_layout_status_as_service_critical"];
+ }
+ if (isset($elementFields["linked_layout_status_as_service_warning"])) {
+ $elementFields["linked_layout_status_as_service_warning"] = (float) $elementFields["linked_layout_status_as_service_warning"];
+ }
switch ($type) {
case 'auto_sla_graph':
@@ -1096,8 +1140,32 @@ switch ($action) {
}
$values['id_agente_modulo'] = $id_module;
$values['id_layout_linked'] = $map_linked;
+
+ if (defined('METACONSOLE') && $metaconsole) {
+ $values['linked_layout_node_id'] = (int) $linked_map_node_id;
+ }
+
+ $values['linked_layout_status_type'] = $linked_map_status_calculation_type;
+
+ if ($map_linked_weight !== null) {
+ if ($map_linked_weight > 100) $map_linked_weight = 100;
+ if ($map_linked_weight < 0) $map_linked_weight = 0;
+ $values['id_layout_linked_weight'] = $map_linked_weight;
+ }
+
+ if ($linked_map_status_service_critical !== null) {
+ if ($linked_map_status_service_critical > 100) $linked_map_status_service_critical = 100;
+ if ($linked_map_status_service_critical < 0) $linked_map_status_service_critical = 0;
+ $values['linked_layout_status_as_service_critical'] = $linked_map_status_service_critical;
+ }
+
+ if ($linked_map_status_service_warning !== null) {
+ if ($linked_map_status_service_warning > 100) $linked_map_status_service_warning = 100;
+ if ($linked_map_status_service_warning < 0) $linked_map_status_service_warning = 0;
+ $values['linked_layout_status_as_service_warning'] = $linked_map_status_service_warning;
+ }
+
$values['element_group'] = $element_group;
- $values['id_layout_linked_weight'] = $map_linked_weight;
$values['parent_item'] = $parent;
$values['enable_link'] = $enable_link;
$values['show_on_top'] = $show_on_top;
@@ -1361,7 +1429,6 @@ if ($get_element_status) {
array('id' => $id_element));
$res = visual_map_get_status_element($layoutData);
-
echo $res;
return;
diff --git a/pandora_console/include/api.php b/pandora_console/include/api.php
index 5884aa34dd..de84850890 100644
--- a/pandora_console/include/api.php
+++ b/pandora_console/include/api.php
@@ -54,6 +54,7 @@ $no_login_msg = "";
// Clean unwanted output
ob_clean();
+// READ THIS:
// Special call without checks to retrieve version and build of the Pandora FMS
// This info is avalable from the web console without login
// Don't change the format, it is parsed by applications
@@ -63,7 +64,7 @@ switch($info) {
$config["MR"] = 0;
}
- echo get_product_name() . ' ' . $pandora_version . ' - ' . $build_version . " MR" . $config["MR"];
+ echo 'Pandora FMS ' . $pandora_version . ' - ' . $build_version . " MR" . $config["MR"];
exit;
}
diff --git a/pandora_console/include/auth/mysql.php b/pandora_console/include/auth/mysql.php
index f2aff5ed44..835a709ba8 100644
--- a/pandora_console/include/auth/mysql.php
+++ b/pandora_console/include/auth/mysql.php
@@ -349,15 +349,15 @@ function process_user_login_remote ($login, $pass, $api = false) {
foreach ($attributes as $attr) {
$attr = explode('=', $attr, 2);
- if(preg_match('/' . $attr[1] . '/', $sr[$attr[0]][0])){
- $permissions[$i]["profile"] = $ldap_adv_perm['profile'];
- $permissions[$i]["groups"] = $ldap_adv_perm['group'];
- $permissions[$i]["tags"] = implode(",",$ldap_adv_perm['tags']);
- $i++;
- break;
+ foreach ($sr[$attr[0]] as $s_attr) {
+ if(preg_match('/' . $attr[1] . '/', $s_attr)){
+ $permissions[$i]["profile"] = $ldap_adv_perm['profile'];
+ $permissions[$i]["groups"] = $ldap_adv_perm['group'];
+ $permissions[$i]["tags"] = implode(",",$ldap_adv_perm['tags']);
+ $i++;
+ }
}
}
-
}
} else {
$permissions[0]["profile"] = $config['default_remote_profile'];
diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php
index 996eeaf07f..b72e3ec216 100644
--- a/pandora_console/include/class/Tree.class.php
+++ b/pandora_console/include/class/Tree.class.php
@@ -19,17 +19,31 @@ class Tree {
protected $id = -1;
protected $rootID = -1;
protected $serverID = false;
+ protected $serverName = '';
protected $tree = array();
protected $filter = array();
protected $childrenMethod = "on_demand";
protected $userGroupsACL;
protected $userGroups;
+ protected $userGroupsArray;
- protected $strictACL = false;
protected $acltags = false;
protected $access = false;
+ protected $L1fieldName = '';
+ protected $L1fieldNameSql = '';
+ protected $L1extraFields = array();
+ protected $L1inner = '';
+ protected $L1innerInside = '';
+ protected $L1orderByFinal = '';
+
+ protected $L2condition = '';
+ protected $L2conditionInside = '';
+ protected $L2inner = '';
+
+ const TV_DEFAULT_AGENT_STATUS = -1;
+
public function __construct($type, $rootType = '', $id = -1, $rootID = -1, $serverID = false, $childrenMethod = "on_demand", $access = 'AR') {
$this->type = $type;
@@ -37,12 +51,16 @@ class Tree {
$this->id = $id;
$this->rootID = !empty($rootID) ? $rootID : $id;
$this->serverID = $serverID;
+ if (is_metaconsole()) {
+ $this->serverName = metaconsole_get_server_by_id($serverID);
+ }
$this->childrenMethod = $childrenMethod;
$this->access = $access;
$userGroupsACL = users_get_groups(false, $this->access);
$this->userGroupsACL = empty($userGroupsACL) ? false : $userGroupsACL;
$this->userGroups = $this->userGroupsACL;
+ $this->userGroupsArray = array_keys($this->userGroups);
global $config;
include_once($config['homedir']."/include/functions_servers.php");
@@ -52,21 +70,46 @@ class Tree {
if (is_metaconsole()) enterprise_include_once("meta/include/functions_ui_meta.php");
- $this->strictACL = (bool) db_get_value("strict_acl", "tusuario", "id_user", $config['id_user']);
-
$this->acltags = tags_get_user_groups_and_tags($config['id_user'], $this->access);
}
public function setFilter($filter) {
+ // There is not module filter in metaconsole.
+ if (is_metaconsole()) {
+ $filter['searchModule'] = "";
+ $filter['statusModule'] = self::TV_DEFAULT_AGENT_STATUS;
+ }
$this->filter = $filter;
}
- protected function getAgentStatusFilter ($status = -1) {
- if ($status == -1)
+ protected function getEmptyModuleFilterStatus() {
+ return (
+ !isset($this->filter['statusModule']) ||
+ $this->filter['statusModule'] == -1
+ );
+ }
+
+ protected function getModuleSearchFilter() {
+ if (empty($this->filter['searchModule'])) {
+ return "";
+ }
+ return " AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' ";
+ }
+
+ protected function getAgentSearchFilter() {
+ if (empty($this->filter['searchAgent'])) return "";
+ return " AND LOWER(ta.alias) LIKE LOWER('%%".$this->filter['searchAgent']."%%')";
+ }
+
+
+ protected function getAgentStatusFilter ($status = self::TV_DEFAULT_AGENT_STATUS) {
+ if ($status == self::TV_DEFAULT_AGENT_STATUS)
$status = $this->filter['statusAgent'];
$agent_status_filter = "";
switch ($status) {
+ case AGENT_STATUS_ALL:
+ break;
case AGENT_STATUS_NOT_INIT:
$agent_status_filter = " AND (ta.total_count = 0
OR ta.total_count = ta.notinit_count) ";
@@ -94,1298 +137,149 @@ class Tree {
return $agent_status_filter;
}
- protected function getAgentCounterColumnsSql ($agent_table) {
- // Add the agent counters to the columns
-
- if ($this->filter['statusAgent'] == -1) {
- // Critical
- $agent_critical_filter = $this->getAgentStatusFilter(AGENT_STATUS_CRITICAL);
- $agents_critical_count = "($agent_table
- $agent_critical_filter) AS total_critical_count";
- // Warning
- $agent_warning_filter = $this->getAgentStatusFilter(AGENT_STATUS_WARNING);
- $agents_warning_count = "($agent_table
- $agent_warning_filter) AS total_warning_count";
- // Unknown
- $agent_unknown_filter = $this->getAgentStatusFilter(AGENT_STATUS_UNKNOWN);
- $agents_unknown_count = "($agent_table
- $agent_unknown_filter) AS total_unknown_count";
- // Normal
- $agent_normal_filter = $this->getAgentStatusFilter(AGENT_STATUS_NORMAL);
- $agents_normal_count = "($agent_table
- $agent_normal_filter) AS total_normal_count";
- // Not init
-
- if($this->filter['show_not_init_agents']){
- $agent_not_init_filter = $this->getAgentStatusFilter(AGENT_STATUS_NOT_INIT);
- $agents_not_init_count = "($agent_table
- $agent_not_init_filter) AS total_not_init_count";
- }
- else{
- $agent_not_init_filter = 0;
- $agents_not_init_count = 0;
- }
-
- // Alerts fired
- $agents_fired_count = "($agent_table
- AND ta.fired_count > 0) AS total_fired_count";
- // Total
- $agents_total_count = "($agent_table) AS total_count";
-
- $columns = "$agents_critical_count, $agents_warning_count, "
- . "$agents_unknown_count, $agents_normal_count, $agents_not_init_count, "
- . "$agents_fired_count, $agents_total_count";
- }
- else {
- // Alerts fired
- $agents_fired_count = "($agent_table
- AND ta.fired_count > 0) AS total_fired_count";
- // Total
- $agents_total_count = "($agent_table) AS total_count";
-
- switch ($this->filter['statusAgent']) {
- case AGENT_STATUS_NOT_INIT:
- // Not init
- $agent_not_init_filter = $this->getAgentStatusFilter(AGENT_STATUS_NOT_INIT);
- $agents_not_init_count = "($agent_table
- $agent_not_init_filter) AS total_not_init_count";
- $columns = "$agents_not_init_count, $agents_fired_count, $agents_total_count";
- break;
- case AGENT_STATUS_CRITICAL:
- // Critical
- $agent_critical_filter = $this->getAgentStatusFilter(AGENT_STATUS_CRITICAL);
- $agents_critical_count = "($agent_table
- $agent_critical_filter) AS total_critical_count";
- $columns = "$agents_critical_count, $agents_fired_count, $agents_total_count";
- break;
- case AGENT_STATUS_WARNING:
- // Warning
- $agent_warning_filter = $this->getAgentStatusFilter(AGENT_STATUS_WARNING);
- $agents_warning_count = "($agent_table
- $agent_warning_filter) AS total_warning_count";
- $columns = "$agents_warning_count, $agents_fired_count, $agents_total_count";
- break;
- case AGENT_STATUS_UNKNOWN:
- // Unknown
- $agent_unknown_filter = $this->getAgentStatusFilter(AGENT_STATUS_UNKNOWN);
- $agents_unknown_count = "($agent_table
- $agent_unknown_filter) AS total_unknown_count";
- $columns = "$agents_unknown_count, $agents_fired_count, $agents_total_count";
- break;
- case AGENT_STATUS_NORMAL:
- // Normal
- $agent_normal_filter = $this->getAgentStatusFilter(AGENT_STATUS_NORMAL);
- $agents_normal_count = "($agent_table
- $agent_normal_filter) AS total_normal_count";
- $columns = "$agents_normal_count, $agents_fired_count, $agents_total_count";
- break;
- }
- }
-
- return $columns;
+ protected function getFirstLevelFields() {
+ $fields = array (
+ "g AS " . $this->L1fieldName,
+ "SUM(x_critical) AS total_critical_count",
+ "SUM(x_warning) AS total_warning_count",
+ "SUM(x_normal) AS total_normal_count",
+ "SUM(x_unknown) AS total_unknown_count",
+ "SUM(x_not_init) AS total_not_init_count",
+ "SUM(x_alerts) AS total_alerts_count",
+ "SUM(x_total) AS total_count"
+ );
+ return implode(",", array_merge($fields, $this->L1extraFields));
}
- protected function getAgentCountersSql ($agent_table) {
- global $config;
-
- $columns = $this->getAgentCounterColumnsSql($agent_table);
-
- switch ($config["dbtype"]) {
- case "mysql":
- case "postgresql":
- $columns = "SELECT $columns FROM dual LIMIT 1";
- break;
- case "oracle":
- $columns = "SELECT $columns FROM dual WHERE rownum <= 1";
- break;
- }
-
- return $columns;
+ protected function getFirstLevelFieldsInside() {
+ return array(
+ 'warning' => array(
+ 'header' => "0 AS x_critical, SUM(total) AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_WARNING, $this->filter['show_not_init_agents'])
+ ),
+ 'critical' => array(
+ 'header' => "SUM(total) AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_CRITICAL, $this->filter['show_not_init_agents'])
+ ),
+ 'normal' => array(
+ 'header' => "0 AS x_critical, 0 AS x_warning, SUM(total) AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NORMAL, $this->filter['show_not_init_agents'])
+ ),
+ 'unknown' => array(
+ 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, SUM(total) AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_UNKNOWN, $this->filter['show_not_init_agents'])
+ ),
+ 'not_init' => array(
+ 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, SUM(total) AS x_not_init, 0 AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NOT_INIT, $this->filter['show_not_init_agents'])
+ ),
+ 'alerts' => array(
+ 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, SUM(total) AS x_alerts, 0 AS x_total, g",
+ 'condition' => "AND ta.fired_count > 0"
+ ),
+ 'total' => array(
+ 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, SUM(total) AS x_total, g",
+ 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_ALL, $this->filter['show_not_init_agents'])
+ )
+ );
}
- protected function getSql ($item_for_count = false) {
- // Get the type
- if (empty($this->type))
- $type = 'none';
- else
- $type = $this->type;
-
- // Get the root type
- if (empty($this->rootType))
- $rootType = 'none';
- else
- $rootType = $this->rootType;
-
- // Get the parent
- $parent = $this->id;
-
- // Get the root id
- $rootID = $this->rootID;
-
- // Get the server id
- $serverID = $this->serverID;
-
- // Agent name filter
- $agent_search_filter = "";
- if (!empty($this->filter['searchAgent'])) {
- $agent_search_filter = " AND LOWER(ta.alias) LIKE LOWER('%".$this->filter['searchAgent']."%')";
- }
-
- //Search hirearchy
- $search_hirearchy = false;
- if($this->filter['searchHirearchy']){
- $search_hirearchy = true;
- }
-
- // Agent status filter
- $agent_status_filter = "";
- if (isset($this->filter['statusAgent'])
- && $this->filter['statusAgent'] != AGENT_STATUS_ALL
- && !$this->strictACL) {
- $agent_status_filter = $this->getAgentStatusFilter($this->filter['statusAgent']);
- }
-
- // Agents join
- $agents_join = "";
- if (!empty($agent_search_filter) || !empty($agent_status_filter)) {
- $agents_join = "INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $agent_search_filter
- $agent_status_filter";
- }
-
- // Module name filter
- $module_search_filter = "";
- if (!empty($this->filter['searchModule'])) {
- $module_search_filter = " AND tam.nombre LIKE '%".$this->filter['searchModule']."%' ";
- }
-
- // Module status filter
- $module_status_filter = "";
- if (isset($this->filter['statusModule'])
- && $this->filter['statusModule'] != -1) {
-
- switch ($this->filter['statusModule']) {
- case AGENT_MODULE_STATUS_CRITICAL_ALERT:
- case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $module_status_filter = " AND (tae.estado = ".AGENT_MODULE_STATUS_CRITICAL_ALERT."
- OR tae.estado = ".AGENT_MODULE_STATUS_CRITICAL_BAD.") ";
- break;
- case AGENT_MODULE_STATUS_WARNING_ALERT:
- case AGENT_MODULE_STATUS_WARNING:
- $module_status_filter = " AND (tae.estado = ".AGENT_MODULE_STATUS_WARNING_ALERT."
- OR tae.estado = ".AGENT_MODULE_STATUS_WARNING.") ";
- break;
- case AGENT_MODULE_STATUS_UNKNOWN:
- $module_status_filter = " AND tae.estado = ".AGENT_MODULE_STATUS_UNKNOWN." ";
- break;
- case AGENT_MODULE_STATUS_NO_DATA:
- case AGENT_MODULE_STATUS_NOT_INIT:
- $module_status_filter = " AND (tae.estado = ".AGENT_MODULE_STATUS_NO_DATA."
- OR tae.estado = ".AGENT_MODULE_STATUS_NOT_INIT.") ";
- break;
- case AGENT_MODULE_STATUS_NORMAL_ALERT:
- case AGENT_MODULE_STATUS_NORMAL:
- $module_status_filter = " AND (tae.estado = ".AGENT_MODULE_STATUS_NORMAL_ALERT."
- OR tae.estado = ".AGENT_MODULE_STATUS_NORMAL.") ";
- break;
- }
- }
-
- // Modules join
- $modules_join = "";
- $module_status_join = "";
- if (!empty($module_search_filter) || !empty($module_status_filter) || !$this->filter['show_not_init_agents']) {
-
- if (!empty($module_status_filter) || !$this->filter['show_not_init_agents']) {
- $module_status_join = "INNER JOIN tagente_estado tae
- ON tam.id_agente_modulo IS NOT NULL
- AND tam.id_agente_modulo = tae.id_agente_modulo
- $module_status_filter";
-
- if(!$this->filter['show_not_init_modules'] || ($this->filter['show_not_init_modules'] && !$this->filter['show_not_init_agents'])){
- if($type != 'agent' || ($type == 'agent' && !$this->filter['show_not_init_modules'] && !$this->filter['show_not_init_agents'])){
- $module_status_join .= ' AND tae.estado <> '.AGENT_MODULE_STATUS_NO_DATA.' AND tae.estado <> '.AGENT_MODULE_STATUS_NOT_INIT.' ';
- }
- }
- }
-
- $modules_join = "INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- $module_search_filter
- $module_status_join";
- }
-
- if (empty($module_status_join)) {
- if(!$this->filter['show_not_init_modules'] || !$this->filter['show_not_init_agents']){
- if($type == "agent"){
- $module_status_join = 'INNER JOIN tagente_estado tae
- ON tam.id_agente_modulo = tae.id_agente_modulo ';
- }
- else{
- $module_status_join = 'LEFT JOIN tagente_estado tae
- ON tam.id_agente_modulo = tae.id_agente_modulo ';
- }
-
- $module_status_join .= ' AND 1=1 AND tae.estado <> '.AGENT_MODULE_STATUS_NO_DATA.' AND tae.estado <> '.AGENT_MODULE_STATUS_NOT_INIT.' ';
- }
- else{
- $module_status_join = 'LEFT JOIN tagente_estado tae
- ON tam.id_agente_modulo = tae.id_agente_modulo ';
- }
- }
-
- $sql = false;
-
- switch ($rootType) {
- case 'group':
- // ACL Group
- $user_groups_str = "-1";
- $group_filter = "";
-
- if (empty($this->userGroups)) {
- return;
- }
-
- // Asking for a specific group.
- if ($item_for_count !== false) {
- if (!isset($this->userGroups[$item_for_count])) {
- return;
- }
- }
- // Asking for all groups.
- else {
- $user_groups_str = implode(",", array_keys($this->userGroups));
- $group_filter = "AND (
- ta.id_grupo IN ($user_groups_str)
- OR tasg.id_group IN ($user_groups_str)
- )";
- }
-
- if(!$search_hirearchy && (!empty($agent_search_filter) || !empty($module_search_filter))){
-
- if(is_metaconsole()){
- $id_groups_agents = db_get_all_rows_sql(
- " SELECT DISTINCT(ta.id_grupo)
- FROM tmetaconsole_agent ta
- LEFT JOIN tmetaconsole_agent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- WHERE ta.disabled = 0
- $agent_search_filter"
- );
- $id_secondary_groups_agents = db_get_all_rows_sql(
- " SELECT DISTINCT(tasg.id_group)
- FROM tmetaconsole_agent ta
- LEFT JOIN tmetaconsole_agent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- WHERE ta.disabled = 0
- $agent_search_filter"
- );
- }
- else{
- $id_groups_agents = db_get_all_rows_sql(
- " SELECT DISTINCT(ta.id_grupo)
- FROM tagente ta
- LEFT JOIN tagent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- , tagente_modulo tam
- WHERE tam.id_agente = ta.id_agente
- AND ta.disabled = 0
- $agent_search_filter
- $module_search_filter"
- );
- $id_secondary_groups_agents = db_get_all_rows_sql(
- " SELECT DISTINCT(tasg.id_group)
- FROM tagente ta
- LEFT JOIN tagent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- , tagente_modulo tam
- WHERE tam.id_agente = ta.id_agente
- AND ta.disabled = 0
- $agent_search_filter
- $module_search_filter"
- );
- }
-
- if($id_groups_agents != false){
- foreach ($id_groups_agents as $key => $value) {
- $id_groups_agents_array[$value['id_grupo']] = $value['id_grupo'];
- }
- foreach ($id_secondary_groups_agents as $key => $value) {
- $id_groups_agents_array[$value['id_group']] = $value['id_group'];
- }
- $user_groups_array = explode(",", $user_groups_str);
- $user_groups_array = array_intersect($user_groups_array, $id_groups_agents_array);
- $user_groups_str = implode("," , $user_groups_array);
- }
- else{
- $user_groups_str = false;
- }
- }
-
- switch ($type) {
- // Get the agents of a group
- case 'group':
- if (empty($rootID) || $rootID == -1) {
- if(!$search_hirearchy && (!empty($agent_search_filter) || !empty($module_search_filter))){
- $columns = 'tg.id_grupo AS id, tg.nombre AS name, tg.icon';
- }
- else{
- $columns = 'tg.id_grupo AS id, tg.nombre AS name, tg.parent, tg.icon';
- }
-
- $order_fields = 'tg.nombre ASC, tg.id_grupo ASC';
-
- if (! is_metaconsole()) {
- // Groups SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM tgrupo tg
- WHERE tg.id_grupo IN ($user_groups_str)
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tagente ta
- LEFT JOIN tagent_secondary_group tasg
- ON ta.id_agente=tasg.id_agent
- LEFT JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- AND (
- ta.id_grupo = $item_for_count
- OR tasg.id_group = $item_for_count
- )
- $group_filter
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- // Metaconsole
- else {
- // Groups SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM tgrupo tg
- WHERE tg.id_grupo IN ($user_groups_str)
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tmetaconsole_agent ta
- LEFT JOIN tmetaconsole_agent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- WHERE ta.disabled = 0
- AND (
- ta.id_grupo = $item_for_count
- OR tasg.id_group = $item_for_count
- )
- $group_filter
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- }
- else {
- if (! is_metaconsole()) {
- $columns = 'ta.id_agente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $group_by_fields = 'ta.id_agente, ta.nombre, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $order_fields = 'ta.alias ASC, ta.id_agente ASC';
-
- $sql = "SELECT $columns
- FROM tagente ta
- LEFT JOIN tagent_secondary_group tasg
- ON tasg.id_agent = ta.id_agente
- LEFT JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- AND (
- ta.id_grupo = $rootID
- OR tasg.id_group = $rootID
- )
- $group_filter
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- else {
- $columns = 'ta.id_tagente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet, ta.id_tmetaconsole_setup AS server_id';
- $order_fields = 'ta.alias ASC, ta.id_tagente ASC';
-
- $sql = "SELECT $columns
- FROM tmetaconsole_agent ta
- LEFT JOIN tmetaconsole_agent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- WHERE ta.disabled = 0
- AND (
- ta.id_grupo = $rootID
- OR tasg.id_group = $rootID
- )
- $group_filter
- $agent_search_filter
- $agent_status_filter
- GROUP BY ta.id_agente
- ORDER BY $order_fields";
- }
- }
- break;
- // Get the modules of an agent
- case 'agent':
- $columns = 'tam.id_agente_modulo AS id,
- tam.parent_module_id AS parent,
- tam.nombre AS name, tam.id_tipo_modulo,
- tam.id_modulo, tae.estado, tae.datos';
- $order_fields = 'tam.nombre ASC, tam.id_agente_modulo ASC';
-
- // Set for the common ACL only. The strict ACL case is different (groups and tags divided).
- // The modules only have visibility in two cases:
- // 1. The user has access to the group of its agent and this group hasn't tags.
- // 2. The user has access to the group of its agent, this group has tags and the module
- // has any of this tags.
- $tag_join = '';
- if (!$this->strictACL) {
- // $rootID it the agent group id in this case
- if (!empty($this->acltags) && isset($this->acltags[$rootID])) {
- $tags_str = $this->acltags[$rootID];
-
- if (!empty($tags_str)) {
- $tag_join = sprintf('INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag IN (%s)', $tags_str);
- }
- }
- }
-
- $sql = "SELECT DISTINCT $columns
- FROM tagente_modulo tam
- $tag_join
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- LEFT JOIN tagent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- AND tam.id_agente = ta.id_agente
- AND ta.id_grupo = $rootID
- $group_filter
- $agent_search_filter
- $agent_status_filter
- WHERE tam.disabled = 0
- AND tam.id_agente = $parent
- $module_search_filter
- ORDER BY $order_fields";
- break;
- }
- break;
- case 'tag':
- // ACL Group
- $group_acl = "";
- if (!$this->strictACL) {
- if (!empty($this->userGroups)) {
- $user_groups_str = implode(",", array_keys($this->userGroups));
- $group_acl = " AND ta.id_grupo IN ($user_groups_str) ";
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
- }
- else {
- if (!empty($this->acltags) && !empty($rootID) && $rootID != -1) {
- $groups = array();
- foreach ($this->acltags as $group_id => $tags_str) {
- if (!empty($tags_str)) {
- $tags = explode(",", $tags_str);
-
- if (in_array($rootID, $tags)) {
- $hierarchy_groups = groups_get_id_recursive($group_id);
- $groups = array_merge($groups, $hierarchy_groups);
- }
- }
- }
- if (!empty($groups)) {
- if (array_search(0, $groups) === false) {
- $user_groups_str = implode(",", $groups);
- $group_acl = " AND ta.id_grupo IN ($user_groups_str) ";
- }
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
- }
-
- switch ($type) {
- // Get the agents of a tag
- case 'tag':
- if (empty($rootID) || $rootID == -1) {
- if ($this->strictACL)
- return false;
-
- // tagID filter. To access the view from tactical views f.e.
- $tag_filter = '';
- if (!empty($this->filter['tagID'])) {
- $tag_filter = "WHERE tt.id_tag = " . $this->filter['tagID'];
- }
-
- $columns = 'tt.id_tag AS id, tt.name AS name';
- $group_by_fields = 'tt.id_tag, tt.name';
- $order_fields = 'tt.name ASC, tt.id_tag ASC';
-
- // Tags SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM ttag tt
- INNER JOIN ttag_module ttm
- ON tt.id_tag = ttm.id_tag
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ttm.id_agente_modulo = tam.id_agente_modulo
- $module_search_filter
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- $agent_search_filter
- $agent_status_filter
- $tag_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- $module_search_filter
- $module_status_join
- INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag = $item_for_count
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- else {
- $columns = 'ta.id_agente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $group_by_fields = 'ta.id_agente, ta.nombre, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $order_fields = 'ta.alias ASC, ta.id_agente ASC';
-
- $sql = "SELECT $columns
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- $module_search_filter
- $module_status_join
- INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag = $rootID
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- break;
- // Get the modules of an agent
- case 'agent':
- $columns = 'tam.id_agente_modulo AS id, tam.nombre AS name,
- tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos';
- $order_fields = 'tam.nombre ASC, tam.id_agente_modulo ASC';
-
- // Set for the common ACL only. The strict ACL case is different (groups and tags divided).
- // The modules only have visibility in two cases:
- // 1. The user has access to the group of its agent and this group hasn't tags.
- // 2. The user has access to the group of its agent, this group has tags and the module
- // has any of this tags.
- $tag_filter = '';
- if (!$this->strictACL) {
- // $parent is the agent id
- $group_id = (int) db_get_value('id_grupo', 'tagente', 'id_agente', $parent);
- if (empty($group_id)) {
- // ACL error, this will restrict (fuck) the module search
- $tag_filter = 'AND 1=0';
- }
- else if (!empty($this->acltags) && isset($this->acltags[$group_id])) {
- $tags_str = $this->acltags[$group_id];
-
- if (!empty($tags_str)) {
- $tag_filter = sprintf('AND ttm.id_tag IN (%s)', $tags_str);
- }
- }
- }
-
- $sql = "SELECT $columns
- FROM tagente_modulo tam
- INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag = $rootID
- $tag_filter
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- $agent_search_filter
- $agent_status_filter
- WHERE tam.disabled = 0
- AND tam.id_agente = $parent
- $module_search_filter
- ORDER BY $order_fields";
- break;
- }
- break;
- case 'os':
- // ACL Group
- $group_acl = "";
- if (!empty($this->userGroups)) {
- $user_groups_str = implode(",", array_keys($this->userGroups));
- $group_acl = " AND ta.id_grupo IN ($user_groups_str) ";
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
-
- switch ($type) {
- // Get the agents of an os
- case 'os':
- if (empty($rootID) || $rootID == -1) {
- $columns = 'tos.id_os AS id, tos.name AS name, tos.icon_name AS os_icon';
- $group_by_fields = 'tos.id_os, tos.name, tos.icon_name';
- $order_fields = 'tos.icon_name ASC, tos.id_os ASC';
-
- // OS SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM tconfig_os tos
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND ta.id_os = tos.id_os
- $agent_search_filter
- $agent_status_filter
- $group_acl
- $modules_join
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tagente ta
- $modules_join
- WHERE ta.disabled = 0
- AND ta.id_os = $item_for_count
- $group_acl
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- else {
- $columns = 'ta.id_agente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $group_by_fields = 'ta.id_agente, ta.nombre, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $order_fields = 'ta.alias ASC, ta.id_agente ASC';
-
- $sql = "SELECT $columns
- FROM tagente ta
- $modules_join
- WHERE ta.disabled = 0
- AND ta.id_os = $rootID
- $group_acl
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- break;
- // Get the modules of an agent
- case 'agent':
- $columns = 'tam.id_agente_modulo AS id, tam.nombre AS name,
- tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos';
- $order_fields = 'tam.nombre ASC, tam.id_agente_modulo ASC';
-
- $os_filter = "AND ta.id_os = $rootID";
- $agent_filter = "AND ta.id_agente = $parent";
-
- // Set for the common ACL only. The strict ACL case is different (groups and tags divided).
- // The modules only have visibility in two cases:
- // 1. The user has access to the group of its agent and this group hasn't tags.
- // 2. The user has access to the group of its agent, this group has tags and the module
- // has any of this tags.
- $tag_join = '';
- if (!$this->strictACL) {
- // $parent is the agent id
- $group_id = (int) db_get_value('id_grupo', 'tagente', 'id_agente', $parent);
- if (empty($group_id)) {
- // ACL error, this will restrict (fuck) the module search
- $tag_join = 'INNER JOIN ttag_module tta
- ON 1=0';
- }
- else if (!empty($this->acltags) && isset($this->acltags[$group_id])) {
- $tags_str = $this->acltags[$group_id];
-
- if (!empty($tags_str)) {
- $tag_join = sprintf('INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag IN (%s)', $tags_str);
- }
- }
- }
-
- $sql = "SELECT $columns
- FROM tagente_modulo tam
- $tag_join
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $os_filter
- $group_acl
- $agent_search_filter
- $agent_status_filter
- WHERE tam.disabled = 0
- $agent_filter
- $module_search_filter
- ORDER BY $order_fields";
- break;
- }
- break;
- case 'module_group':
- // ACL Group
- $group_acl = "";
- if (!empty($this->userGroups)) {
- $user_groups_str = implode(",", array_keys($this->userGroups));
- $group_acl = " AND ta.id_grupo IN ($user_groups_str) ";
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
-
- switch ($type) {
- // Get the agents of a module group
- case 'module_group':
- if (empty($rootID) || $rootID == -1) {
- $columns = 'tmg.id_mg AS id, tmg.name AS name';
- $group_by_fields = 'tmg.id_mg, tmg.name';
- $order_fields = 'tmg.name ASC, tmg.id_mg ASC';
-
- // Module groups SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM tmodule_group tmg
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND tam.id_module_group = tmg.id_mg
- $module_search_filter
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- AND tam.id_module_group = $item_for_count
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- else {
- $columns = 'ta.id_agente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $group_by_fields = 'ta.id_agente, ta.nombre, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $order_fields = 'ta.alias ASC, ta.id_agente ASC';
-
- $sql = "SELECT $columns
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- AND tam.id_module_group = $rootID
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- break;
- // Get the modules of an agent
- case 'agent':
- $columns = 'tam.id_agente_modulo AS id, tam.nombre AS name,
- tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos';
- $order_fields = 'tam.nombre ASC, tam.id_agente_modulo ASC';
-
- $module_group_filter = "AND tam.id_module_group = $rootID";
- $agent_filter = "AND tam.id_agente = $parent";
-
- // Set for the common ACL only. The strict ACL case is different (groups and tags divided).
- // The modules only have visibility in two cases:
- // 1. The user has access to the group of its agent and this group hasn't tags.
- // 2. The user has access to the group of its agent, this group has tags and the module
- // has any of this tags.
- $tag_join = '';
- if (!$this->strictACL) {
- // $parent is the agent id
- $group_id = (int) db_get_value('id_grupo', 'tagente', 'id_agente', $parent);
- if (empty($group_id)) {
- // ACL error, this will restrict (fuck) the module search
- $tag_join = 'INNER JOIN ttag_module tta
- ON 1=0';
- }
- else if (!empty($this->acltags) && isset($this->acltags[$group_id])) {
- $tags_str = $this->acltags[$group_id];
-
- if (!empty($tags_str)) {
- $tag_join = sprintf('INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag IN (%s)', $tags_str);
- }
- }
- }
-
- $sql = "SELECT $columns
- FROM tagente_modulo tam
- $tag_join
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- $agent_search_filter
- $agent_status_filter
- WHERE tam.disabled = 0
- $agent_filter
- $module_group_filter
- $module_search_filter
- ORDER BY $order_fields";
- break;
- }
- break;
- case 'module':
- // ACL Group
- $group_acl = "";
- if (!empty($this->userGroups)) {
- $user_groups_str = implode(",", array_keys($this->userGroups));
- $group_acl = " AND ta.id_grupo IN ($user_groups_str) ";
- }
- else {
- $group_acl = "AND ta.id_grupo = -1";
- }
-
- switch ($type) {
- // Get the agents of a module
- case 'module':
- if (empty($rootID) || $rootID == -1) {
- $columns = 'tam.nombre AS name';
- $order_fields = 'tam.nombre ASC';
-
- // Modules SQL
- if ($item_for_count === false) {
- $sql = "SELECT $columns
- FROM tagente_modulo tam
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- $agent_search_filter
- $agent_status_filter
- $module_status_join
- WHERE tam.disabled = 0
- $module_search_filter
- GROUP BY tam.nombre
- ORDER BY $order_fields";
- }
- // Counters SQL
- else {
- $agent_table = "SELECT COUNT(DISTINCT(ta.id_agente))
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- AND tam.nombre = '$item_for_count'
- $module_group_filter
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter";
- $sql = $this->getAgentCountersSql($agent_table);
- }
- }
- else {
- $columns = 'ta.id_agente AS id, ta.nombre AS name, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $group_by_fields = 'ta.id_agente, ta.nombre, ta.alias,
- ta.fired_count, ta.normal_count, ta.warning_count,
- ta.critical_count, ta.unknown_count, ta.notinit_count,
- ta.total_count, ta.quiet';
- $order_fields = 'ta.alias ASC, ta.id_agente ASC';
-
- $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~';
- $name = $rootID;
- for ($i = 0; $i < strlen($symbols); $i++) {
- $name = str_replace('_articapandora_' .
- ord(substr($symbols, $i, 1)) .'_pandoraartica_',
- substr($symbols, $i, 1), $name);
- }
- $name = io_safe_input($name);
-
- $sql = "SELECT $columns
- FROM tagente ta
- INNER JOIN tagente_modulo tam
- ON tam.disabled = 0
- AND ta.id_agente = tam.id_agente
- AND tam.nombre = '$name'
- $module_group_filter
- $module_search_filter
- $module_status_join
- WHERE ta.disabled = 0
- $group_acl
- $agent_search_filter
- $agent_status_filter
- GROUP BY $group_by_fields
- ORDER BY $order_fields";
- }
- break;
- // Get the modules of an agent
- case 'agent':
- $columns = 'tam.id_agente_modulo AS id, tam.nombre AS name,
- tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos';
- $order_fields = 'tam.nombre ASC, tam.id_agente_modulo ASC';
-
- $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~';
- $name = $rootID;
- for ($i = 0; $i < strlen($symbols); $i++) {
- $name = str_replace('_articapandora_' .
- ord(substr($symbols, $i, 1)) .'_pandoraartica_',
- substr($symbols, $i, 1), $name);
- }
- $name = io_safe_input($name);
-
- $module_name_filter = "AND tam.nombre = '$name'";
- $agent_filter = "AND tam.id_agente = $parent";
-
- // We need the agents table
- if (empty($agents_join)) {
- $agents_join = "INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl";
- }
- else {
- $agents_join .= " $group_acl";
- }
-
- // Set for the common ACL only. The strict ACL case is different (groups and tags divided).
- // The modules only have visibility in two cases:
- // 1. The user has access to the group of its agent and this group hasn't tags.
- // 2. The user has access to the group of its agent, this group has tags and the module
- // has any of this tags.
- $tag_join = '';
- if (!$this->strictACL) {
- // $parent is the agent id
- $group_id = (int) db_get_value('id_grupo', 'tagente', 'id_agente', $parent);
- if (empty($group_id)) {
- // ACL error, this will restrict (fuck) the module search
- $tag_join = 'INNER JOIN ttag_module tta
- ON 1=0';
- }
- else if (!empty($this->acltags) && isset($this->acltags[$group_id])) {
- $tags_str = $this->acltags[$group_id];
-
- if (!empty($tags_str)) {
- $tag_join = sprintf('INNER JOIN ttag_module ttm
- ON tam.id_agente_modulo = ttm.id_agente_modulo
- AND ttm.id_tag IN (%s)', $tags_str);
- }
- }
- }
-
- $sql = "SELECT $columns
- FROM tagente_modulo tam
- $tag_join
- $module_status_join
- INNER JOIN tagente ta
- ON ta.disabled = 0
- AND tam.id_agente = ta.id_agente
- $group_acl
- WHERE tam.disabled = 0
- $agent_filter
- $module_name_filter
- $module_group_filter
- $module_search_filter
- ORDER BY $order_fields";
- break;
- }
- break;
- default:
- $sql = $this->getSqlExtended($item_for_count, $type, $rootType, $parent, $rootID,
- $agent_search_filter, $agent_status_filter, $agents_join,
- $module_search_filter, $module_status_filter, $modules_join,
- $module_status_join);
- }
-
- return $sql;
+ protected function getInnerOrLeftJoin () {
+ return $this->filter['show_not_init_agents']
+ ? "LEFT"
+ : "INNER";
}
- // Override this method
- protected function getSqlExtended ($item_for_count, $type, $rootType, $parent, $rootID,
- $agent_search_filter, $agent_status_filter, $agents_join,
- $module_search_filter, $module_status_filter, $modules_join,
- $module_status_join) {
- return false;
+ protected function getModuleStatusFilter () {
+ $show_init_condition = ($this->filter['show_not_init_agents'])
+ ? ""
+ : " AND ta.notinit_count <> ta.total_count";
+
+ if ($this->getEmptyModuleFilterStatus()) {
+ return $show_init_condition;
+ }
+
+ $field_filter = modules_get_counter_by_states($this->filter['statusModule']);
+ if ($field_filter === false) return " AND 1=0";
+
+ return "AND ta.$field_filter > 0" . $show_init_condition;
}
- protected function getItems ($item_for_count = false) {
- $sql = $this->getSql($item_for_count);
- if (empty($sql))
- return array();
+ // FIXME: Separate and condition from inner join
+ protected function getTagJoin () {
+ // $parent is the agent id
+ $group_id = (int) db_get_value('id_grupo', 'tagente', 'id_agente', $this->id);
+ $tag_join = '';
+ if (empty($group_id)) {
+ // ACL error, this will restrict the module search
+ $tag_join = 'INNER JOIN ttag_module tta
+ ON 1=0';
+ }
+ else if (!empty($this->acltags) && isset($this->acltags[$group_id])) {
+ $tags_str = $this->acltags[$group_id];
- $data = db_process_sql($sql);
- if (empty($data))
- return array();
-
- foreach ($data[0] as $key => $value) {
-
- if($key != 'total_count' && $key != 'total_fired_count' && strpos($key, 'count')){
- $zero_counter += $value;
+ if (!empty($tags_str)) {
+ $tag_join = sprintf('INNER JOIN ttag_module ttm
+ ON tam.id_agente_modulo = ttm.id_agente_modulo
+ AND ttm.id_tag IN (%s)', $tags_str);
}
-
}
-
- if(!$zero_counter){
- $data[0]['total_count'] = 0;
- }
- else{
- $data[0]['total_count'] = $zero_counter;
- }
-
-
-
- // [26/10/2017] It seems the module hierarchy should be only available into the tree by group
- if ($this->rootType == 'group' && $this->type == 'agent') {
- $data = $this->getProcessedModules($data);
- }
-
- return $data;
+ return $tag_join;
}
- protected function getCounters ($id) {
- $counters = $this->getItems($id);
+ protected function getModuleStatusFilterFromTestado ($state = false, $without_ands = false) {
+ $selected_status = ($state !== false && $state !== self::TV_DEFAULT_AGENT_STATUS)
+ ? $state
+ : $this->filter['statusModule'];
- if (!empty($counters)) {
- $counters = array_pop($counters);
+ $filter = array(
+ modules_get_state_condition($selected_status)
+ );
+ if (!$this->filter['show_not_init_modules'] && $state === false) {
+ if (!empty($filter))
+ $filter[] = "(
+ tae.estado <> ".AGENT_MODULE_STATUS_NO_DATA."
+ AND tae.estado <> ".AGENT_MODULE_STATUS_NOT_INIT."
+ )";
}
- return $counters;
+ $filter = implode(" AND ", $filter);
+ return ($without_ands)
+ ? $filter
+ : " AND $filter ";
+ }
+
+ public function getGroupAclCondition() {
+ if (users_can_manage_group_all("AR")) return "";
+
+ $groups_str= implode(",", $this->userGroupsArray);
+ return " AND (
+ ta.id_grupo IN ($groups_str)
+ OR tasg.id_group IN ($groups_str)
+ )";
+ }
+
+ protected function getGroupSearchInner() {
+ if (empty($this->filter['searchGroup'])) return "";
+ return "INNER JOIN tgrupo tg
+ ON ta.id_grupo = tg.id_grupo
+ OR tasg.id_group = tg.id_grupo"
+ ;
+ }
+
+ protected function getGroupSearchFilter() {
+ if (empty($this->filter['searchGroup'])) return "";
+ return " AND tg.nombre LIKE '%%" . $this->filter['searchGroup'] . "%%'";
}
static function cmpSortNames($a, $b) {
return strcmp($a["name"], $b["name"]);
}
- protected function getProcessedGroups ($items, $remove_empty = false) {
- $processed_groups = array();
- // Index and process the groups
- $groups = array();
- foreach ($items as $item) {
- $groups[$item['id']] = $this->getProcessedItem($item);
- }
-
- // If user have not permissions in parent, set parent node to 0 (all)
- $user_groups_with_privileges = $this->userGroups;
- foreach ($groups as $id => $group) {
- if (!in_array($groups[$id]['parent'], array_keys($user_groups_with_privileges))) {
- $groups[$id]['parent'] = 0;
- }
- }
- // Build the group hierarchy
- foreach ($groups as $id => $group) {
- if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) {
- $parent = $groups[$id]['parent'];
- // Parent exists
- if (!isset($groups[$parent]['children'])) {
- $groups[$parent]['children'] = array();
- }
- // Store a reference to the group into the parent
- $groups[$parent]['children'][] = &$groups[$id];
- // This group was introduced into a parent
- $groups[$id]['have_parent'] = true;
- }
- }
- // Sort the children groups
- foreach ($groups as $id => $group) {
- if (isset($groups[$id]['children'])) {
- usort($groups[$id]['children'], array("Tree", "cmpSortNames"));
- }
- }
- //Filter groups and eliminates the reference to children groups out of her parent
- $groups = array_filter($groups, function ($group) {
- return !$group['have_parent'];
- });
- // Propagate child counters to her parents
- Tree::processCounters($groups);
- // Filter groups and eliminates the reference to empty groups
- if ($remove_empty) {
- $groups = Tree::deleteEmptyGroups($groups);
- }
- usort($groups, array("Tree", "cmpSortNames"));
- return $groups;
- }
-
- protected function getProcessedItem ($item, $server = false, &$items = array(), &$items_tmp = array(), $remove_empty = false) {
+ protected function getProcessedItem ($item, $server = false) {
if (isset($processed_item['is_processed']) && $processed_item['is_processed'])
return $item;
- // For strict items
- if (isset($item['_id_'])) {
- $item['id'] = $item['_id_'];
- $item['name'] = $item['_name_'];
-
- if (isset($item['_is_tag_']) && $item['_is_tag_']) {
- $item['type'] = 'tag';
- $item['rootType'] = 'tag';
- }
- else {
- $item['type'] = 'group';
- $item['rootType'] = 'group';
- $item['parent'] = $item['_parent_id_'];
-
- if (!empty($item['_iconImg_']))
- $item['iconHTML'] = $item['_iconImg_'];
- }
-
- if (isset($item['_agents_unknown_']))
- $item['total_unknown_count'] = $item['_agents_unknown_'];
- if (isset($item['_agents_critical_']))
- $item['total_critical_count'] = $item['_agents_critical_'];
- if (isset($item['_agents_warning_']))
- $item['total_warning_count'] = $item['_agents_warning_'];
- if (isset($item['_agents_not_init_']))
- $item['total_not_init_count'] = $item['_agents_not_init_'];
- if (isset($item['_agents_ok_']))
- $item['total_normal_count'] = $item['_agents_ok_'];
- if (isset($item['_total_agents_']))
- $item['total_count'] = $item['_total_agents_'];
- if (isset($item['_monitors_alerts_fired_']))
- $item['total_fired_count'] = $item['_monitors_alerts_fired_'];
-
- // Agent filter for Strict ACL users
- if ($this->filter["statusAgent"] != -1) {
- switch ($this->filter["statusAgent"]) {
- case AGENT_STATUS_NOT_INIT:
- $item['total_count'] = $item['total_not_init_count'];
-
- $item['total_unknown_count'] = 0;
- $item['total_critical_count'] = 0;
- $item['total_warning_count'] = 0;
- $item['total_normal_count'] = 0;
- break;
- case AGENT_STATUS_CRITICAL:
- $item['total_count'] = $item['total_critical_count'];
-
- $item['total_unknown_count'] = 0;
- $item['total_warning_count'] = 0;
- $item['total_not_init_count'] = 0;
- $item['total_normal_count'] = 0;
- break;
- case AGENT_STATUS_WARNING:
- $item['total_count'] = $item['total_warning_count'];
-
- $item['total_unknown_count'] = 0;
- $item['total_critical_count'] = 0;
- $item['total_not_init_count'] = 0;
- $item['total_normal_count'] = 0;
- break;
- case AGENT_STATUS_UNKNOWN:
- $item['total_count'] = $item['total_unknown_count'];
-
- $item['total_critical_count'] = 0;
- $item['total_warning_count'] = 0;
- $item['total_not_init_count'] = 0;
- $item['total_normal_count'] = 0;
- break;
- case AGENT_STATUS_NORMAL:
- $item['total_count'] = $item['total_normal_count'];
-
- $item['total_unknown_count'] = 0;
- $item['total_critical_count'] = 0;
- $item['total_warning_count'] = 0;
- $item['total_not_init_count'] = 0;
- break;
- }
- }
- }
-
-
$processed_item = array();
$processed_item['id'] = $item['id'];
$processed_item['name'] = $item['name'];
@@ -1406,28 +300,18 @@ class Tree {
if ($processed_item['type'] == 'group') {
$processed_item['parent'] = $item['parent'];
- if (!empty($item['iconHTML']))
- $processed_item['iconHTML'] = $item['iconHTML'];
- else if (!empty($item['icon']))
- $processed_item['icon'] = $item['icon'].".png";
- else
- $processed_item['icon'] = "without_group.png";
+ $processed_item['icon'] = empty($item['icon'])
+ ? "without_group.png"
+ : $item['icon'].".png";
+ }
+ if (isset($item['iconHTML'])) {
+ $processed_item['icon'] = $item['iconHTML'];
}
if (is_metaconsole() && !empty($server)) {
$processed_item['serverID'] = $server['id'];
}
- // Get the counters of the group (special case)
- if ($processed_item['type'] == 'group') {
- $counters = $this->getGroupCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
- }
-
$counters = array();
if (isset($item['total_unknown_count']))
$counters['unknown'] = $item['total_unknown_count'];
@@ -1550,12 +434,12 @@ class Tree {
return $mergedItems;
}
- protected function processModule (&$module, $server = false) {
+ protected function processModule (&$module, $server = false, $all_groups) {
global $config;
if (isset($module['children'])) {
foreach ($module['children'] as $i => $children) {
- $this->processModule($module['children'][$i], $server);
+ $this->processModule($module['children'][$i], $server, $all_groups);
}
}
@@ -1567,9 +451,9 @@ class Tree {
$module['status'] = $module['estado'];
$module['value'] = $module['datos'];
- if (is_metaconsole() && !empty($server)) {
- $module['serverID'] = $server['id'];
- $module['serverName'] = $server['server_name'];
+ if (is_metaconsole()) {
+ $module['serverID'] = $this->serverID;
+ $module['serverName'] = $this->serverName;
}
else {
$module['serverName'] = false;
@@ -1634,20 +518,14 @@ class Tree {
// Link to the Module graph
// ACL
- $group_id = (int) modules_get_agent_group($module['id']);
$acl_graphs = false;
$module["showGraphs"] = 0;
// Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions
if (!empty($group_id) && !is_metaconsole()) {
- if ($this->strictACL) {
- $acl_graphs = tags_check_acl_by_module($module['id'], $config['id_user'], 'RR') === true;
- }
- else {
- $acl_graphs = check_acl($config['id_user'], $group_id, "RR");
- }
+ $acl_graphs = check_acl_one_of_groups($config['id_user'], $all_groups, "RR");
}
- else if (!empty($group_id)) {
+ else if (!empty($all_groups)) {
$acl_graphs = true;
}
@@ -1668,7 +546,7 @@ class Tree {
"refresh" => SECONDS_10MINUTES
);
- if (is_metaconsole() && !empty($server)) {
+ if (is_metaconsole()) {
// Set the server id
$graph_params["server"] = $module['serverID'];
}
@@ -1684,26 +562,24 @@ class Tree {
// Info to be able to open the snapshot image new page
$module['snapshot'] = ui_get_snapshot_link(array(
'id_module' => $module['id'],
- 'last_data' => $module['datos'],
- 'timestamp' => $module['timestamp'],
'interval' => $module['current_interval'],
- 'module_name' => $module['name']
+ 'module_name' => $module['name'],
+ 'id_node' => $module['serverID'] ? $module['serverID'] : 0,
), true);
}
// Alerts fired image
- $has_alerts = (bool) db_get_value(
- 'COUNT(DISTINCT(id_agent_module))',
- 'talert_template_modules', 'id_agent_module', $module['id']);
-
- if ($has_alerts) {
+ if ((bool)$module['alerts']) {
$module['alertsImageHTML'] = html_print_image("images/bell.png", true, array("title" => __('Module alerts')));
}
}
protected function processModules (&$modules, $server = false) {
+ if (!empty($modules)) {
+ $all_groups = modules_get_agent_groups($modules[0]['id']);
+ }
foreach ($modules as $iterator => $module) {
- $this->processModule($modules[$iterator], $server);
+ $this->processModule($modules[$iterator], $server, $all_groups);
}
}
@@ -1723,183 +599,17 @@ class Tree {
else if (!empty($server))
$agent['serverID'] = $server['id'];
}
-
- // Realtime counters for Strict ACL
- if ($this->strictACL) {
- $agent_filter = array("id" => $agent['id']);
- $module_filter = array();
-
- if (isset($this->filter["statusAgent"]))
- $agent_filter["status"] = $this->filter["statusAgent"];
- if (isset($this->filter["searchAgent"]))
- $agent_filter["name"] = $this->filter["searchAgent"];
-
- if (isset($this->filter["statusModule"]))
- $module_filter["status"] = $this->filter["statusModule"];
- if (isset($this->filter["searchModule"]))
- $module_filter["name"] = $this->filter["searchModule"];
-
- $agent['counters'] = array();
- $agent['counters']['unknown'] = 0;
- $agent['counters']['critical'] = 0;
- $agent['counters']['warning'] = 0;
- $agent['counters']['not_init'] = 0;
- $agent['counters']['ok'] = 0;
- $agent['counters']['total'] = 0;
- $agent['counters']['alerts'] = 0;
-
- if ($agent['rootType'] == "group") {
- $agent['counters']['alerts'] = agents_get_alerts_fired($agent['id']);
-
- // With module filter
- if (isset($this->filter["statusModule"]) && $this->filter["statusModule"] != AGENT_MODULE_STATUS_ALL) {
- switch ($this->filter["statusModule"]) {
- case AGENT_MODULE_STATUS_CRITICAL_ALERT:
- case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $agent['counters']['critical'] = (int) groups_get_critical_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = $agent['counters']['critical'];
- break;
- case AGENT_MODULE_STATUS_WARNING_ALERT:
- case AGENT_MODULE_STATUS_WARNING:
- $agent['counters']['warning'] = (int) groups_get_warning_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = $agent['counters']['warning'];
- break;
- case AGENT_MODULE_STATUS_UNKNOWN:
- $agent['counters']['unknown'] = (int) groups_get_unknown_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = $agent['counters']['unknown'];
- break;
- case AGENT_MODULE_STATUS_NO_DATA:
- case AGENT_MODULE_STATUS_NOT_INIT:
- $agent['counters']['not_init'] = (int) groups_get_not_init_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = $agent['counters']['not_init'];
- break;
- case AGENT_MODULE_STATUS_NORMAL_ALERT:
- case AGENT_MODULE_STATUS_NORMAL:
- $agent['counters']['ok'] = (int) groups_get_normal_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = $agent['counters']['ok'];
- break;
- }
- }
- // Without module filter
- else {
- $agent['counters']['unknown'] = (int) groups_get_unknown_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['critical'] = (int) groups_get_critical_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['warning'] = (int) groups_get_warning_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['not_init'] = (int) groups_get_not_init_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['ok'] = (int) groups_get_normal_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- $agent['counters']['total'] = (int) groups_get_total_monitors ($agent['rootID'], $agent_filter, $module_filter, true, $this->acltags);
- }
- }
- else if ($agent['rootType'] == "tag") {
- $agent['counters']['alerts'] = (int) tags_monitors_fired_alerts ($agent['rootID'], $this->acltags, $agent['id']);
-
- // With module filter
- if (isset($this->filter["statusModule"]) && $this->filter["statusModule"] != AGENT_MODULE_STATUS_ALL) {
- switch ($this->filter["statusModule"]) {
- case AGENT_MODULE_STATUS_CRITICAL_ALERT:
- case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $agent['counters']['critical'] = (int) tags_get_critical_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = $agent['counters']['critical'];
- break;
- case AGENT_MODULE_STATUS_WARNING_ALERT:
- case AGENT_MODULE_STATUS_WARNING:
- $agent['counters']['warning'] = (int) tags_get_warning_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = $agent['counters']['warning'];
- break;
- case AGENT_MODULE_STATUS_UNKNOWN:
- $agent['counters']['unknown'] = (int) tags_get_unknown_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = $agent['counters']['unknown'];
- break;
- case AGENT_MODULE_STATUS_NO_DATA:
- case AGENT_MODULE_STATUS_NOT_INIT:
- $agent['counters']['not_init'] = (int) tags_get_not_init_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = $agent['counters']['not_init'];
- break;
- case AGENT_MODULE_STATUS_NORMAL_ALERT:
- case AGENT_MODULE_STATUS_NORMAL:
- $agent['counters']['ok'] = (int) tags_get_normal_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = $agent['counters']['ok'];
- break;
- }
- }
- // Without module filter
- else {
- $agent['counters']['unknown'] = (int) tags_get_unknown_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['critical'] = (int) tags_get_critical_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['warning'] = (int) tags_get_warning_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['not_init'] = (int) tags_get_not_init_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['ok'] = (int) tags_get_normal_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- $agent['counters']['total'] = (int) tags_get_total_monitors ($agent['rootID'], $this->acltags, $agent_filter, $module_filter);
- }
- }
-
- if (isset($this->filter["statusAgent"]) && $this->filter["statusAgent"] != AGENT_STATUS_ALL) {
- switch ($this->filter["statusAgent"]) {
- case AGENT_STATUS_CRITICAL:
- if ($agent['counters']['critical'] == 0)
- $agent = array();
- break;
- case AGENT_STATUS_WARNING:
- if ($agent['counters']['total'] == 0 || $agent['counters']['critical'] > 0 || $agent['counters']['warning'] == 0)
- $agent = array();
- break;
- case AGENT_STATUS_UNKNOWN:
- if ($agent['counters']['critical'] > 0 || $agent['counters']['warning'] > 0 || $agent['counters']['unknown'] == 0)
- $agent = array();
- break;
- case AGENT_STATUS_NOT_INIT:
- if ($agent['counters']['total'] != 0 && $agent['counters']['total'] != $agent['counters']['not_init'])
- $agent = array();
- break;
- case AGENT_STATUS_NORMAL:
- if ($agent['counters']['critical'] > 0 || $agent['counters']['warning'] > 0 || $agent['counters']['unknown'] > 0 || $agent['counters']['ok'] == 0)
- $agent = array();
- break;
- }
- // Leave the function
- if (empty($agent))
- return;
- }
- }
-
// Counters
if (empty($agent['counters'])) {
$agent['counters'] = array();
- if (isset($agent['unknown_count']))
- $agent['counters']['unknown'] = $agent['unknown_count'];
- else
- $agent['counters']['unknown'] = (int) agents_monitor_unknown($agent['id']);
-
- if (isset($agent['critical_count']))
- $agent['counters']['critical'] = $agent['critical_count'];
- else
- $agent['counters']['critical'] = (int) agents_monitor_critical($agent['id']);
-
- if (isset($agent['warning_count']))
- $agent['counters']['warning'] = $agent['warning_count'];
- else
- $agent['counters']['warning'] = (int) agents_monitor_warning($agent['id']);
-
- if (isset($agent['notinit_count']))
- $agent['counters']['not_init'] = $agent['notinit_count'];
- else
- $agent['counters']['not_init'] = (int) agents_monitor_notinit($agent['id']);
-
- if (isset($agent['normal_count']))
- $agent['counters']['ok'] = $agent['normal_count'];
- else
- $agent['counters']['ok'] = (int) agents_monitor_ok($agent['id']);
-
- if (isset($agent['total_count']))
- $agent['counters']['total'] = $agent['total_count'];
- else
- $agent['counters']['total'] = (int) agents_monitor_total($agent['id']);
-
- if (isset($agent['fired_count']))
- $agent['counters']['alerts'] = $agent['fired_count'];
- else
- $agent['counters']['alerts'] = (int) agents_get_alerts_fired($agent['id']);
+ $agent['counters']['unknown'] = isset($agent['unknown_count']) ? $agent['unknown_count'] : 0;
+ $agent['counters']['critical'] = isset($agent['critical_count']) ? $agent['critical_count'] : 0;
+ $agent['counters']['warning'] = isset($agent['warning_count']) ? $agent['warning_count'] : 0;
+ $agent['counters']['not_init'] = isset($agent['notinit_count']) ? $agent['notinit_count'] : 0;
+ $agent['counters']['ok'] = isset($agent['normal_count']) ? $agent['normal_count'] : 0;
+ $agent['counters']['total'] = isset($agent['total_count']) ? $agent['total_count'] : 0;
+ $agent['counters']['alerts'] = isset($agent['fired_count']) ? $agent['fired_count'] : 0;
}
// Status image
@@ -1913,33 +623,67 @@ class Tree {
// Alerts fired image
$agent["alertImageHTML"] = agents_tree_view_alert_img_ball($agent['counters']['alerts']);
+ // search module recalculate counters
+ if(array_key_exists('state_normal', $agent)){
+ $agent['counters']['unknown'] = $agent['state_unknown'];
+ $agent['counters']['critical'] = $agent['state_critical'];
+ $agent['counters']['warning'] = $agent['state_warning'];
+ $agent['counters']['not_init'] = $agent['state_notinit'];
+ $agent['counters']['ok'] = $agent['state_normal'];
+ $agent['counters']['total'] = $agent['state_total'];
+
+ $agent['critical_count'] = $agent['counters']['critical'];
+ $agent['warning_count'] = $agent['counters']['warning'];
+ $agent['unknown_count'] = $agent['counters']['unknown'];
+ $agent['notinit_count'] = $agent['counters']['not_init'];
+ $agent['normal_count'] = $agent['counters']['ok'];
+ $agent['total_count'] = $agent['counters']['total'];
+ }
+
+ if (!$this->getEmptyModuleFilterStatus()) {
+ $agent['counters']['unknown'] = 0;
+ $agent['counters']['critical'] = 0;
+ $agent['counters']['warning'] = 0;
+ $agent['counters']['not_init'] = 0;
+ $agent['counters']['ok'] = 0;
+ $agent['counters']['total'] = 0;
+ switch($this->filter['statusModule']) {
+ case AGENT_MODULE_STATUS_CRITICAL_ALERT:
+ case AGENT_MODULE_STATUS_CRITICAL_BAD:
+ $agent['counters']['critical'] = $agent['critical_count'];
+ $agent['counters']['total'] = $agent['critical_count'];
+ break;
+ case AGENT_MODULE_STATUS_WARNING_ALERT:
+ case AGENT_MODULE_STATUS_WARNING:
+ $agent['counters']['warning'] = $agent['warning_count'];
+ $agent['counters']['total'] = $agent['warning_count'];
+ break;
+ case AGENT_MODULE_STATUS_UNKNOWN:
+ $agent['counters']['unknown'] = $agent['unknown_count'];
+ $agent['counters']['total'] = $agent['unknown_count'];
+ break;
+ case AGENT_MODULE_STATUS_NO_DATA:
+ case AGENT_MODULE_STATUS_NOT_INIT:
+ $agent['counters']['not_init'] = $agent['notinit_count'];
+ $agent['counters']['total'] = $agent['notinit_count'];
+ break;
+ case AGENT_MODULE_STATUS_NORMAL_ALERT:
+ case AGENT_MODULE_STATUS_NORMAL:
+ $agent['counters']['ok'] = $agent['normal_count'];
+ $agent['counters']['total'] = $agent['normal_count'];
+ break;
+ }
+ }
+
+ if (!$this->filter['show_not_init_modules']) {
+ $agent['counters']['total'] -= $agent['counters']['not_init'];
+ $agent['counters']['not_init'] = 0;
+ }
+
// Quiet image
if (isset($agent['quiet']) && $agent['quiet'])
$agent['quietImageHTML'] = html_print_image("/images/dot_blue.png", true, array("title" => __('Quiet')));
- // Status
- $agent['statusRaw'] = agents_get_status($agent['id'], !$this->strictACL);
- switch ($agent['statusRaw']) {
- case AGENT_STATUS_NORMAL:
- $agent['status'] = "ok";
- break;
- case AGENT_STATUS_WARNING:
- $agent['status'] = "warning";
- break;
- case AGENT_STATUS_CRITICAL:
- $agent['status'] = "critical";
- break;
- case AGENT_STATUS_UNKNOWN:
- $agent['status'] = "unknown";
- break;
- case AGENT_STATUS_NOT_INIT:
- $agent['status'] = "not_init";
- break;
- default:
- $agent['status'] = "none";
- break;
- }
-
// Children
if (empty($agent['children'])) {
$agent['children'] = array();
@@ -1950,9 +694,6 @@ class Tree {
break;
case 'live':
$agent['searchChildren'] = 0;
-
- // if ($searchChildren)
- // $agent['children'] = $this->getModules($agent['id'], $modulesFilter);
break;
}
}
@@ -1977,800 +718,222 @@ class Tree {
}
}
- /**
- * @brief Recursive function to remove the empty groups
- *
- * @param groups All groups structure
- *
- * @return new_groups A new groups structure without empty groups
- */
- protected static function deleteEmptyGroups ($groups) {
- $new_groups = array();
- foreach ($groups as $group) {
- // If a group is empty, do not add to new_groups.
- if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) {
- continue;
- }
- // Tray to remove the children groups
- if (!empty($group['children'])) {
- $children = Tree::deleteEmptyGroups ($group['children']);
- if (empty($children)) unset($group['children']);
- else $group['children'] = $children;
- }
- $new_groups[] = $group;
- }
- return $new_groups;
+ protected function getData() {
+
}
- private static function extractGroupsWithIDs ($groups, $ids_hash) {
- $result_groups = array();
- foreach ($groups as $group) {
- if (isset($ids_hash[$group['id']])) {
- $result_groups[] = $group;
- }
- else if (!empty($group['children'])) {
- $result = self::extractGroupsWithIDs($group['children'], $ids_hash);
+ protected function getFirstLevel() {
+ $sql = $this->getFirstLevelSql();
+ $items = db_get_all_rows_sql($sql);
+ if ($items === false) $items = array();
- // Item found on children
- if (!empty($result)) {
- $result_groups = array_merge($result_groups, $result);
- }
- }
- }
-
- return $result_groups;
+ $this->tree = $this->getProcessedItemsFirstLevel($items);
}
- private static function extractItemWithID ($items, $item_id, $item_type = "group", $strictACL = false) {
- foreach ($items as $item) {
- if ($item["type"] != $item_type)
- continue;
-
- // Item found
- if ($strictACL && is_metaconsole()) {
- foreach ($item["id"] as $server_id => $id) {
- if ($id == $item_id)
- return $item;
- }
- }
- else {
- if ($item["id"] == $item_id)
- return $item;
- }
-
- if ($item["type"] == "group" && !empty($item["children"])) {
- $result = self::extractItemWithID($item["children"], $item_id, $item_type, $strictACL);
-
- // Item found on children
- if ($result !== false)
- return $result;
- }
- }
-
- // Item not found
- return false;
- }
-
- public function getData() {
- if (! is_metaconsole()) {
- if ($this->strictACL) {
- switch ($this->type) {
- case 'group':
- case 'tag':
- $this->getDataStrict();
- break;
- case 'agent':
- $this->getDataAgent();
- break;
- }
- }
- else{
- switch ($this->type) {
- case 'os':
- $this->getDataOS();
- break;
- case 'group':
- $this->getDataGroup();
- break;
- case 'module_group':
- $this->getDataModuleGroup();
- break;
- case 'module':
- $this->getDataModules();
- break;
- case 'tag':
- $this->getDataTag();
- break;
- case 'agent':
- $this->getDataAgent();
- break;
- default:
- $this->getDataExtended();
- }
- }
- }
- else if ($this->strictACL) {
- switch ($this->type) {
- case 'group':
- case 'tag':
- $this->getDataStrict();
- break;
- case 'agent':
- $this->getDataAgent();
- break;
- }
- }
- else {
- if ($this->type == 'agent') {
- $this->getDataAgent();
- }
- else {
- $this->getDataGroup();
- }
- }
- }
-
- protected function getDataExtended () {
- // Override this method to add new types
- }
-
- private function getDataAgent () {
+ protected function getProcessedItemsFirstLevel($items){
$processed_items = array();
-
- // Module names
- if ($this->id == -1) {
-
+ foreach ($items as $key => $item) {
+ $processed_item = $this->getProcessedItem($item);
+ $processed_items[] = $processed_item;
}
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processModules($items);
- $processed_items = $items;
-
- if(!$this->filter['show_not_init_modules']){
-
- foreach ($items as $key => $value) {
- if($items[$key]['total_count'] != $items[$key]['notinit_count']){
- $items[$key]['total_count'] = $items[$key]['total_count'] - $items[$key]['notinit_count'];
- $items[$key]['notinit_count'] = 0;
- }
-
- }
-
- }
- }
- else {
- $items = array();
-
- if ($this->serverID !== false) {
-
- $server = metaconsole_get_servers($this->serverID);
- if (metaconsole_connect($server) == NOERR) {
- $items = $this->getItems();
- $this->processModules($items, $server);
-
- metaconsole_restore_db();
- }
- }
-
- $processed_items = $items;
- }
- }
-
- $this->tree = $processed_items;
+ return $processed_items;
}
- private function getDataStrict () {
- global $config;
+ protected function getFirstLevelSql() {
- require_once($config['homedir']."/include/functions_groups.php");
+ $fields = $this->getFirstLevelFields();
+ $field_name_sql = $this->L1fieldNameSql;
+ $inside_fields = $this->getFirstLevelFieldsInside();
+ $inner = $this->L1inner;
+ $inner_inside = $this->L1innerInside;
+ $order_by_final = $this->L1orderByFinal;
- $processed_items = array();
-
- // Groups and tags
- if ($this->id == -1) {
- $agent_filter = array();
- if (isset($this->filter["statusAgent"]))
- $agent_filter["status"] = $this->filter["statusAgent"];
- if (isset($this->filter["searchAgent"]))
- $agent_filter["name"] = $this->filter["searchAgent"];
-
- $module_filter = array();
- if (isset($this->filter["statusModule"]))
- $module_filter["status"] = $this->filter["statusModule"];
- if (isset($this->filter["searchModule"]))
- $module_filter["name"] = $this->filter["searchModule"];
-
- if (! is_metaconsole()) {
- $items = group_get_data($config['id_user'], $this->strictACL, $this->acltags, false, 'tree', $agent_filter, $module_filter);
-
- // Build the group and tag hierarchy
- $processed_groups = array();
- $processed_tags = array();
-
- foreach ($items as $key => $item) {
- $processed_item = $this->getProcessedItem($item);
- if ($processed_item['type'] == 'tag') {
- if (!empty($processed_item) &&
- isset($processed_item['counters']) &&
- isset($processed_item['counters']['total']) &&
- !empty($processed_item['counters']['total'])) {
- $processed_tags[] = $processed_item;
- }
- }
- else {
- $processed_groups[] = $processed_item;
- }
- }
-
- // Build the groups hierarchy
- $processed_groups = $this->getProcessedGroups($processed_groups, true);
- // Sort tags
- usort($processed_tags, array("Tree", "cmpSortNames"));
-
- // Join tags and groups
- $processed_items = array_merge($processed_groups, $processed_tags);
- }
- else {
- $unmerged_items = array();
-
- $servers = metaconsole_get_servers();
- foreach ($servers as $server) {
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $items = group_get_data($config['id_user'], $this->strictACL, $this->acltags, false, 'tree', $agent_filter, $module_filter);
-
- // Build the group and tag hierarchy
- $processed_groups = array();
- $processed_tags = array();
-
- foreach ($items as $key => $item) {
- $processed_item = $this->getProcessedItem($item);
- if ($processed_item['type'] == 'tag')
- $processed_tags[] = $processed_item;
- else
- $processed_groups[] = $processed_item;
- }
-
- // Build the groups hierarchy
- $processed_groups = $this->getProcessedGroups($processed_groups);
- // Sort tags
- usort($processed_tags, array("Tree", "cmpSortNames"));
-
- // Join tags and groups
- $processed_items = array_merge($processed_groups, $processed_tags);
-
- $unmerged_items += $processed_items;
-
- metaconsole_restore_db();
- }
-
- $processed_items = $this->getMergedItems($unmerged_items);
- }
-
- if (!empty($processed_items)) {
- if (!empty($this->filter["groupID"])) {
- $result = self::extractItemWithID($processed_items, $this->filter["groupID"], "group", $this->strictACL);
-
- if ($result === false)
- $processed_items = array();
- else
- $processed_items = array($result);
- }
- else if (!empty($this->filter["tagID"])) {
- $result = self::extractItemWithID($processed_items, $this->filter["tagID"], "tag", $this->strictACL);
-
- if ($result === false)
- $processed_items = array();
- else
- $processed_items = array($result);
- }
- }
- }
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processAgents($items);
- // Remove empty entrys
- $processed_items = array_filter($items);
- // Restart the array keys -> Important!
- $processed_items = array_values($processed_items);
- }
- else {
- $rootIDs = $this->rootID;
-
- $items = array();
- $j = 1;
- $server = metaconsole_get_servers();
- foreach ($rootIDs as $serverID => $rootID) {
- if (metaconsole_connect($server[$j]) != NOERR)
- continue;
- db_clean_cache();
-
- $this->rootID = $rootID;
- $newItems = $this->getItems();
- $this->processAgents($newItems, $server[$j]);
- $newItems = array_filter($newItems);
- $items = array_merge($items, $newItems);
-
- metaconsole_restore_db();
- $j++;
- }
- $this->rootID = $rootIDs;
-
- if (!empty($items))
- usort($items, array("Tree", "cmpSortNames"));
-
- $processed_items = $items;
- }
+ $group_inner = $this->getGroupSearchInner();
+ $group_acl = $this->getGroupAclCondition();
+ $group_search_filter = $this->getGroupSearchFilter();
+ $agent_search_filter = $this->getAgentSearchFilter();
+ $agent_status_filter = $this->getAgentStatusFilter();
+ $module_search_filter = $this->getModuleSearchFilter();
+ $module_status_inner = "";
+ $module_status_filter = $this->getModuleStatusFilterFromTestado();
+ if (!empty($module_status_filter)) {
+ $module_status_inner = "
+ INNER JOIN tagente_estado tae
+ ON tae.id_agente_modulo = tam.id_agente_modulo";
}
- $this->tree = $processed_items;
+ $sql_model = "SELECT %s FROM
+ (
+ SELECT COUNT(DISTINCT(ta.id_agente)) AS total, $field_name_sql AS g
+ FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ INNER JOIN tagente_modulo tam
+ ON ta.id_agente = tam.id_agente
+ $inner_inside
+ $module_status_inner
+ $group_inner
+ WHERE ta.disabled = 0
+ AND tam.disabled = 0
+ %s
+ $agent_search_filter
+ $agent_status_filter
+ $module_search_filter
+ $module_status_filter
+ $group_search_filter
+ $group_acl
+ GROUP BY $field_name_sql
+ ) x GROUP BY g";
+ $sql_array = array();
+ foreach ($inside_fields as $inside_field) {
+ $sql_array[] = sprintf(
+ $sql_model,
+ $inside_field['header'],
+ $inside_field['condition']
+ );
+ }
+ $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2
+ $inner
+ GROUP BY g
+ ORDER BY $order_by_final";
+ return $sql;
}
- private function getDataGroup() {
- $processed_items = array();
-
- // Groups
- if ($this->id == -1) {
-
- $items = $this->getItems();
-
- $processed_items = $this->getProcessedGroups($items, true);
-
- if (!empty($processed_items)) {
- // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants
- if (!empty($this->filter['searchGroup'])) {
- // Save the groups which intersect with the user groups
- $groups = db_get_all_rows_filter('tgrupo', array('nombre' => '%' . $this->filter['searchGroup'] . '%'));
- if ($groups == false) $groups = array();
- $userGroupsACL = $this->userGroupsACL;
- $ids_hash = array_reduce($groups, function ($userGroups, $group) use ($userGroupsACL) {
- $group_id = $group['id_grupo'];
- if (isset($userGroupsACL[$group_id])) {
- $userGroups[$group_id] = $userGroupsACL[$group_id];
- }
-
- return $userGroups;
- }, array());
-
- $result = self::extractGroupsWithIDs($processed_items, $ids_hash);
-
- $processed_items = ($result === false) ? array() : $result;
- }
-
- // groupID filter. To access the view from tactical views f.e.
- if (!empty($this->filter['groupID'])) {
- $result = self::extractItemWithID($processed_items, $this->filter['groupID'], "group", $this->strictACL);
-
- $processed_items = ($result === false) ? array() : array($result);
- }
- }
- }
- // Agents
- else {
- $items = $this->getItems();
-
-
- if(!$this->filter['show_not_init_modules']){
-
- foreach ($items as $key => $value) {
- $items[$key]['total_count'] = $items[$key]['total_count'] - $items[$key]['notinit_count'];
- $items[$key]['notinit_count'] = 0;
-
- }
-
- }
-
- if(!$this->filter['show_not_init_agents']){
-
- foreach ($items as $key => $value) {
- if($items[$key]['total_count'] == $items[$key]['notinit_count']){
- unset($items[$key]);
- }
- }
-
- }
-
- $this->processAgents($items);
- $processed_items = $items;
+ protected function getSecondLevel() {
+ $sql = $this->getSecondLevelSql();
+ $data = db_process_sql($sql);
+ if (empty($data)) {
+ $this->tree = array();
+ return;
}
+ $this->processAgents($data);
- $this->tree = $processed_items;
+ $this->tree = $data;
}
- private function getDataTag() {
- $processed_items = array();
+ protected function getSecondLevelSql() {
+ $columns = sprintf("ta.id_agente AS id, ta.nombre AS name, ta.alias,
+ ta.fired_count, ta.normal_count, ta.warning_count,
+ ta.critical_count, ta.unknown_count, ta.notinit_count,
+ ta.total_count, ta.quiet,
+ SUM(if(%s, 1, 0)) as state_critical,
+ SUM(if(%s, 1, 0)) as state_warning,
+ SUM(if(%s, 1, 0)) as state_unknown,
+ SUM(if(%s, 1, 0)) as state_notinit,
+ SUM(if(%s, 1, 0)) as state_normal,
+ SUM(if(%s AND tae.estado IS NOT NULL, 1, 0)) as state_total
+ ",
+ $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_CRITICAL_ALERT, true),
+ $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_WARNING_ALERT, true),
+ $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_UNKNOWN, true),
+ $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NO_DATA, true),
+ $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NORMAL, true),
+ $this->getModuleStatusFilterFromTestado(self::TV_DEFAULT_AGENT_STATUS, true)
+ );
- // Tags
- if ($this->id == -1) {
- if (! is_metaconsole()) {
- $items = $this->getItems();
+ $inner_or_left = $this->getInnerOrLeftJoin();
+ $group_inner = $this->getGroupSearchInner();
+ $group_acl = $this->getGroupAclCondition();
+ $group_search_filter = $this->getGroupSearchFilter();
+ $agent_search_filter = $this->getAgentSearchFilter();
+ $agent_status_filter = $this->getAgentStatusFilter();
+ $module_search_filter = $this->getModuleSearchFilter();
+ $module_status_filter = $this->getModuleStatusFilter();
- foreach ($items as $key => $item) {
+ $condition = $this->L2condition;
+ $condition_inside = $this->L2conditionInside;
+ $inner = $this->L2inner;
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
+ $sql = "SELECT $columns
+ FROM tagente ta
+ $inner_or_left JOIN tagente_modulo tam
+ ON ta.id_agente = tam.id_agente
+ AND tam.disabled = 0
+ $inner_or_left JOIN tagente_estado tae
+ ON tae.id_agente_modulo = tam.id_agente_modulo
+ $inner
+ WHERE ta.id_agente IN
+ (
+ SELECT ta.id_agente
+ FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON tasg.id_agent = ta.id_agente
+ $group_inner
+ WHERE ta.disabled = 0
+ $group_acl
+ $group_search_filter
+ $condition_inside
+ )
+ AND ta.disabled = 0
+ $condition
+ $agent_search_filter
+ $agent_status_filter
+ $module_search_filter
+ $module_status_filter
+ GROUP BY ta.id_agente
+ ORDER BY ta.alias ASC, ta.id_agente ASC
+ ";
- $processed_item = $this->getProcessedItem($item);
- $processed_items[] = $processed_item;
- }
- }
- else {
- $servers = metaconsole_get_servers();
-
- $item_list = array();
- foreach ($servers as $server) {
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $items = $this->getItems();
-
- $processed_items = array();
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $processed_item = $this->getProcessedItem($item, $server);
- $processed_items[] = $processed_item;
- }
- $item_list = array_merge($item_list, $processed_items);
-
- metaconsole_restore_db();
- }
-
- $processed_items = $this->getMergedItems($item_list);
- }
- }
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processAgents($items);
- $processed_items = $items;
- }
- else {
- $rootIDs = $this->rootID;
-
- $items = array();
- foreach ($rootIDs as $serverID => $rootID) {
- $server = metaconsole_get_servers($serverID);
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $this->rootID = $rootID;
- $newItems = $this->getItems();
- $this->processAgents($newItems, $server);
- $items = array_merge($items, $newItems);
-
- metaconsole_restore_db();
- }
- $this->rootID = $rootIDs;
-
- if (!empty($items))
- usort($items, array("Tree", "cmpSortNames"));
-
- $processed_items = $items;
- }
- }
-
- $this->tree = $processed_items;
+ return $sql;
}
- private function getDataModules() {
- $processed_items = array();
-
- // Module names
- if ($this->id == -1) {
- if (! is_metaconsole()) {
- $items = $this->getItems();
-
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['name']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $name = str_replace(array(' ','#','/','.','(',')','¿','?','¡','!'),
- array( '_articapandora_'.ord(' ').'_pandoraartica_',
- '_articapandora_'.ord('#').'_pandoraartica_',
- '_articapandora_'.ord('/').'_pandoraartica_',
- '_articapandora_'.ord('.').'_pandoraartica_',
- '_articapandora_'.ord('(').'_pandoraartica_',
- '_articapandora_'.ord(')').'_pandoraartica_',
- '_articapandora_'.ord('¿').'_pandoraartica_',
- '_articapandora_'.ord('?').'_pandoraartica_',
- '_articapandora_'.ord('¡').'_pandoraartica_',
- '_articapandora_'.ord('!').'_pandoraartica_'),
- io_safe_output($item['name']));
-
- $processed_item = $this->getProcessedItem($item);
- $processed_item['id'] = $name;
- $processed_item['rootID'] = $name;
-
- $processed_items[] = $processed_item;
- }
- }
- else {
- $servers = metaconsole_get_servers();
-
- $item_list = array();
- foreach ($servers as $server) {
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $items = $this->getItems();
-
- $processed_items = array();
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['name']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $name = str_replace(array(' ','#','/','.','(',')','¿','?','¡','!'),
- array( '_articapandora_'.ord(' ').'_pandoraartica_',
- '_articapandora_'.ord('#').'_pandoraartica_',
- '_articapandora_'.ord('/').'_pandoraartica_',
- '_articapandora_'.ord('.').'_pandoraartica_',
- '_articapandora_'.ord('(').'_pandoraartica_',
- '_articapandora_'.ord(')').'_pandoraartica_',
- '_articapandora_'.ord('¿').'_pandoraartica_',
- '_articapandora_'.ord('?').'_pandoraartica_',
- '_articapandora_'.ord('¡').'_pandoraartica_',
- '_articapandora_'.ord('!').'_pandoraartica_'),
- io_safe_output($item['name']));
-
- $processed_item = $this->getProcessedItem($item, $server);
- $processed_item['id'] = $name;
- $processed_item['rootID'] = $name;
-
- $processed_items[] = $processed_item;
- }
- $item_list = array_merge($item_list, $processed_items);
-
- metaconsole_restore_db();
- }
-
- $processed_items = $this->getMergedItems($item_list);
- }
+ protected function getThirdLevel() {
+ $sql = $this->getThirdLevelSql();
+ $data = db_process_sql($sql);
+ if (empty($data)) {
+ $this->tree = array();
+ return;
}
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processAgents($items);
- $processed_items = $items;
- }
- else {
- $rootIDs = $this->rootID;
+ $data = $this->getProcessedModules($data);
+ $this->processModules($data);
- $items = array();
- foreach ($rootIDs as $serverID => $rootID) {
- $server = metaconsole_get_servers($serverID);
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $this->rootID = $rootID;
- $newItems = $this->getItems();
- $this->processAgents($newItems, $server);
- $items = array_merge($items, $newItems);
-
- metaconsole_restore_db();
- }
- $this->rootID = $rootIDs;
-
- if (!empty($items))
- usort($items, array("Tree", "cmpSortNames"));
-
- $processed_items = $items;
- }
- }
-
- $this->tree = $processed_items;
+ $this->tree = $data;
}
- private function getDataModuleGroup() {
- $processed_items = array();
+ protected function getThirdLevelSql() {
+ // Get the server id
+ $serverID = $this->serverID;
- // Module groups
- if ($this->id == -1) {
- if (! is_metaconsole()) {
- $items = $this->getItems();
+ $group_acl = $this->getGroupAclCondition();
+ $agent_search_filter = $this->getAgentSearchFilter();
+ $agent_status_filter = $this->getAgentStatusFilter();
+ $module_search_filter = $this->getModuleSearchFilter();
+ $module_status_filter = $this->getModuleStatusFilterFromTestado();
+ $agent_filter = "AND ta.id_agente = " . $this->id;
+ $tag_join = $this->getTagJoin();
- foreach ($items as $key => $item) {
+ $condition = $this->L2condition;
+ $inner = $this->L2inner;
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
+ $columns = 'DISTINCT(tam.id_agente_modulo) AS id, tam.nombre AS name,
+ tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos,
+ tam.parent_module_id AS parent, tatm.id AS alerts';
- $processed_item = $this->getProcessedItem($item);
- $processed_items[] = $processed_item;
- }
- }
- else {
- $servers = metaconsole_get_servers();
+ // has any of this tags.
+ $tag_join = '';
- $item_list = array();
- foreach ($servers as $server) {
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $items = $this->getItems();
-
- $processed_items = array();
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $processed_item = $this->getProcessedItem($item, $server);
- $processed_items[] = $processed_item;
- }
- $item_list = array_merge($item_list, $processed_items);
-
- metaconsole_restore_db();
- }
-
- $processed_items = $this->getMergedItems($item_list);
- }
- }
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processAgents($items);
- $processed_items = $items;
- }
- else {
- $rootIDs = $this->rootID;
-
- $items = array();
- foreach ($rootIDs as $serverID => $rootID) {
- $server = metaconsole_get_servers($serverID);
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $this->rootID = $rootID;
- $newItems = $this->getItems();
- $this->processAgents($newItems, $server);
- $items = array_merge($items, $newItems);
-
- metaconsole_restore_db();
- }
- $this->rootID = $rootIDs;
-
- if (!empty($items))
- usort($items, array("Tree", "cmpSortNames"));
-
- $processed_items = $items;
- }
- }
-
- $this->tree = $processed_items;
- }
-
- private function getDataOS() {
- $processed_items = array();
-
- // OS
- if ($this->id == -1) {
- if (! is_metaconsole()) {
- $items = $this->getItems();
-
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $processed_item = $this->getProcessedItem($item);
- $processed_item['icon'] = $item['os_icon'];
- $processed_items[] = $processed_item;
- }
- }
- else {
- $servers = metaconsole_get_servers();
-
- $item_list = array();
- foreach ($servers as $server) {
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $items = $this->getItems();
-
- $processed_items = array();
- foreach ($items as $key => $item) {
-
- $counters = $this->getCounters($item['id']);
- if (!empty($counters)) {
- foreach ($counters as $type => $value) {
- $item[$type] = $value;
- }
- }
-
- $processed_item = $this->getProcessedItem($item, $server);
- $processed_item['icon'] = $item['os_icon'];
- $processed_items[] = $processed_item;
- }
- $item_list = array_merge($item_list, $processed_items);
-
- metaconsole_restore_db();
- }
-
- $processed_items = $this->getMergedItems($item_list);
- }
- }
- // Agents
- else {
- if (! is_metaconsole()) {
- $items = $this->getItems();
- $this->processAgents($items);
- $processed_items = $items;
- }
- else {
- $rootIDs = $this->rootID;
-
- $items = array();
- foreach ($rootIDs as $serverID => $rootID) {
- $server = metaconsole_get_servers($serverID);
- if (metaconsole_connect($server) != NOERR)
- continue;
- db_clean_cache();
-
- $this->rootID = $rootID;
- $newItems = $this->getItems();
- $this->processAgents($newItems, $server);
- $items = array_merge($items, $newItems);
-
- metaconsole_restore_db();
- }
- $this->rootID = $rootIDs;
-
- if (!empty($items))
- usort($items, array("Tree", "cmpSortNames"));
-
- $processed_items = $items;
- }
- }
-
- $this->tree = $processed_items;
+ $sql = "SELECT $columns
+ FROM tagente_modulo tam
+ $tag_join
+ INNER JOIN tagente_estado tae
+ ON tam.id_agente_modulo = tae.id_agente_modulo
+ INNER JOIN tagente ta
+ ON tam.id_agente = ta.id_agente
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ LEFT JOIN talert_template_modules tatm
+ ON tatm.id_agent_module = tam.id_agente_modulo
+ $inner
+ WHERE tam.disabled = 0 AND ta.disabled = 0
+ $condition
+ $agent_filter
+ $group_acl
+ $agent_search_filter
+ $agent_status_filter
+ $module_status_filter
+ $module_search_filter
+ ORDER BY tam.nombre ASC, tam.id_agente_modulo ASC";
+ return $sql;
}
public function getJSON() {
@@ -2785,112 +948,37 @@ class Tree {
return $this->tree;
}
- static function processCounters(&$groups) {
- $all_counters = array();
- foreach ($groups as $id => $group) {
- $child_counters = array();
- if (!empty($groups[$id]['children'])) {
- $child_counters = Tree::processCounters($groups[$id]['children']);
- }
- if (!empty($child_counters)) {
- foreach($child_counters as $type => $value) {
- $groups[$id]['counters'][$type] += $value;
- }
- }
- foreach($groups[$id]['counters'] as $type => $value) {
- $all_counters[$type] += $value;
- }
+ static function name2symbol($name) {
+ return str_replace(
+ array(' ','#','/','.','(',')','¿','?','¡','!'),
+ array(
+ '_articapandora_'.ord(' ').'_pandoraartica_',
+ '_articapandora_'.ord('#').'_pandoraartica_',
+ '_articapandora_'.ord('/').'_pandoraartica_',
+ '_articapandora_'.ord('.').'_pandoraartica_',
+ '_articapandora_'.ord('(').'_pandoraartica_',
+ '_articapandora_'.ord(')').'_pandoraartica_',
+ '_articapandora_'.ord('¿').'_pandoraartica_',
+ '_articapandora_'.ord('?').'_pandoraartica_',
+ '_articapandora_'.ord('¡').'_pandoraartica_',
+ '_articapandora_'.ord('!').'_pandoraartica_'
+ ),
+ io_safe_output($name)
+ );
+ }
+
+ static function symbol2name($name) {
+ $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~';
+ for ($i = 0; $i < strlen($symbols); $i++) {
+ $name = str_replace('_articapandora_' .
+ ord(substr($symbols, $i, 1)) .'_pandoraartica_',
+ substr($symbols, $i, 1), $name);
}
- return $all_counters;
+ return io_safe_input($name);
}
protected function getProcessedModules($modules_tree) {
- $tree_modules = array();
- $new_modules_root = array_filter($modules_tree, function ($module) {
- return (isset($module['parent']) && ($module['parent'] == 0));
- });
-
- $new_modules_child = array_filter($modules_tree, function ($module) {
- return (isset($module['parent']) && ($module['parent'] != 0));
- });
-
- while (!empty($new_modules_child)) {
- foreach ($new_modules_child as $i => $child) {
- Tree::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child);
- }
- }
-
- foreach ($new_modules_root as $m) {
- $tree_modules[] = $m;
- }
-
- return $tree_modules;
- }
-
- protected function getGroupCounters($group_id) {
- global $config;
- static $group_stats = false;
- // FIXME: Avoid to use cache when secondary groups is used
- if (enterprise_hook('agents_is_using_secondary_groups')) {
- return $this->getCounters($group_id);
- }
- # Do not use the group stat cache when using tags or real time group stats.
- if ($config['realtimestats'] == 1 ||
- (isset($this->userGroups[$group_id]['tags']) && $this->userGroups[$group_id]['tags'] != "") ||
- !empty($this->filter['searchAgent']) ) {
- return $this->getCounters($group_id);
- }
-
- # Update the group stat cache.
- if ( $group_stats === false) {
- $group_stats = array();
- $stats = db_get_all_rows_sql('SELECT * FROM tgroup_stat');
- foreach ($stats as $group) {
- if ($group['modules'] > 0) {
- $group_stats[$group['id_group']]['total_count'] = $group['modules'] > 0 ? $group['agents'] : 0;
- $group_stats[$group['id_group']]['total_critical_count'] = $group['critical'];
- $group_stats[$group['id_group']]['total_unknown_count'] = $group['unknown'];
- $group_stats[$group['id_group']]['total_warning_count'] = $group['warning'];
- if($this->filter['show_not_init_modules']){
- $group_stats[$group['id_group']]['total_not_init_count'] = $group['non-init'];
- }
- else{
- $group_stats[$group['id_group']]['total_not_init_count'] = 0;
- }
- $group_stats[$group['id_group']]['total_normal_count'] = $group['normal'];
- $group_stats[$group['id_group']]['total_fired_count'] = $group['alerts_fired'];
- }
- # Skip groups without modules.
- else {
- $group_stats[$group['id_group']]['total_count'] = 0;
- $group_stats[$group['id_group']]['total_critical_count'] = 0;
- $group_stats[$group['id_group']]['total_unknown_count'] = 0;
- $group_stats[$group['id_group']]['total_warning_count'] = 0;
- $group_stats[$group['id_group']]['total_not_init_count'] = 0;
- $group_stats[$group['id_group']]['total_normal_count'] = 0;
- $group_stats[$group['id_group']]['total_fired_count'] = 0;
- }
- }
- }
-
- if ($group_stats !== false && isset($group_stats[$group_id])) {
- return $group_stats[$group_id];
- }
-
- return $this->getCounters($group_id);
- }
-
- static function recursive_modules_tree_view (&$new_modules, &$new_modules_child, $i, $child) {
- foreach ($new_modules as $index => $module) {
- if ($module['id'] == $child['parent']) {
- $new_modules[$index]['children'][] = $child;
- unset($new_modules_child[$i]);
- break;
- }
- else if (isset($new_modules[$index]['children'])) {
- Tree::recursive_modules_tree_view ($new_modules[$index]['children'], $new_modules_child, $i, $child);
- }
- }
+ return $modules_tree;
}
}
diff --git a/pandora_console/include/class/TreeGroup.class.php b/pandora_console/include/class/TreeGroup.class.php
new file mode 100644
index 0000000000..ced6b8d442
--- /dev/null
+++ b/pandora_console/include/class/TreeGroup.class.php
@@ -0,0 +1,457 @@
+L1fieldName = "id_group";
+ $this->L1extraFields = array(
+ "tg.nombre AS `name`",
+ "tg.icon",
+ "tg.id_grupo AS gid"
+ );
+
+ $this->L2conditionInside = "AND (
+ ta.id_grupo = " . $this->id . "
+ OR tasg.id_group = " . $this->id . "
+ )";
+ }
+
+ public function setPropagateCounters($value) {
+ $this->propagateCounters = (bool)$value;
+ }
+
+ public function setDisplayAllGroups($value) {
+ $this->displayAllGroups = (bool)$value;
+ }
+
+ protected function getData() {
+ if ($this->id == -1) {
+ $this->getFirstLevel();
+ } elseif ($this->type == 'group') {
+ $this->getSecondLevel();
+ } elseif ($this->type == 'agent') {
+ $this->getThirdLevel();
+ }
+ }
+
+ protected function getGroupSearchFilter() {
+ return "";
+ }
+
+ protected function getFirstLevel() {
+ $processed_items = $this->getProcessedGroups();
+
+ if (!empty($processed_items)) {
+ // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants
+ if (!empty($this->filter['searchGroup'])) {
+ // Save the groups which intersect with the user groups
+ $groups = db_get_all_rows_filter('tgrupo', array('nombre' => '%' . $this->filter['searchGroup'] . '%'));
+ if ($groups == false) $groups = array();
+ $userGroupsACL = $this->userGroupsACL;
+ $ids_hash = array_reduce($groups, function ($userGroups, $group) use ($userGroupsACL) {
+ $group_id = $group['id_grupo'];
+ if (isset($userGroupsACL[$group_id])) {
+ $userGroups[$group_id] = $userGroupsACL[$group_id];
+ }
+
+ return $userGroups;
+ }, array());
+
+ $result = self::extractGroupsWithIDs($processed_items, $ids_hash);
+
+ $processed_items = ($result === false) ? array() : $result;
+ }
+
+ // groupID filter. To access the view from tactical views f.e.
+ if (!empty($this->filter['groupID'])) {
+ $result = self::extractItemWithID($processed_items, $this->filter['groupID'], "group", $this->strictACL);
+
+ $processed_items = ($result === false) ? array() : array($result);
+ }
+ }
+
+ $this->tree = $processed_items;
+ }
+
+ protected function getProcessedGroups () {
+ $processed_groups = array();
+ // Index and process the groups
+ $groups = $this->getGroupCounters();
+
+ // If user have not permissions in parent, set parent node to 0 (all)
+ // Avoid to do foreach for admins
+ if (!users_can_manage_group_all("AR")) {
+ foreach ($groups as $id => $group) {
+ if (!isset($this->userGroups[$groups[$id]['parent']])) {
+ $groups[$id]['parent'] = 0;
+ }
+ }
+ }
+ // Build the group hierarchy
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) {
+ $parent = $groups[$id]['parent'];
+ // Parent exists
+ if (!isset($groups[$parent]['children'])) {
+ $groups[$parent]['children'] = array();
+ }
+ // Store a reference to the group into the parent
+ $groups[$parent]['children'][] = &$groups[$id];
+ // This group was introduced into a parent
+ $groups[$id]['have_parent'] = true;
+ }
+ }
+ // Sort the children groups
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['children'])) {
+ usort($groups[$id]['children'], array("Tree", "cmpSortNames"));
+ }
+ }
+ //Filter groups and eliminates the reference to children groups out of her parent
+ $groups = array_filter($groups, function ($group) {
+ return !$group['have_parent'];
+ });
+ // Propagate child counters to her parents
+
+ if ($this->propagateCounters) {
+ TreeGroup::processCounters($groups);
+ // Filter groups and eliminates the reference to empty groups
+ $groups = $this->deleteEmptyGroups($groups);
+ } else {
+ $groups = $this->deleteEmptyGroupsNotPropagate($groups);
+ }
+
+ usort($groups, array("Tree", "cmpSortNames"));
+ return $groups;
+ }
+
+ protected function getGroupCounters() {
+ $fields = $this->getFirstLevelFields();
+ $inside_fields = $this->getFirstLevelFieldsInside();
+
+ $group_acl = "";
+ $secondary_group_acl = "";
+ if (!users_can_manage_group_all("AR")) {
+ $user_groups_str = implode(",", $this->userGroupsArray);
+ $group_acl = " AND ta.id_grupo IN ($user_groups_str)";
+ $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)";
+ }
+ $agent_search_filter = $this->getAgentSearchFilter();
+ $agent_search_filter = preg_replace("/%/", "%%", $agent_search_filter);
+ $agent_status_filter = $this->getAgentStatusFilter();
+ $module_status_filter = $this->getModuleStatusFilter();
+
+ $module_search_inner = "";
+ $module_search_filter = "";
+ if (!empty($this->filter['searchModule'])) {
+ $module_search_inner = "
+ INNER JOIN tagente_modulo tam
+ ON ta.id_agente = tam.id_agente
+ INNER JOIN tagente_estado tae
+ ON tae.id_agente_modulo = tam.id_agente_modulo";
+ $module_search_filter = "AND tam.disabled = 0
+ AND tam.nombre LIKE '%%" . $this->filter['searchModule'] . "%%' " .
+ $this->getModuleStatusFilterFromTestado()
+ ;
+ }
+
+ $table = is_metaconsole() ? "tmetaconsole_agent" : "tagente";
+ $table_sec = is_metaconsole() ? "tmetaconsole_agent_secondary_group" : "tagent_secondary_group";
+
+ $sql_model = "SELECT %s FROM
+ (
+ SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_grupo AS g
+ FROM $table ta
+ $module_search_inner
+ WHERE ta.disabled = 0
+ %s
+ $agent_search_filter
+ $agent_status_filter
+ $module_status_filter
+ $module_search_filter
+ $group_acl
+ GROUP BY id_grupo
+ UNION ALL
+ SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_group AS g
+ FROM $table ta INNER JOIN $table_sec tasg
+ ON ta.id_agente = tasg.id_agent
+ $module_search_inner
+ WHERE ta.disabled = 0
+ %s
+ $agent_search_filter
+ $agent_status_filter
+ $module_status_filter
+ $module_search_filter
+ $secondary_group_acl
+ GROUP BY id_group
+ ) x GROUP BY g";
+ $sql_array = array();
+ foreach ($inside_fields as $inside_field) {
+ $sql_array[] = sprintf(
+ $sql_model,
+ $inside_field['header'],
+ $inside_field['condition'],
+ $inside_field['condition']
+ );
+ }
+ $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2
+ RIGHT JOIN tgrupo tg
+ ON x2.g = tg.id_grupo
+ GROUP BY tg.id_grupo";
+ $stats = db_get_all_rows_sql($sql);
+
+ $group_stats = array();
+ foreach ($stats as $group) {
+ $group_stats[$group['gid']]['total_count'] = (int)$group['total_count'];
+ $group_stats[$group['gid']]['total_critical_count'] = (int)$group['total_critical_count'];
+ $group_stats[$group['gid']]['total_unknown_count'] = (int)$group['total_unknown_count'];
+ $group_stats[$group['gid']]['total_warning_count'] = (int)$group['total_warning_count'];
+ $group_stats[$group['gid']]['total_not_init_count'] = (int)$group['total_not_init_count'];
+ $group_stats[$group['gid']]['total_normal_count'] = (int)$group['total_normal_count'];
+ $group_stats[$group['gid']]['total_fired_count'] = (int)$group['total_alerts_count'];
+ $group_stats[$group['gid']]['name'] = $group['name'];
+ $group_stats[$group['gid']]['parent'] = $group['parent'];
+ $group_stats[$group['gid']]['icon'] = $group['icon'];
+ $group_stats[$group['gid']]['id'] = $group['gid'];
+ $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]);
+ }
+
+ return $group_stats;
+ }
+
+ protected function getFirstLevelFields() {
+ $fields = parent::getFirstLevelFields();
+ $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent';
+ return "$fields, $parent";
+ }
+
+ protected function getProcessedModules($modules_tree) {
+
+ $groups = array();
+ foreach ($modules_tree as $group) {
+ $groups[$group["id"]] = $group;
+ }
+
+ // Build the module hierarchy
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) {
+ $parent = $groups[$id]['parent'];
+ // Parent exists
+ if (!isset($groups[$parent]['children'])) {
+ $groups[$parent]['children'] = array();
+ }
+ // Store a reference to the group into the parent
+ $groups[$parent]['children'][] = &$groups[$id];
+ // This group was introduced into a parent
+ $groups[$id]['have_parent'] = true;
+ }
+ }
+
+ // Sort the children groups
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['children'])) {
+ usort($groups[$id]['children'], array("Tree", "cmpSortNames"));
+ }
+ }
+ //Filter groups and eliminates the reference to children groups out of her parent
+ $groups = array_filter($groups, function ($group) {
+ return !$group['have_parent'];
+ });
+
+ return array_values($groups);
+ }
+
+ // FIXME: Hierarchy lops is broken
+ protected function getProcessedModules_old($modules_tree) {
+
+ $tree_modules = array();
+ $new_modules_root = array_filter($modules_tree, function ($module) {
+ return (isset($module['parent']) && ($module['parent'] == 0));
+ });
+
+ $new_modules_child = array_filter($modules_tree, function ($module) {
+ return (isset($module['parent']) && ($module['parent'] != 0));
+ });
+
+ $i = 0;
+ while (!empty($new_modules_child)) {
+ foreach ($new_modules_child as $i => $child) {
+ TreeGroup::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child);
+ }
+ }
+
+ foreach ($new_modules_root as $m) {
+ $tree_modules[] = $m;
+ }
+ return $tree_modules;
+ }
+
+ // FIXME with getProcessedModules_old
+ static function recursive_modules_tree_view (&$new_modules, &$new_modules_child, $i, $child) {
+ foreach ($new_modules as $index => $module) {
+ if ($module['id'] == $child['parent']) {
+ $new_modules[$index]['children'][] = $child;
+ unset($new_modules_child[$i]);
+ break;
+ }
+ else if (isset($new_modules[$index]['children'])) {
+ TreeGroup::recursive_modules_tree_view ($new_modules[$index]['children'], $new_modules_child, $i, $child);
+ }
+ }
+ }
+
+ static function processCounters(&$groups) {
+ $all_counters = array();
+ foreach ($groups as $id => $group) {
+ $child_counters = array();
+ if (!empty($groups[$id]['children'])) {
+ $child_counters = TreeGroup::processCounters($groups[$id]['children']);
+ }
+ if (!empty($child_counters)) {
+ foreach($child_counters as $type => $value) {
+ $groups[$id]['counters'][$type] += $value;
+ }
+ }
+ foreach($groups[$id]['counters'] as $type => $value) {
+ $all_counters[$type] += $value;
+ }
+ }
+ return $all_counters;
+ }
+
+ /**
+ * @brief Recursive function to remove the empty groups
+ *
+ * @param groups All groups structure
+ *
+ * @return new_groups A new groups structure without empty groups
+ */
+ protected function deleteEmptyGroups ($groups) {
+ if($this->displayAllGroups) return $groups;
+ $new_groups = array();
+ foreach ($groups as $group) {
+ // If a group is empty, do not add to new_groups.
+ if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) {
+ continue;
+ }
+ // Tray to remove the children groups
+ if (!empty($group['children'])) {
+ $children = $this->deleteEmptyGroups ($group['children']);
+ if (empty($children)) unset($group['children']);
+ else $group['children'] = $children;
+ }
+ $new_groups[] = $group;
+ }
+ return $new_groups;
+ }
+
+ protected function deleteEmptyGroupsNotPropagate ($groups) {
+ if($this->displayAllGroups) return $groups;
+ $new_groups = array();
+ foreach ($groups as $group) {
+ // Tray to remove the children groups
+ if (!empty($group['children'])) {
+ $children = $this->deleteEmptyGroupsNotPropagate ($group['children']);
+ if (empty($children)) {
+ unset($group['children']);
+ // If a group is empty, do not add to new_groups.
+ if (isset($group['counters']['total']) && $group['counters']['total'] != 0) {
+ $new_groups[] = $group;
+ }
+ } else {
+ $group['children'] = $children;
+ $new_groups[] = $group;
+ }
+ } else {
+ // If a group is empty, do not add to new_groups.
+ if (isset($group['counters']['total']) && $group['counters']['total'] != 0) {
+ $new_groups[] = $group;
+ }
+ }
+ }
+ return $new_groups;
+ }
+
+ private static function extractGroupsWithIDs ($groups, $ids_hash) {
+ $result_groups = array();
+ foreach ($groups as $group) {
+ if (isset($ids_hash[$group['id']])) {
+ $result_groups[] = $group;
+ }
+ else if (!empty($group['children'])) {
+ $result = self::extractGroupsWithIDs($group['children'], $ids_hash);
+
+ // Item found on children
+ if (!empty($result)) {
+ $result_groups = array_merge($result_groups, $result);
+ }
+ }
+ }
+
+ return $result_groups;
+ }
+
+ private static function extractItemWithID ($items, $item_id, $item_type = "group", $strictACL = false) {
+ foreach ($items as $item) {
+ if ($item["type"] != $item_type)
+ continue;
+
+ // Item found
+ if ($strictACL && is_metaconsole()) {
+ foreach ($item["id"] as $server_id => $id) {
+ if ($id == $item_id)
+ return $item;
+ }
+ }
+ else {
+ if ($item["id"] == $item_id)
+ return $item;
+ }
+
+ if ($item["type"] == "group" && !empty($item["children"])) {
+ $result = self::extractItemWithID($item["children"], $item_id, $item_type, $strictACL);
+
+ // Item found on children
+ if ($result !== false)
+ return $result;
+ }
+ }
+
+ // Item not found
+ return false;
+ }
+
+ protected function getDisplayHierarchy() {
+ return $this->filter['searchHirearchy'] ||
+ (empty($this->filter['searchAgent']) && empty($this->filter['searchModule']));
+ }
+
+}
+
+?>
+
diff --git a/pandora_console/include/class/TreeGroupEdition.class.php b/pandora_console/include/class/TreeGroupEdition.class.php
new file mode 100644
index 0000000000..dea62da238
--- /dev/null
+++ b/pandora_console/include/class/TreeGroupEdition.class.php
@@ -0,0 +1,108 @@
+id == -1) {
+ $this->getFirstLevel();
+ }
+ }
+
+ protected function getProcessedGroups () {
+ $processed_groups = array();
+ // Index and process the groups
+ $groups = $this->getGroupCounters();
+
+ // If user have not permissions in parent, set parent node to 0 (all)
+ // Avoid to do foreach for admins
+ if (!users_can_manage_group_all("AR")) {
+ foreach ($groups as $id => $group) {
+ if (!isset($this->userGroups[$groups[$id]['parent']])) {
+ $groups[$id]['parent'] = 0;
+ }
+ }
+ }
+ // Build the group hierarchy
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) {
+ $parent = $groups[$id]['parent'];
+ // Parent exists
+ if (!isset($groups[$parent]['children'])) {
+ $groups[$parent]['children'] = array();
+ }
+ // Store a reference to the group into the parent
+ $groups[$parent]['children'][] = &$groups[$id];
+ // This group was introduced into a parent
+ $groups[$id]['have_parent'] = true;
+ }
+ }
+
+ // Sort the children groups
+ foreach ($groups as $id => $group) {
+ if (isset($groups[$id]['children'])) {
+ usort($groups[$id]['children'], array("Tree", "cmpSortNames"));
+ }
+ }
+ //Filter groups and eliminates the reference to children groups out of her parent
+ $groups = array_filter($groups, function ($group) {
+ return !$group['have_parent'];
+ });
+
+ usort($groups, array("Tree", "cmpSortNames"));
+ return $groups;
+ }
+
+
+ protected function getGroupCounters() {
+ $messages = array(
+ 'confirm' => __('Confirm'),
+ 'cancel' => __('Cancel'),
+ 'messg' => __('Are you sure?')
+ );
+ $sql = "SELECT id_grupo AS gid,
+ nombre as name, parent, icon
+ FROM tgrupo
+ ";
+
+ $stats = db_get_all_rows_sql($sql);
+ $group_stats = array();
+ foreach ($stats as $group) {
+ $group_stats[$group['gid']]['name'] = $group['name'];
+ $group_stats[$group['gid']]['parent'] = $group['parent'];
+ $group_stats[$group['gid']]['icon'] = $group['icon'];
+ $group_stats[$group['gid']]['id'] = $group['gid'];
+ $group_stats[$group['gid']]['type'] = 'group';
+
+ $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]);
+ $group_stats[$group['gid']]['delete']['messages'] = $messages;
+ $group_stats[$group['gid']]['edit'] = 1;
+ $group_stats[$group['gid']]['alerts'] = '';
+ }
+
+ return $group_stats;
+ }
+}
+
+?>
+
diff --git a/pandora_console/include/class/TreeModule.class.php b/pandora_console/include/class/TreeModule.class.php
new file mode 100644
index 0000000000..45f9259854
--- /dev/null
+++ b/pandora_console/include/class/TreeModule.class.php
@@ -0,0 +1,60 @@
+L1fieldName = 'name';
+ $this->L1fieldNameSql = 'tam.nombre';
+ $this->L1inner = '';
+ $this->L1orderByFinal = 'name';
+
+ $this->L2condition = "AND tam.nombre = '" . $this->symbol2name($this->rootID) . "'";
+ }
+
+ protected function getData() {
+ if ($this->id == -1) {
+ $this->getFirstLevel();
+ } elseif ($this->type == 'module') {
+ $this->getSecondLevel();
+ } elseif ($this->type == 'agent') {
+ $this->getThirdLevel();
+ }
+ }
+
+ protected function getProcessedItemsFirstLevel($items){
+ $processed_items = array();
+ foreach ($items as $key => $item) {
+ $name = $this->name2symbol($item['name']);
+ $processed_item = $this->getProcessedItem($item);
+ $processed_item['id'] = $name;
+ $processed_item['rootID'] = $name;
+ $processed_items[] = $processed_item;
+ }
+ return $processed_items;
+ }
+}
+
+?>
+
diff --git a/pandora_console/include/class/TreeModuleGroup.class.php b/pandora_console/include/class/TreeModuleGroup.class.php
new file mode 100644
index 0000000000..06bc8fb6ff
--- /dev/null
+++ b/pandora_console/include/class/TreeModuleGroup.class.php
@@ -0,0 +1,49 @@
+L1fieldName = 'id_module_group';
+ $this->L1fieldNameSql = 'tam.id_module_group';
+ $this->L1extraFields = array('tmg.name', 'tmg.id_mg AS id');
+ $this->L1inner = 'INNER JOIN tmodule_group tmg ON tmg.id_mg = x2.g';
+ $this->L1orderByFinal = 'tmg.name';
+
+ $this->L2condition = "AND tam.id_module_group = " . $this->rootID;
+ }
+
+ protected function getData() {
+ if ($this->id == -1) {
+ $this->getFirstLevel();
+ } elseif ($this->type == 'module_group') {
+ $this->getSecondLevel();
+ } elseif ($this->type == 'agent') {
+ $this->getThirdLevel();
+ }
+ }
+}
+
+?>
+
diff --git a/pandora_console/include/class/TreeOS.class.php b/pandora_console/include/class/TreeOS.class.php
new file mode 100644
index 0000000000..8d7724f209
--- /dev/null
+++ b/pandora_console/include/class/TreeOS.class.php
@@ -0,0 +1,49 @@
+L1fieldName = 'id_os';
+ $this->L1fieldNameSql = 'ta.id_os';
+ $this->L1extraFields = array('tco.name', 'tco.id_os AS id', 'tco.icon_name AS iconHTML');
+ $this->L1inner = 'INNER JOIN tconfig_os tco ON tco.id_os = x2.g';
+ $this->L1orderByFinal = 'tco.name';
+
+ $this->L2condition = "AND ta.id_os = " . $this->rootID;
+ }
+
+ protected function getData() {
+ if ($this->id == -1) {
+ $this->getFirstLevel();
+ } elseif ($this->type == 'os') {
+ $this->getSecondLevel();
+ } elseif ($this->type == 'agent') {
+ $this->getThirdLevel();
+ }
+ }
+}
+
+?>
+
diff --git a/pandora_console/include/class/TreeTag.class.php b/pandora_console/include/class/TreeTag.class.php
new file mode 100644
index 0000000000..c6562db725
--- /dev/null
+++ b/pandora_console/include/class/TreeTag.class.php
@@ -0,0 +1,54 @@
+L1fieldName = 'id_tag';
+ $this->L1fieldNameSql = 'ttm.id_tag';
+ $this->L1innerInside = '
+ INNER JOIN ttag_module ttm
+ ON ttm.id_agente_modulo = tam.id_agente_modulo
+ ';
+ $this->L1extraFields = array('tt.name', 'tt.id_tag AS id');
+ $this->L1inner = 'INNER JOIN ttag tt ON tt.id_tag = x2.g';
+ $this->L1orderByFinal = 'tt.name';
+
+ $this->L2condition = "AND ttm.id_tag = " . $this->rootID;
+ $this->L2inner = $this->L1innerInside;
+ }
+
+ protected function getData() {
+ if ($this->id == -1) {
+ $this->getFirstLevel();
+ } elseif ($this->type == 'tag') {
+ $this->getSecondLevel();
+ } elseif ($this->type == 'agent') {
+ $this->getThirdLevel();
+ }
+ }
+}
+
+?>
+
diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php
index 4983a1b45c..100c12c8fd 100644
--- a/pandora_console/include/config_process.php
+++ b/pandora_console/include/config_process.php
@@ -22,8 +22,8 @@
/**
* Pandora build version and version
*/
-$build_version = 'PC180718';
-$pandora_version = 'v7.0NG.724';
+$build_version = 'PC181001';
+$pandora_version = 'v7.0NG.727';
// Do not overwrite default timezone set if defined.
$script_tz = @date_default_timezone_get();
diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php
index 7af3256453..e2c5c742a3 100644
--- a/pandora_console/include/functions.php
+++ b/pandora_console/include/functions.php
@@ -1360,11 +1360,41 @@ function safe_sql_string($string) {
function is_metaconsole() {
global $config;
-
- if ($config['metaconsole'])
- return true;
- else
- return false;
+ return (bool) $config['metaconsole'];
+}
+
+/**
+ * @brief Check if there is management operations are allowed in current context
+ * (node // meta)
+ *
+ * @return bool
+ */
+function is_management_allowed() {
+ global $config;
+ return ( (is_metaconsole() && $config["centralized_management"])
+ || (!is_metaconsole() && !$config["centralized_management"]));
+}
+
+/**
+ * @brief Check if there is centralized management in metaconsole environment.
+ * Usefull to display some policy features on metaconsole.
+ *
+ * @return bool
+ */
+function is_central_policies() {
+ global $config;
+ return is_metaconsole() && $config["centralized_management"];
+}
+
+/**
+ * @brief Check if there is centralized management in node environment. Usefull
+ * to reduce the policy functionallity on nodes.
+ *
+ * @return bool
+ */
+function is_central_policies_on_node() {
+ global $config;
+ return (!is_metaconsole()) && $config["centralized_management"];
}
/**
@@ -2517,15 +2547,9 @@ function set_when_empty (&$var, $default) {
}
}
-function sort_by_column (&$array_ref, $column_parameter) {
- global $column;
-
- $column = $column_parameter;
-
+function sort_by_column (&$array_ref, $column) {
if (!empty($column)) {
- usort($array_ref, function ($a, $b) {
- global $column;
-
+ usort($array_ref, function ($a, $b) use ($column) {
return strcmp($a[$column], $b[$column]);
});
}
@@ -3250,7 +3274,7 @@ function generator_chart_to_pdf($type_graph_pdf, $params, $params_combined = fal
$img_url = $config["homeurl"] . "attachment/" . $img_file;
$width_img = 500;
- $height_img = (isset($config['graph_image_height'])) ? $config['graph_image_height'] : 350;
+ $height_img = (isset($config['graph_image_height'])) ? $config['graph_image_height'] : 280;
$params['height'] = $height_img;
@@ -3320,4 +3344,27 @@ function get_copyright_notice () {
return $stored_name;
}
+/**
+ * Generate a random code to prevent cross site request fogery attacks
+ *
+ * @return string Generated code
+ */
+function generate_csrf_code() {
+ // Start session to make this var permanent
+ session_start();
+ $_SESSION['csrf_code'] = md5(uniqid(mt_rand(), true));
+ session_write_close();
+ return $_SESSION['csrf_code'];
+}
+
+/**
+ * Validate the CSRF code
+ *
+ * @return bool True if code is valid
+ */
+function validate_csrf_code() {
+ $code = get_parameter('csrf_code');
+ return isset($code) && isset($_SESSION['csrf_code'])
+ && $_SESSION['csrf_code'] == $code;
+}
?>
diff --git a/pandora_console/include/functions_agents.php b/pandora_console/include/functions_agents.php
index 65e27936cd..426a5c2e6b 100644
--- a/pandora_console/include/functions_agents.php
+++ b/pandora_console/include/functions_agents.php
@@ -796,11 +796,22 @@ function agents_common_modules ($id_agent, $filter = false, $indexed = true, $ge
* @param boolean $childGroups The flag to get agents in the child group of group parent passed. By default false.
* @param boolean $serialized Only in metaconsole. Return the key as
. By default false.
* @param string $separator Only in metaconsole. Separator for the serialized data. By default |.
+ * @param bool $add_alert_bulk_op //TODO documentation
+ * @param bool $force_serialized. If the agent has not id_server (typically in node) put 0 as .
*
* @return array An array with all agents in the group or an empty array
*/
-function agents_get_group_agents ($id_group = 0, $search = false,
- $case = "lower", $noACL = false, $childGroups = false, $serialized = false, $separator = '|', $add_alert_bulk_op = false) {
+function agents_get_group_agents (
+ $id_group = 0,
+ $search = false,
+ $case = "lower",
+ $noACL = false,
+ $childGroups = false,
+ $serialized = false,
+ $separator = '|',
+ $add_alert_bulk_op = false,
+ $force_serialized = false
+) {
global $config;
@@ -831,11 +842,18 @@ function agents_get_group_agents ($id_group = 0, $search = false,
users_get_groups(false, "AR", true, false, (array)$id_group));
}
}
-
+
+ // Search for primary and secondary groups
if (!empty($id_group)) {
- $filter['id_grupo'] = $id_group;
+ $filter[] = '(' . db_format_array_where_clause_sql(
+ array(
+ 'id_group' => $id_group,
+ 'id_grupo' => $id_group
+ ),
+ 'OR'
+ ) . ')';
}
-
+
if ($search === true) {
//No added search. Show both disabled and non-disabled
}
@@ -897,7 +915,7 @@ function agents_get_group_agents ($id_group = 0, $search = false,
if (isset($search['status'])) {
switch ($search['status']) {
case AGENT_STATUS_NORMAL:
- $filter[] = "normal_count = total_count";
+ $filter[] = "(normal_count = total_count AND notinit_count <> total_count)";
break;
case AGENT_STATUS_WARNING:
$filter[] = "(critical_count = 0 AND warning_count > 0)";
@@ -948,25 +966,25 @@ function agents_get_group_agents ($id_group = 0, $search = false,
$filter['order'] = 'alias';
if (is_metaconsole()) {
- $table_name = 'tmetaconsole_agent';
-
+ $table_name = 'tmetaconsole_agent ta LEFT JOIN tmetaconsole_agent_secondary_group tasg ON ta.id_agente = tasg.id_agent';
+
$fields = array(
- 'id_tagente AS id_agente',
+ 'ta.id_tagente AS id_agente',
'alias',
- 'id_tmetaconsole_setup AS id_server'
+ 'ta.id_tmetaconsole_setup AS id_server'
);
}
else {
- $table_name = 'tagente';
-
+ $table_name = 'tagente LEFT JOIN tagent_secondary_group ON id_agente=id_agent';
+
$fields = array(
'id_agente',
'alias'
);
}
-
+
$result = db_get_all_rows_filter($table_name, $filter, $fields);
-
+
if ($result === false)
return array (); //Return an empty array
@@ -974,14 +992,14 @@ function agents_get_group_agents ($id_group = 0, $search = false,
foreach ($result as $row) {
if (!isset($row["id_agente"]) || !isset($row["alias"]))
continue;
-
if ($serialized && isset($row["id_server"])) {
$key = $row["id_server"] . $separator . $row["id_agente"];
- }
- else {
+ } elseif ($force_serialized) {
+ $key = "0" . $separator . $row["id_agente"];
+ } else {
$key = $row["id_agente"];
}
-
+
switch ($case) {
case "lower":
$value = mb_strtolower ($row["alias"], "UTF-8");
@@ -1727,7 +1745,8 @@ function agents_get_status($id_agent = 0, $noACLs = false) {
// Get all non disabled modules of the agent
$all_modules = db_get_all_rows_filter('tagente_modulo',
$filter_modules, 'id_agente_modulo');
-
+ if ($all_modules === false) $all_modules = array();
+
$result_modules = array();
// Skip non init modules
foreach ($all_modules as $module) {
@@ -2006,11 +2025,17 @@ function agents_get_agentmodule_group ($id_module) {
* This function gets the group for a given agent
*
* @param int The agent id
+ * @param bool True to use the metaconsole tables
*
* @return int The group id
*/
-function agents_get_agent_group ($id_agent) {
- return (int) db_get_value ('id_grupo', 'tagente', 'id_agente', (int) $id_agent);
+function agents_get_agent_group ($id_agent, $force_meta = false) {
+ return (int) db_get_value (
+ 'id_grupo',
+ $force_meta ? "tmetaconsole_agent" : "tagente",
+ 'id_agente',
+ (int) $id_agent
+ );
}
/**
@@ -2661,23 +2686,28 @@ function agents_generate_name ($alias, $address = '') {
*
* @param int $id_agent
* @param int $id_group. By default it will search for it in dtabase
+ * @param bool True to use the metaconsole tables
*
* @return Array with the main and secondary groups
*/
-function agents_get_all_groups_agent ($id_agent, $group = false) {
+function agents_get_all_groups_agent ($id_agent, $group = false, $force_meta = false) {
+ // Cache the agent id groups
+ static $cache = array();
+ if (isset($cache[$id_agent])) return $cache[$id_agent];
// Get the group if is not defined
- if ($group === false) $group = agents_get_agent_group($id_agent);
+ if ($group === false) $group = agents_get_agent_group($id_agent, $force_meta);
// If cannot retrieve the group, it means that agent does not exist
if (!$group) return array();
- $secondary_groups = enterprise_hook('agents_get_secondary_groups', array($id_agent));
+ $secondary_groups = enterprise_hook('agents_get_secondary_groups', array($id_agent, $force_meta));
// Return only an array with the group in open version
if ($secondary_groups == ENTERPRISE_NOT_HOOK) return array($group);
// Add a list of groups
$secondary_groups['plain'][] = $group;
+ $cache[$id_agent] = $secondary_groups['plain'];
return $secondary_groups['plain'];
}
@@ -2719,4 +2749,33 @@ function agents_check_access_agent ($id_agent, $access = "AR") {
// Return null otherwise
return null;
}
+
+function agents_get_status_clause($state, $show_not_init = true) {
+ switch ($state) {
+ case AGENT_STATUS_CRITICAL:
+ return "(ta.critical_count > 0)";
+ case AGENT_STATUS_WARNING:
+ return "(ta.warning_count > 0 AND ta.critical_count = 0)";
+ case AGENT_STATUS_UNKNOWN:
+ return "(
+ ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count > 0
+ )";
+ case AGENT_STATUS_NOT_INIT:
+ return $show_not_init
+ ? "(ta.total_count = ta.notinit_count)"
+ : "1=0";
+ case AGENT_STATUS_NORMAL:
+ return "(
+ ta.critical_count = 0 AND ta.warning_count = 0
+ AND ta.unknown_count = 0 AND ta.normal_count > 0
+ )";
+ case AGENT_STATUS_ALL:
+ default:
+ return $show_not_init
+ ? "1=1"
+ : "(ta.total_count <> ta.notinit_count)";
+ }
+ // If the state is not an expected state, return no condition
+ return "1=1";
+}
?>
diff --git a/pandora_console/include/functions_alerts.php b/pandora_console/include/functions_alerts.php
index 52f43783b5..52c0338eb4 100644
--- a/pandora_console/include/functions_alerts.php
+++ b/pandora_console/include/functions_alerts.php
@@ -50,7 +50,10 @@ function alerts_get_alerts($id_group = 0, $free_search = "", $status = "all", $s
$id_groups = array_keys($groups);
- $group_query = " AND t3.id_grupo IN (" . implode(',', $id_groups) . ") ";
+ $group_query = " AND (
+ t3.id_grupo IN (" . implode(',', $id_groups) . ")
+ OR tasg.id_group IN (" . implode(',', $id_groups) . ")
+ )";
}
else {
$group_query = "";
@@ -91,7 +94,8 @@ function alerts_get_alerts($id_group = 0, $free_search = "", $status = "all", $s
}
else {
$sql = 'SELECT *, t2.nombre AS module_name,
- t3.nombre AS agent_name, t1.name AS template_name,
+ t3.nombre AS agent_name, t3.alias AS agent_alias,
+ t1.name AS template_name,
t0.disabled AS alert_disabled ';
}
$sql .= '
@@ -102,6 +106,8 @@ function alerts_get_alerts($id_group = 0, $free_search = "", $status = "all", $s
ON t0.id_agent_module = t2.id_agente_modulo
INNER JOIN tagente t3
ON t2.id_agente = t3.id_agente
+ LEFT JOIN tagent_secondary_group tasg
+ ON tasg.id_agent = t3.id_agente
WHERE 1=1
' . $status_query . ' ' . $standby_query . ' ' . $group_query . '
AND (t1.name LIKE "%' . $free_search . '%"
@@ -1013,14 +1019,16 @@ function alerts_create_alert_agent_module ($id_agent_module, $id_alert_template,
* @return mixed Affected rows or false if something goes wrong.
*/
function alerts_update_alert_agent_module ($id_alert_agent_module, $values) {
- if (empty ($id_agent_module))
+
+ if (empty ($id_alert_agent_module))
return false;
+
if (! is_array ($values))
return false;
-
+
return (@db_process_sql_update ('talert_template_modules',
$values,
- array ('id' => $id_alert_template))) !== false;
+ array ('id' => $id_alert_agent_module))) !== false;
}
/**
@@ -1644,23 +1652,13 @@ function get_agent_alert_fired ($id_agent, $id_alert, $period, $date = 0) {
*
* @return array An array with all the events happened.
*/
-function get_module_alert_fired ($id_agent_module, $id_alert, $period, $date = 0) {
+function get_module_alert_fired ($id_agent_module, $id_alert) {
- if (!is_numeric ($date)) {
- $date = time_w_fixed_tz($date);
- }
- if (empty ($date)) {
- $date = get_system_time();
- }
-
- $datelimit = $date - $period;
-
- $sql = sprintf ('SELECT timestamp
+ $sql = sprintf ('SELECT *
FROM tevento
- WHERE id_agentmodule = %d AND utimestamp > %d
- AND utimestamp <= %d
+ WHERE id_agentmodule = %d
AND id_alert_am = %d
- ORDER BY timestamp DESC', $id_agent_module, $datelimit, $date, $id_alert);
+ ORDER BY timestamp DESC', $id_agent_module, $id_alert);
return db_get_all_rows_sql ($sql);
}
@@ -1803,9 +1801,12 @@ function get_group_alerts($id_group, $filter = '', $options = false,
FROM tagente_modulo
WHERE delete_pending = 0
AND id_agente IN (SELECT id_agente
- FROM tagente
+ FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
WHERE
- id_grupo IN (' . implode(',', $id_group) . '))';
+ id_grupo IN (' . implode(',', $id_group) . ')
+ OR id_group IN (' . implode(',', $id_group) . '))';
}
}
@@ -1872,6 +1873,8 @@ function get_group_alerts($id_group, $filter = '', $options = false,
ON talert_template_modules.id_agent_module = t2.id_agente_modulo
INNER JOIN tagente t3
ON t2.id_agente = t3.id_agente
+ LEFT JOIN tagent_secondary_group tasg
+ ON tasg.id_agent = t2.id_agente
INNER JOIN talert_templates t4
ON talert_template_modules.id_alert_template = t4.id
WHERE id_agent_module in (%s) %s %s %s",
diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php
index 8979b04b14..7bfe95d575 100644
--- a/pandora_console/include/functions_api.php
+++ b/pandora_console/include/functions_api.php
@@ -30,6 +30,7 @@ include_once($config['homedir'] . "/include/functions_network_components.php");
include_once($config['homedir'] . "/include/functions_netflow.php");
include_once($config['homedir'] . "/include/functions_servers.php");
include_once($config['homedir'] . "/include/functions_planned_downtimes.php");
+include_once($config['homedir'] . "/include/functions_db.php");
enterprise_include_once ('include/functions_local_components.php');
enterprise_include_once ('include/functions_events.php');
enterprise_include_once ('include/functions_agents.php');
@@ -99,78 +100,69 @@ function returnError($typeError, $returnType = 'string') {
break;
default:
returnData("string",
- array('type' => 'string', 'data' => __($returnType)));
+ array('type' => 'string', 'data' => __($typeError)));
break;
}
}
/**
- *
* @param $returnType
* @param $data
* @param $separator
- *
* @return
*/
function returnData($returnType, $data, $separator = ';') {
switch ($returnType) {
case 'string':
- if ($data['type'] == 'string') {
- echo $data['data'];
+ if( is_array($data['data']) ){
+ echo convert_array_multi($data['data'], $separator);
}
- else {
- //TODO
+ else{
+ echo $data['data'];
}
break;
case 'csv':
case 'csv_head':
- switch ($data['type']) {
- case 'array':
- if (array_key_exists('list_index', $data))
- {
- if ($returnType == 'csv_head') {
- foreach($data['list_index'] as $index) {
- echo $index;
- if (end($data['list_index']) == $index)
- echo "\n";
- else
- echo $separator;
- }
- }
- foreach($data['data'] as $dataContent) {
- foreach($data['list_index'] as $index) {
- if (array_key_exists($index, $dataContent))
- echo str_replace("\n", " ", $dataContent[$index]);
- if (end($data['list_index']) == $index)
- echo "\n";
- else
- echo $separator;
- }
+ if( is_array($data['data']) ){
+ if (array_key_exists('list_index', $data)) {
+ if ($returnType == 'csv_head') {
+ foreach($data['list_index'] as $index) {
+ echo $index;
+ if (end($data['list_index']) == $index)
+ echo "\n";
+ else
+ echo $separator;
}
}
- else {
- if (!empty($data['data'])) {
-
- foreach ($data['data'] as $dataContent) {
-
- $clean = array_map("array_apply_io_safe_output", $dataContent);
-
- foreach ($clean as $k => $v) {
- $clean[$k] = str_replace("\r", "\n", $clean[$k]);
- $clean[$k] = str_replace("\n", " ", $clean[$k]);
- $clean[$k] = strip_tags($clean[$k]);
- $clean[$k] = str_replace(';',' ',$clean[$k]);
- }
- $row = implode($separator, $clean);
-
- echo $row . "\n";
- }
+ foreach($data['data'] as $dataContent) {
+ foreach($data['list_index'] as $index) {
+ if (array_key_exists($index, $dataContent))
+ echo str_replace("\n", " ", $dataContent[$index]);
+ if (end($data['list_index']) == $index)
+ echo "\n";
+ else
+ echo $separator;
}
}
- break;
- case 'string':
- echo $data['data'];
- break;
+ }
+ else {
+ if (!empty($data['data'])) {
+ foreach ($data['data'] as $dataContent) {
+ $clean = array_map("array_apply_io_safe_output", $dataContent);
+ foreach ($clean as $k => $v) {
+ $clean[$k] = str_replace("\r", "\n", $clean[$k]);
+ $clean[$k] = str_replace("\n", " ", $clean[$k]);
+ $clean[$k] = strip_tags($clean[$k]);
+ $clean[$k] = str_replace(';',' ',$clean[$k]);
+ }
+ $row = implode($separator, $clean);
+ echo $row . "\n";
+ }
+ }
+ }
+ }
+ else{
+ echo $data['data'];
}
break;
case 'json':
@@ -180,13 +172,13 @@ function returnData($returnType, $data, $separator = ';') {
if ($separator == ";") {
$separator = null;
}
-
+
if(empty($separator)){
echo json_encode ($data);
} else {
echo json_encode ($data, $separator);
}
-
+
break;
}
}
@@ -1183,11 +1175,14 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) {
return;
}
}
+ $values_old = db_get_row_filter('tagente',
+ array('id_agente' => $id_agent),
+ array('id_grupo', 'disabled')
+ );
+ $tpolicy_group_old = db_get_all_rows_sql("SELECT id_policy FROM tpolicy_groups
+ WHERE id_group = ".$values_old['id_grupo']);
- $group_old = db_get_sql("SELECT id_grupo FROM tagente WHERE id_agente =" .$id_agent);
- $tpolicy_group_old = db_get_all_rows_sql("SELECT id_policy FROM tpolicy_groups
- WHERE id_group = ".$group_old);
-
+
$return = db_process_sql_update('tagente',
array('alias' => $alias,
'direccion' => $ip,
@@ -1208,8 +1203,16 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) {
// register ip for this agent in 'taddress'
agents_add_address ($id_agent, $ip);
}
-
+
if($return){
+ // Update config file
+ if (isset($disabled) && $values_old['disabled'] != $disabled) {
+ enterprise_hook(
+ 'config_agents_update_config_token',
+ array($id_agent, 'standby', $disabled)
+ );
+ }
+
if($tpolicy_group_old){
foreach ($tpolicy_group_old as $key => $value) {
$tpolicy_agents_old= db_get_sql("SELECT * FROM tpolicy_agents
@@ -1399,6 +1402,68 @@ function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) {
}
}
+
+function api_set_create_os($thrash1, $thrash2, $other, $thrash3) {
+ global $config;
+
+
+ if (!check_acl($config['id_user'], 0, "AW")) {
+ returnError('forbidden', 'string');
+ return;
+ }
+
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ $values = array();
+
+ $values['name'] = $other['data'][0];
+ $values['description'] = $other['data'][1];
+
+ if (($other['data'][2] !== 0) && ($other['data'][2] != '')) {
+ $values['icon_name'] = $other['data'][2];
+ }
+
+
+
+ $resultOrId = false;
+ if ($other['data'][0] != '') {
+ $resultOrId = db_process_sql_insert('tconfig_os', $values);
+ }
+
+}
+
+function api_set_update_os($id_os, $thrash2, $other, $thrash3) {
+ global $config;
+
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ if (!check_acl($config['id_user'], 0, "AW")) {
+ returnError('forbidden', 'string');
+ return;
+ }
+
+ $values = array();
+ $values['name'] = $other['data'][0];
+ $values['description'] = $other['data'][1];
+
+ if (($other['data'][2] !== 0) && ($other['data'][2] != '')) {
+ $values['icon_name'] = $other['data'][2];;
+ }
+ $result = false;
+
+
+ if ($other['data'][0] != '') {
+
+ $result = db_process_sql_update('tconfig_os', $values, array('id_os' => $id_os));
+ }
+
+}
+
+
/**
*
* Creates a custom field
@@ -5400,74 +5465,6 @@ function api_set_planned_downtimes_additem ($id, $thrash1, $other, $thrash3) {
}
}
-/**
- * Add agent to a policy. And return a message with the result of the operation.
- *
- * @param string $id Id of the target policy.
- * @param $thrash1 Don't use.
- * @param array $other it's array, $other as param is in this order
- * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_)
- * example:
- *
- * example:
- *
- * api.php?op=set&op2=add_agent_policy&id=1&other=167&other_mode=url_encode_separator_|
- *
- * @param $thrash3 Don't use
- */
-function api_set_add_agent_policy($id, $thrash1, $other, $thrash2) {
- if (defined ('METACONSOLE')) {
- return;
- }
-
- if ($id == "") {
- returnError('error_add_agent_policy', __('Error adding agent to policy. Id_policy cannot be left blank.'));
- return;
- }
-
- if ($other['data'][0] == "") {
- returnError('error_add_agent_policy', __('Error adding agent to policy. Id_agent cannot be left blank.'));
- return;
- }
-
- // Check if the agent exists and permissions
- if (!util_api_check_agent_and_print_error((int) $other['data'][0], 'string', "AW")) {
- return;
- }
-
- // Check the policy permissions and existence
- if (enterprise_hook('policies_check_user_policy', array($id)) === false) {
- $result_agent = db_get_value ('id_agente', 'tagente', 'id_agente', (int) $other['data'][0]);
- if ($result_agent) {
- returnError('error_add_agent_policy', __('Error adding agent to policy. Id policy doesn\'t exist.'));
- return;
- }
- returnError('forbidden', 'string');
- return;
- }
-
- // Check if the agent is already in the policy
- $id_agent_policy = enterprise_hook('policies_get_agents', array($id, array('id_agent' => $other['data'][0]), 'id'));
-
- if ($id_agent_policy === ENTERPRISE_NOT_HOOK) {
- returnError('error_add_agent_policy', __('Error adding agent to policy.'));
- return;
- }
-
- if ($id_agent_policy === false) {
- $success = enterprise_hook('policies_create_agent', array($other['data'][0], $id, true));
- }
- else {
- returnError('error_add_agent_policy', __('Error adding agent to policy. The agent is already in the policy.'));
- return;
- }
-
- if ($success)
- returnData('string', array('type' => 'string', 'data' => $success));
- else
- returnError('error_add_agent_policy', 'Error adding agent to policy.');
-}
-
/**
* Add data module to policy. And return id from new module.
*
@@ -6429,153 +6426,6 @@ function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3) {
array('type' => 'string', 'data' => __('SNMP policy module updated.')));
}
-
-/**
- * Apply policy. And return id from the applying operation.
- *
- * @param string $id Id of the target policy.
- * @param $thrash1 Don't use.
- * @param array $other Don't use
- * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_)
- * example:
- *
- * api.php?op=set&op2=apply_policy&id=1
- *
- * @param $thrash3 Don't use
- */
-function api_set_apply_policy($id, $thrash1, $other, $thrash3) {
- if (defined ('METACONSOLE')) {
- return;
- }
-
- if ($id == "") {
- returnError('error_apply_policy', __('Error applying policy. Id_policy cannot be left blank.'));
- return;
- }
-
- # Check if this operation is duplicated
- $duplicated = enterprise_hook('policies_get_policy_queue_status', array($id));
-
- if ($duplicated === ENTERPRISE_NOT_HOOK) {
- // We want to return a value
- if ($other == "return") {
- return -1;
- }
- else {
- returnError('error_apply_policy', __('Error applying policy.'));
- return;
- }
- }
-
- if ($duplicated == STATUS_IN_QUEUE_APPLYING or $duplicated == STATUS_IN_QUEUE_IN) {
- // We want to return a value
- if ($other == "return") {
- return -1;
- }
- else {
- returnError('error_apply_policy',
- __('Error applying policy. This policy is already pending to apply.'));
- return;
- }
- }
-
- $check_acl = enterprise_hook('policies_check_user_policy', array($id));
- if ($check_acl !== true) {
- // We want to return a value
- if ($other == "return") {
- return -1;
- }
- else {
- returnError('error_apply_policy', __('Error applying policy.'));
- return;
- }
- }
-
- $id = enterprise_hook('add_policy_queue_operation', array($id, 0, 'apply'));
-
- if ($id === ENTERPRISE_NOT_HOOK) {
- // We want to return a value
- if ($other == "return") {
- return -1;
- }
- else {
- returnError('error_apply_policy', __('Error applying policy.'));
- return;
- }
- }
-
- // We want to return a value
- if ($other == "return") {
- if ($id)
- return $id;
- else
- return -1;
- }
- else {
- if ($id)
- returnData('string', array('type' => 'string', 'data' => $id));
- else
- returnError('error_apply_policy', 'Error applying policy.');
- }
-}
-
-
-/**
- * Apply all policy in database. And return the number of policies applied.
- *
- * @param string $id Don't use.
- * @param $thrash1 Don't use.
- * @param array $other Don't use
- * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_)
- * example:
- *
- * api.php?op=set&op2=apply_all_policies
- *
- * @param $thrash3 Don't use
- */
-function api_set_apply_all_policies($thrash1, $thrash2, $other, $thrash3) {
- global $config;
- if (defined ('METACONSOLE')) {
- return;
- }
-
- if (!check_acl($config['id_user'], 0, "AW")) {
- returnError('forbidden', 'string');
- return;
- }
-
- $policies = array();
-
- # Get all policies
- $policies = enterprise_hook('policies_get_policies', array(false, false, false));
-
- if ($policies === ENTERPRISE_NOT_HOOK) {
- returnError('error_apply_all_policy', __('Error applying all policies.'));
- return;
- }
- if ($policies === false) $policies = array();
-
- $num_policies = count($policies);
- $count_results = 0;
- foreach ($policies as $policy) {
- $return_value = enterprise_hook('add_policy_queue_operation',
- array($policy['id'], 0, 'apply'));
-
- if ($return_value != -1) {
- $count_results++;
- }
- }
-
- if ($num_policies > $count_results) {
- $errors = $num_policies - $count_results;
-
- returnError('error_apply_policy', 'Error applying policy. ' . $errors . ' failed. ');
- }
- else {
- returnData('string', array('type' => 'string', 'data' => $count_results));
- }
-}
-
/**
* Create a new group. And return the id_group of the new group.
*
@@ -11621,8 +11471,282 @@ function util_api_check_agent_and_print_error($id_agent, $returnType, $access =
return false;
}
+function api_get_user_info($thrash1, $thrash2, $other, $returnType) {
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ $separator = ';';
+
+ $other = json_decode(base64_decode($other['data']),true);
+
+ $sql = 'select * from tusuario where id_user = "'.$other[0]['id_user'].'" and password = "'.$other[0]['password'].'"';
+
+ $user_info = db_get_all_rows_sql($sql);
+
+ if (count($user_info) > 0 and $user_info !== false) {
+ $data = array('type' => 'array', 'data' => $user_info);
+ returnData($returnType, $data, $separator);
+ }
+ else {
+ return 0;
+ }
+}
+/*
+
+This function receives different parameters to process one of these actions the logging process in our application from the records in the audit of pandora fms, to avoid concurrent access of administrator users, and optionally to prohibit access to non-administrator users:
+
+Parameter 0
+
+The User ID that attempts the action is used to check the status of the application for access.
+
+Parameter 1
+
+Login, logout, exclude, browse.
+
+These requests receive a response that we can treat as we consider, this function only sends answers, does not perform any action in your application, you must customize them.
+
+Login action: free (register our access), taken, denied (if you are not an administrator user and parameter four is set to 1, register the expulsion).
+
+Browse action: It has the same answers as login, but does not register anything in the audit.
+
+Logout action: It records the deslogeo but does not send a response.
+
+All other actions do not return a response,
+
+Parameter 2
+
+IP address of the application is also used to check the status of the application for access.
+
+Parameter 3
+
+Name of the application, it is also used to check the status of the application for access.
+
+Parameter 4
+
+If you mark 1 you will avoid the access to the non-administrators users, returning the response `denied' and registering that expulsion in the audit of pandora fms.
+
+*/
+
+
+
+function api_set_access_process($thrash1, $thrash2, $other, $returnType) {
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ $other['data'] = explode('|',$other['data']);
+
+ $sql = 'select id_usuario,utimestamp from tsesion where descripcion like "%'.$other['data'][2].'%" and accion like "%'.$other['data'][3].' Logon%" and id_usuario IN (select id_user from tusuario where is_admin = 1) and id_usuario != "'.$other['data'][0].'" order by utimestamp DESC limit 1';
+ $audit_concurrence = db_get_all_rows_sql($sql);
+ $sql_user = 'select id_usuario,utimestamp from tsesion where descripcion like "%'.$other['data'][2].'%" and accion like "%'.$other['data'][3].' Logon%" and id_usuario IN (select id_user from tusuario where is_admin = 1) and id_usuario = "'.$other['data'][0].'" order by utimestamp DESC limit 1';
+ $audit_concurrence_user = db_get_all_rows_sql($sql_user);
+ $sql2 = 'select id_usuario,utimestamp,accion from tsesion where descripcion like "%'.$other['data'][2].'%" and accion like "%'.$other['data'][3].' Logoff%" and id_usuario = "'.$audit_concurrence[0]['id_usuario'].'" order by utimestamp DESC limit 1';
+ $audit_concurrence_2 = db_get_all_rows_sql($sql2);
+
+ //The user trying to log in is an administrator
+ if(users_is_admin($other['data'][0])){
+ //The admin user is trying to login
+ if($other['data'][1] == 'login'){
+ // Check if there is an administrator user logged in prior to our last login
+ if($audit_concurrence[0]['utimestamp'] > $audit_concurrence_user[0]['utimestamp']){
+ // Check if the administrator user logged in later to us has unlogged and left the node free
+ if($audit_concurrence[0]['utimestamp'] > $audit_concurrence_2[0]['utimestamp']){
+ // The administrator user logged in later has not yet unlogged
+ returnData('string', array('type' => 'string', 'data' => 'taken'));
+ }
+ else{
+ // The administrator user logged in later has already unlogged
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+ }
+ }
+ else{
+ // There is no administrator user who has logged in since then to log us in.
+ db_pandora_audit($other['data'][3].' Logon', 'Logged in '.$other['data'][3].' node '.$other['data'][2] , $other['data'][0]);
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+ }
+
+ }
+ elseif ($other['data'][1] == 'logout') {
+ // The administrator user wants to log out
+ db_pandora_audit($other['data'][3].' Logoff', 'Logout from '.$other['data'][3].' node '.$other['data'][2], $other['data'][0]);
+ }
+ elseif ($other['data'][1] == 'exclude') {
+ // The administrator user has ejected another administrator user who was logged in
+ db_pandora_audit($other['data'][3].' Logon', 'Logged in '.$other['data'][3].' node '.$other['data'][2] , $other['data'][0]);
+ db_pandora_audit($other['data'][3].' Logoff', 'Logout from '.$other['data'][3].' node '.$other['data'][2] , $audit_concurrence[0]['id_usuario']);
+
+ }
+ //The admin user is trying to browse
+ elseif ($other['data'][1] == 'browse') {
+ // Check if there is an administrator user logged in prior to our last login
+ if($audit_concurrence[0]['utimestamp'] > $audit_concurrence_user[0]['utimestamp']){
+ // Check if the administrator user logged in later to us has unlogged and left the node free
+ if($audit_concurrence[0]['utimestamp'] > $audit_concurrence_2[0]['utimestamp']){
+ // The administrator user logged in later has not yet unlogged
+ returnData('string', array('type' => 'string', 'data' => $audit_concurrence[0]['id_usuario']));
+ }
+ else{
+ // The administrator user logged in later has already unlogged
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+ }
+ }
+ else{
+ // There is no administrator user who has logged in since then to log us in.
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+ }
+
+ }
+ elseif ($other['data'][1] == 'cancelled'){
+ //The administrator user tries to log in having another administrator logged in, but instead of expelling him he cancels his log in.
+ db_pandora_audit($other['data'][3].' cancelled access', 'Cancelled access in '.$other['data'][3].' node '.$other['data'][2] , $other['data'][0]);
+ returnData('string', array('type' => 'string', 'data' => 'cancelled'));
+ }
+
+}
+else{
+
+ if($other['data'][4] == 1){
+ //The user trying to log in is not an administrator and is not allowed no admin access
+ db_pandora_audit($other['data'][3].' denied access', 'Denied access to non-admin user '.$other['data'][3].' node '.$other['data'][2] , $other['data'][0]);
+ returnData('string', array('type' => 'string', 'data' => 'denied'));
+ }
+ else{
+ //The user trying to log in is not an administrator and is allowed no admin access
+ if($other['data'][1] == 'login'){
+ //The user trying to login is not admin, can enter without concurrent use filter
+ db_pandora_audit($other['data'][3].' Logon', 'Logged in '.$other['data'][3].' node '.$other['data'][2] , $other['data'][0]);
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+
+ }
+ elseif ($other['data'][1] == 'logout') {
+ //The user trying to logoff is not admin
+ db_pandora_audit($other['data'][3].' Logoff', 'Logout from '.$other['data'][3].' node '.$other['data'][2], $other['data'][0]);
+ }
+ elseif ($other['data'][1] == 'browse'){
+ //The user trying to browse in an app page is not admin, can enter without concurrent use filter
+ returnData('string', array('type' => 'string', 'data' => 'free'));
+ }
+ }
+ }
+}
+
+
+function api_get_traps($thrash1, $thrash2, $other, $returnType) {
+
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ $other['data'] = explode('|',$other['data']);
+
+ $other['data'][1] = date("Y-m-d H:i:s",$other['data'][1]);
+
+ $sql = 'SELECT * from ttrap where timestamp >= "'.$other['data'][1].'"';
+
+ // $sql = 'SELECT * from ttrap where source = "'.$other['data'][0].'" and timestamp >= "'.$other['data'][1].'"';
+
+ if($other['data'][4]){
+ $other['data'][4] = date("Y-m-d H:i:s",$other['data'][4]);
+ $sql .= ' and timestamp <= "'.$other['data'][4].'"';
+ }
+
+ if($other['data'][2]){
+ $sql .= ' limit '.$other['data'][2];
+ }
+
+ if($other['data'][3]){
+ $sql .= ' offset '.$other['data'][3];
+ }
+
+ if($other['data'][5]){
+ $sql .= ' and status = 0';
+ }
+
+ if(sizeof($other['data']) == 0){
+ $sql = 'SELECT * from ttrap';
+ }
+
+
+ $traps = db_get_all_rows_sql($sql);
+
+ if($other['data'][6]){
+
+ foreach ($traps as $key => $value) {
+
+ if(!strpos($value['oid_custom'],$other['data'][6]) && $other['data'][7] == 'false'){
+ unset($traps[$key]);
+ }
+
+ if(strpos($value['oid_custom'],$other['data'][6]) && $other['data'][7] == 'true'){
+ unset($traps[$key]);
+ }
+
+ }
+
+ }
+
+ $traps_json = json_encode($traps);
+
+ if (count($traps) > 0 and $traps !== false) {
+ returnData('string', array('type' => 'string', 'data' => $traps_json));
+ }
+ else {
+ return 0;
+ }
+
+}
+
+function api_set_validate_traps ($id, $thrash2, $other, $thrash3) {
+
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ if($id == 'all'){
+ $result = db_process_sql_update('ttrap',array('status' => 1));
+ }
+ else{
+ $result = db_process_sql_update('ttrap',
+ array('status' => 1), array('id_trap' => $id));
+ }
+
+ if (is_error($result)) {
+ // TODO: Improve the error returning more info
+ returnError('error_update_trap', __('Error in trap update.'));
+ }
+ else {
+ returnData('string',
+ array('type' => 'string',
+ 'data' => __('Validated traps.')));
+ }
+ }
+
+ function api_set_delete_traps ($id, $thrash2, $other, $thrash3) {
+
+ if (defined ('METACONSOLE')) {
+ return;
+ }
+
+ if($id == 'all'){
+ $result = db_process_sql ('delete from ttrap');
+ }
+ else{
+ $result = db_process_sql_delete('ttrap',array('id_trap' => $id));
+ }
+
+ if (is_error($result)) {
+ // TODO: Improve the error returning more info
+ returnError('error_delete_trap', __('Error in trap delete.'));
+ }
+ else {
+ returnData('string',
+ array('type' => 'string',
+ 'data' => __('Deleted traps.')));
+ }
+ }
?>
diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php
index 7e4fd076c4..ca94033ef7 100644
--- a/pandora_console/include/functions_config.php
+++ b/pandora_console/include/functions_config.php
@@ -631,7 +631,10 @@ function config_update_config () {
if (!config_update_value ('type_mode_graph', (int) get_parameter('type_mode_graph', 0)))
$error_update[] = __('Default soft graphs');
- if (!config_update_value ('graph_image_height', (int) get_parameter('graph_image_height', 0)))
+ if (!config_update_value ('zoom_graph', (int) get_parameter('zoom_graph', 1)))
+ $error_update[] = __('Default zoom graphs');
+
+ if (!config_update_value ('graph_image_height', (int) get_parameter('graph_image_height', 280)))
$error_update[] = __('Default height of the chart image');
if (!config_update_value ('classic_menu', (bool) get_parameter('classic_menu', false)))
@@ -664,10 +667,7 @@ function config_update_config () {
}
}
//--------------------------------------------------
-
-
-
-
+
//--------------------------------------------------
// CUSTOM INTERVAL VALUES
//--------------------------------------------------
@@ -1856,11 +1856,15 @@ function config_process_config () {
if (!isset($config['render_proc'])) {
config_update_value ('render_proc', 0);
}
-
+
if (!isset($config['graph_image_height'])) {
- config_update_value ('graph_image_height', 320);
+ config_update_value ('graph_image_height', 280);
}
-
+
+ if (!isset($config['zoom_graph'])) {
+ config_update_value ('zoom_graph', 1);
+ }
+
if (!isset($config["render_proc_ok"])) {
config_update_value ('render_proc_ok', __('Ok') );
}
diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php
index 1348afc96b..f6b6da21cc 100644
--- a/pandora_console/include/functions_events.php
+++ b/pandora_console/include/functions_events.php
@@ -50,6 +50,8 @@ function events_get_all_fields() {
$columns['ack_utimestamp'] = __('ACK Timestamp');
$columns['instructions'] = __('Instructions');
$columns['server_name'] = __('Server name');
+ $columns['data'] = __('Data');
+ $columns['module_status'] = __('Module status');
return $columns;
}
@@ -126,10 +128,10 @@ function events_get_events_no_grouped($sql_post, $offset = 0,
function events_get_events_grouped($sql_post, $offset = 0,
$pagination = 1, $meta = false, $history = false, $total = false,
- $history_db = false, $order = "DESC") {
-
- global $config;
+ $history_db = false, $order = "down", $sort_field = "timestamp") {
+ global $config;
+
$table = events_get_events_table($meta, $history);
if ($meta) {
@@ -139,12 +141,14 @@ function events_get_events_grouped($sql_post, $offset = 0,
$groupby_extra = '';
}
+
switch ($config["dbtype"]) {
case "mysql":
db_process_sql ('SET group_concat_max_len = 9999999');
+ $event_lj = events_get_secondary_groups_left_join($table);
if ($total) {
$sql = "SELECT COUNT(*) FROM (SELECT *
- FROM $table te LEFT JOIN tagent_secondary_group tasg ON te.id_grupo = tasg.id_group
+ FROM $table te $event_lj
WHERE 1=1 " . $sql_post . "
GROUP BY estado, evento, id_agente, id_agentmodule" . $groupby_extra . ") AS t";
}
@@ -158,11 +162,14 @@ function events_get_events_grouped($sql_post, $offset = 0,
(SELECT id_usuario FROM $table WHERE id_evento = MAX(te.id_evento)) id_usuario,
(SELECT id_agente FROM $table WHERE id_evento = MAX(te.id_evento)) id_agente,
(SELECT criticity FROM $table WHERE id_evento = MAX(te.id_evento)) AS criticity,
- (SELECT ack_utimestamp FROM $table WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp
- FROM $table te LEFT JOIN tagent_secondary_group tasg ON te.id_grupo = tasg.id_group
+ (SELECT ack_utimestamp FROM $table WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp,
+ (SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = te.id_agentmodule) AS module_name
+ FROM $table te $event_lj
WHERE 1=1 " . $sql_post . "
- GROUP BY estado, evento, id_agente, id_agentmodule" . $groupby_extra . "
- ORDER BY timestamp_rep " . $order . " LIMIT " . $offset . "," . $pagination;
+ GROUP BY estado, evento, id_agente, id_agentmodule" . $groupby_extra;
+ $sql .= " " . events_get_sql_order($sort_field, $order, 2);
+ $sql .= " LIMIT " . $offset . "," . $pagination;
+
}
break;
case "postgresql":
@@ -721,15 +728,15 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
unknown_instructions, source, tags, custom_data,
- server_id, id_extra)
+ server_id, id_extra, data, module_status)
VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()),
"%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s",
- "%s", "%s", %d, "%s")',
+ "%s", "%s", %d, "%s", %d, %d)',
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
$unknown_instructions, $source, $tags, $custom_data,
- $server_id, $id_extra);
+ $server_id, $id_extra, $data, $module_status);
break;
case "postgresql":
$sql = sprintf ('
@@ -738,16 +745,16 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
unknown_instructions, source, tags, custom_data,
- server_id, id_extra)
+ server_id, id_extra, data, module_status)
VALUES (%d, %d, "%s", NOW(), %d,
ceil(date_part(\'epoch\', CURRENT_TIMESTAMP)), "%s",
"%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s",
- "%s", %d, "%s")',
+ "%s", %d, "%s", %d, %d)',
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
$unknown_instructions, $source, $tags, $custom_data,
- $server_id, $id_extra);
+ $server_id, $id_extra, $data, $module_status);
break;
case "oracle":
$sql = sprintf ('
@@ -756,15 +763,15 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
unknown_instructions, source, tags, custom_data,
- server_id, id_extra)
+ server_id, id_extra, data, module_status)
VALUES (%d, %d, "%s", CURRENT_TIMESTAMP, %d, UNIX_TIMESTAMP,
"%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s",
- "%s", "%s", %d, "%s")',
+ "%s", "%s", %d, "%s", %d, %d)',
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
$unknown_instructions, $source, $tags, $custom_data,
- $server_id, $id_extra);
+ $server_id, $id_extra, $data, $module_status);
break;
}
}
@@ -776,13 +783,13 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
timestamp, estado, utimestamp, id_usuario,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
- unknown_instructions, source, tags, custom_data, id_extra)
+ unknown_instructions, source, tags, custom_data, id_extra, data, module_status)
VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()),
- "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s")',
+ "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)',
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
- $unknown_instructions, $source, $tags, $custom_data, $id_extra);
+ $unknown_instructions, $source, $tags, $custom_data, $id_extra, $data, $module_status);
break;
case "postgresql":
$sql = sprintf ('
@@ -790,14 +797,14 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
timestamp, estado, utimestamp, id_usuario,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
- unknown_instructions, source, tags, custom_data, id_extra)
+ unknown_instructions, source, tags, custom_data, id_extra, data, module_status)
VALUES (%d, %d, "%s", NOW(), %d,
ceil(date_part(\'epoch\', CURRENT_TIMESTAMP)), "%s",
- "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s")',
+ "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)',
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
- $unknown_instructions, $source, $tags, $custom_data, $id_extra);
+ $unknown_instructions, $source, $tags, $custom_data, $id_extra, $data, $module_status);
break;
case "oracle":
$sql = sprintf ("
@@ -805,13 +812,13 @@ function events_create_event ($event, $id_group, $id_agent, $status = 0,
timestamp, estado, utimestamp, id_usuario,
event_type, criticity, id_agentmodule, id_alert_am,
critical_instructions, warning_instructions,
- unknown_instructions, source, tags, custom_data, id_extra)
+ unknown_instructions, source, tags, custom_data, id_extra, data, module_status)
VALUES (%d, %d, '%s', CURRENT_TIMESTAMP, %d, UNIX_TIMESTAMP,
- '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
+ '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
$id_agent, $id_group, $event, $status, $id_user,
$event_type, $priority, $id_agent_module, $id_aam,
$critical_instructions, $warning_instructions,
- $unknown_instructions, $source, $tags, $custom_data, $id_extra);
+ $unknown_instructions, $source, $tags, $custom_data, $id_extra, $data, $module_status);
break;
}
}
@@ -1522,7 +1529,31 @@ function events_get_all_status ($report = false) {
}
return $fields;
-}
+}
+
+/**
+ * Return all event source.
+ *
+ * @return array event source array.
+ */
+function events_get_all_source () {
+ $event_table = events_get_events_table(is_metaconsole(),false);
+ $fields = array ();
+ $fields[''] = __('All');
+
+ if (users_is_admin()) {
+ $sources = db_get_all_rows_sql("SELECT DISTINCT(source) FROM ". $event_table);
+ } else {
+ $groups_user = users_get_groups ($config['id_user'], "ER", true);
+ $sources = db_get_all_rows_sql("SELECT DISTINCT(source) FROM ". $event_table. " WHERE id_grupo IN (" .implode(",",array_keys($groups_user)) .")");
+ }
+
+ foreach ($sources as $key => $source) {
+ $fields[$source['source']] = $source['source'];
+ }
+
+ return $fields;
+}
/**
* Decode a numeric status into status description.
@@ -3317,13 +3348,13 @@ function events_get_events_grouped_by_agent($sql_post, $offset = 0,
$fields_extra = '';
}
+ $event_lj = events_get_secondary_groups_left_join($table);
if ($total) {
- $sql = "SELECT COUNT(*) FROM (select id_agente from $table WHERE 1=1
+ $sql = "SELECT COUNT(*) FROM (select id_agente from $table $event_lj WHERE 1=1
$sql_post GROUP BY id_agente, event_type$groupby_extra ORDER BY id_agente ) AS t";
}
else {
- $sql = "select id_agente, count(*) as total$fields_extra from $table te LEFT JOIN tagent_secondary_group tasg
- ON te.id_grupo = tasg.id_group
+ $sql = "select id_agente, count(*) as total$fields_extra from $table te $event_lj
WHERE id_agente > 0 $sql_post GROUP BY id_agente$groupby_extra ORDER BY id_agente LIMIT $offset,$pagination";
}
@@ -3337,7 +3368,7 @@ function events_get_events_grouped_by_agent($sql_post, $offset = 0,
foreach ($events as $event) {
if ($meta) {
- $sql = "select event_type from $table
+ $sql = "select event_type from $table te $event_lj
WHERE agent_name = '".$event['agent_name']."' $sql_post ORDER BY utimestamp DESC ";
$resultado = db_get_row_sql($sql);
@@ -3348,9 +3379,7 @@ function events_get_events_grouped_by_agent($sql_post, $offset = 0,
'event_type' => $resultado['event_type']);
}
else {
- $sql = "SELECT event_type FROM $table te
- LEFT JOIN tagent_secondary_group tasg
- ON te.id_agente = tasg.id_agent
+ $sql = "SELECT event_type FROM $table te $event_lj
WHERE id_agente = ".$event['id_agente']." $sql_post ORDER BY utimestamp DESC ";
$resultado = db_get_row_sql($sql);
@@ -3703,6 +3732,16 @@ function events_list_events_grouped_agents($sql) {
$table->align[$i] = 'left';
$i++;
}
+ if (in_array('data', $show_fields)) {
+ $table->head[$i] = __('Data');
+ $table->align[$i] = 'left';
+ $i++;
+ }
+ if (in_array('module_status', $show_fields)) {
+ $table->head[$i] = __('Module status');
+ $table->align[$i] = 'left';
+ $i++;
+ }
if ($i != 0 && $allow_action) {
$table->head[$i] = __('Action');
$table->align[$i] = 'left';
@@ -4102,6 +4141,20 @@ function events_list_events_grouped_agents($sql) {
$table->cellclass[count($table->data)][$i] = $myclass;
$i++;
}
+ if (in_array('data',$show_fields)) {
+ $data[$i] = $event["data"];
+ if($data[$i] %1 == 0)
+ $data[$i]= number_format($data[$i], 0);
+ else
+ $data[$i]= number_format($data[$i], 2);
+ $table->cellclass[count($table->data)][$i] = $myclass;
+ $i++;
+ }
+ if (in_array('module_status',$show_fields)) {
+ $data[$i] = modules_get_modules_status ($event["module_status"]);
+ $table->cellclass[count($table->data)][$i] = $myclass;
+ $i++;
+ }
if ($i != 0 && $allow_action) {
//Actions
@@ -4169,7 +4222,62 @@ function events_list_events_grouped_agents($sql) {
return html_print_table($table,true);
}
+function events_get_sql_order($sort_field = "timestamp", $sort = "DESC", $group_rep = 0) {
+ $sort_field_translated = $sort_field;
+ switch ($sort_field) {
+ case 'event_id':
+ $sort_field_translated = "id_evento";
+ break;
+ case 'event_name':
+ $sort_field_translated = "evento";
+ break;
+ case 'status':
+ $sort_field_translated = "estado";
+ break;
+ case 'agent_id':
+ $sort_field_translated = "id_agente";
+ break;
+ case 'timestamp':
+ $sort_field_translated = ($group_rep == 0) ? "timestamp" : "timestamp_rep";
+ break;
+ case 'user_id':
+ $sort_field_translated = "id_usuario";
+ break;
+ case 'owner':
+ $sort_field_translated = "owner_user";
+ break;
+ case 'group_id':
+ $sort_field_translated = "id_grupo";
+ break;
+ case 'alert_id':
+ $sort_field_translated = "id_alert_am";
+ break;
+ case 'comment':
+ $sort_field_translated = "user_comment";
+ break;
+ case 'extra_id':
+ $sort_field_translated = "id_extra";
+ break;
+ }
+ $dir = ($sort == "up") ? "ASC" : "DESC";
+ return "ORDER BY $sort_field_translated $dir";
+}
+
+/**
+ * SQL left join of event queries to handle secondary groups
+ *
+ * @param string Table to see if is metaconsole or not
+ *
+ * @return string With the query.
+ */
+function events_get_secondary_groups_left_join($table) {
+ if ($table == 'tevento') {
+ return "LEFT JOIN tagent_secondary_group tasg ON te.id_agente = tasg.id_agent";
+ }
+ return "LEFT JOIN tmetaconsole_agent_secondary_group tasg
+ ON te.id_agente = tasg.id_tagente AND te.server_id = tasg.id_tmetaconsole_setup";
+}
?>
diff --git a/pandora_console/include/functions_forecast.php b/pandora_console/include/functions_forecast.php
index f58e3592e7..fb09624081 100644
--- a/pandora_console/include/functions_forecast.php
+++ b/pandora_console/include/functions_forecast.php
@@ -20,31 +20,29 @@
*/
/**
- * Create a prediction based on module data with least square method (linear regression)
+ * Create a prediction based on module data with least square method (linear regression)
*
* @param int Module id.
* @param int Period of the module data.
- * @param int Period of the prediction or false to use it in prediction_date function (see below).
+ * @param int Period of the prediction or false to use it in prediction_date function (see below).
* @param int Maximun value using this function for prediction_date.
* @param int Minimun value using this function for prediction_date.
* @param bool Result data for CSV file exportation.
- *
+ *
* @return array Void array or prediction of the module data.
*/
function forecast_projection_graph($module_id,
$period = SECONDS_2MONTHS, $prediction_period, $max_value = false,
$min_value = false, $csv = false) {
-
+
global $config;
-
- $max_exec_time = ini_get('max_execution_time');
-
+
+ $max_exec_time = ini_get('max_execution_time');
+
if ($max_exec_time !== false) {
-
- $max_exec_time = (int)$max_exec_time;
-
+ $max_exec_time = (int)$max_exec_time;
}
-
+
$begin_time = time();
$params =array(
@@ -54,16 +52,16 @@ function forecast_projection_graph($module_id,
'projection' => true
);
- $module_data = grafico_modulo_sparse ($params);
-
+ $module_data = grafico_modulo_sparse($params);
+
if (empty($module_data)) {
- return array();
+ return array();
}
- // Prevents bad behaviour over image error
+ // Prevents bad behaviour over image error
else if (!is_array($module_data) and preg_match('/^= -1.0 and $linear_coef <= -0.8999
// Function variables have an inverse linear relathionship!
- // else
- // Function variables don't have an inverse linear relathionship!
-
+ // else
+ // Function variables don't have an inverse linear relathionship!
// Could be a direct correlation coefficient
- // else
+ // else
// if ($linear_coef >= 0.8999 and $linear_coef <= 1.0) {
// Function variables have a direct linear relathionship!
- // else
+ // else
// Function variables don't have a direct linear relathionship!
-
// 2. Calculation of linear regresion...
-
+
$b_num = (($cont * $sum_xi_yi) - ($sum_xi * $sum_yi));
$b_den = (($cont * $sum_xi2) - ($sum_xi * $sum_xi));
if ($b_den == 0)
return;
$b = $b_num / $b_den;
-
+
$a_num = ($sum_yi) - ($b * $sum_xi);
-
+
if ($cont != 0) {
$a = $a_num / $cont;
} else {
$a = 0;
}
-
+
// Data inicialization
$output_data = array();
if ($prediction_period != false) {
@@ -188,11 +165,11 @@ function forecast_projection_graph($module_id,
$current_ts = $last_timestamp;
$in_range = true;
$time_format_2 = '';
-
+
$temp_range = $period;
if ($period < $prediction_period)
$temp_range = $prediction_period;
-
+
if ($temp_range <= SECONDS_6HOURS) {
$time_format = 'H:i:s';
}
@@ -206,15 +183,15 @@ function forecast_projection_graph($module_id,
elseif ($temp_range <= SECONDS_1MONTH) {
$time_format = 'M d';
$time_format_2 = 'H\h';
- }
+ }
else {
$time_format = 'M d';
}
-
- // Aplying linear regression to module data in order to do the prediction
- $output_data = array();
+
+ // Aplying linear regression to module data in order to do the prediction
$idx = 0;
// Create data in graph format like
+
while ($in_range) {
$now = time();
@@ -242,9 +219,10 @@ function forecast_projection_graph($module_id,
if ($current_ts - $last_timestamp >= 94608000) {
return false;
}
-
+
// Found it
- if ($max_value >= $output_data[$idx][0] and $min_value <= $output_data[$idx][0]) {
+ if (($max_value >= $output_data[$idx][0]) &&
+ ($min_value <= $output_data[$idx][0]) ) {
return $current_ts;
}
}
@@ -254,7 +232,6 @@ function forecast_projection_graph($module_id,
$current_ts = $current_ts + $agent_interval;
$idx++;
}
-
return $output_data;
}
@@ -264,8 +241,8 @@ function forecast_projection_graph($module_id,
* @param int Module id.
* @param int Given data period to make the prediction
* @param int Max value in the interval.
- * @param int Min value in the interval.
- *
+ * @param int Min value in the interval.
+ *
* @return mixed timestamp with the prediction date or false
*/
function forecast_prediction_date ($module_id,
@@ -274,6 +251,5 @@ function forecast_prediction_date ($module_id,
if ($min_value > $max_value) {
return false;
}
-
return forecast_projection_graph($module_id, $period, false, $max_value, $min_value);
}
diff --git a/pandora_console/include/functions_gis.php b/pandora_console/include/functions_gis.php
index d37a4a433e..66f1dd8989 100644
--- a/pandora_console/include/functions_gis.php
+++ b/pandora_console/include/functions_gis.php
@@ -172,6 +172,10 @@ function gis_make_layer($name, $visible = true, $dot = null, $idLayer = null, $p
}
$visible = (bool)$visible;
+
+ $ajax_url = $public_console
+ ? ui_get_full_url('operation/gis_maps/ajax.php', false, false, false, false)
+ : ui_get_full_url('ajax.php', false, false, false, false);
?>
';
-
- $count ++;
- }
-
- return $returnVar;
-}
-
function gis_calculate_distance($lat_start, $lon_start, $lat_end, $lon_end) {
//Use 3958.9=miles, 6371.0=Km;
$earthRadius = 6371;
diff --git a/pandora_console/include/functions_graph.php b/pandora_console/include/functions_graph.php
index cbee30c35f..ff15c53525 100644
--- a/pandora_console/include/functions_graph.php
+++ b/pandora_console/include/functions_graph.php
@@ -264,9 +264,7 @@ function grafico_modulo_sparse_data_chart (
$data_module_graph['id_module_type'] == 18 ||
$data_module_graph['id_module_type'] == 9 ||
$data_module_graph['id_module_type'] == 31 ||
- $data_module_graph['id_module_type'] == 100 ||
- $params['baseline'] || $params['projection']
- ){
+ $data_module_graph['id_module_type'] == 100 ){
$data = db_get_all_rows_filter (
'tagente_datos',
@@ -421,8 +419,7 @@ function grafico_modulo_sparse_data(
$data_module_graph['id_module_type'] == 18 ||
$data_module_graph['id_module_type'] == 9 ||
$data_module_graph['id_module_type'] == 31 ||
- $data_module_graph['id_module_type'] == 100 ||
- $params['projection'] ){
+ $data_module_graph['id_module_type'] == 100 ){
$array_data = grafico_modulo_sparse_data_chart (
$agent_module_id,
$date_array,
@@ -516,6 +513,8 @@ function grafico_modulo_sparse_data(
}
$period_time_interval = $period_time_interval - $params['time_interval'];
}
+ //drag the last value to paint the graph correctly
+ $acum_array_data[]= array( 0 => $start_period, 1 => $acum_array_data[$i-1][1]);
$array_data['sum1']['data'] = $acum_array_data;
}
@@ -892,7 +891,9 @@ function grafico_modulo_sparse ($params) {
}
if(!isset($params['zoom'])){
- $params['zoom'] = 1;
+ $params['zoom'] = $config['zoom_graph']
+ ? $config['zoom_graph']
+ : 1;
}
if(!isset($params['type_mode_graph'])){
@@ -922,7 +923,6 @@ function grafico_modulo_sparse ($params) {
$legend = array();
$array_events_alerts = array();
-
$date_array = array();
$date_array["period"] = $params['period'];
$date_array["final_date"] = $params['date'];
@@ -964,53 +964,58 @@ function grafico_modulo_sparse ($params) {
}
if(!$params['array_data_create']){
- if ($params['compare'] !== false) {
- $series_suffix = 2;
+ if($params['baseline']){
+ $array_data = get_baseline_data($agent_module_id, $date_array, $data_module_graph, $params);
+ }
+ else{
+ if ($params['compare'] !== false) {
+ $series_suffix = 2;
- $date_array_prev['final_date'] = $date_array['start_date'];
- $date_array_prev['start_date'] = $date_array['start_date'] - $date_array['period'];
- $date_array_prev['period'] = $date_array['period'];
+ $date_array_prev['final_date'] = $date_array['start_date'];
+ $date_array_prev['start_date'] = $date_array['start_date'] - $date_array['period'];
+ $date_array_prev['period'] = $date_array['period'];
- if ($params['compare'] === 'overlapped') {
- $params['flag_overlapped'] = 1;
- }
- else{
- $params['flag_overlapped'] = 0;
+ if ($params['compare'] === 'overlapped') {
+ $params['flag_overlapped'] = 1;
+ }
+ else{
+ $params['flag_overlapped'] = 0;
+ }
+
+ $array_data = grafico_modulo_sparse_data(
+ $agent_module_id,
+ $date_array_prev,
+ $data_module_graph,
+ $params,
+ $series_suffix
+ );
+
+ switch ($params['compare']) {
+ case 'separated':
+ case 'overlapped':
+ // Store the chart calculated
+ $array_data_prev = $array_data;
+ $legend_prev = $legend;
+ break;
+ }
}
+ $series_suffix = 1;
+ $params['flag_overlapped'] = 0;
+
$array_data = grafico_modulo_sparse_data(
$agent_module_id,
- $date_array_prev,
+ $date_array,
$data_module_graph,
$params,
$series_suffix
);
- switch ($params['compare']) {
- case 'separated':
- case 'overlapped':
- // Store the chart calculated
- $array_data_prev = $array_data;
- $legend_prev = $legend;
- break;
- }
- }
-
- $series_suffix = 1;
- $params['flag_overlapped'] = 0;
-
- $array_data = grafico_modulo_sparse_data(
- $agent_module_id,
- $date_array,
- $data_module_graph,
- $params,
- $series_suffix
- );
-
- if($params['compare']){
- if ($params['compare'] === 'overlapped') {
- $array_data = array_merge($array_data, $array_data_prev);
- $legend = array_merge($legend, $legend_prev);
+ if($params['compare']){
+ if ($params['compare'] === 'overlapped') {
+ $array_data = array_merge($array_data, $array_data_prev);
+ $legend = array_merge($legend, $legend_prev);
+ }
}
}
}
@@ -1219,7 +1224,7 @@ function graphic_combined_module (
}
else{
$params['stacked'] = 'area';
- $params['projection'] = $params_combined['projection'];
+ $params['projection'] = true;
}
if(!isset($params_combined['labels'])){
@@ -1501,7 +1506,6 @@ function graphic_combined_module (
//XXX arreglar estas
$long_index = '';
-
switch ($params_combined['stacked']) {
default:
case CUSTOM_GRAPH_STACKED_LINE:
@@ -1513,6 +1517,14 @@ function graphic_combined_module (
$date_array["final_date"] = $params['date'];
$date_array["start_date"] = $params['date'] - $params['period'];
+ if($params_combined['projection']){
+ $output_projection = forecast_projection_graph(
+ $module_list[0],
+ $params['period'],
+ $params_combined['projection']
+ );
+ }
+
$i=0;
$array_data = array();
foreach ($module_list as $key => $agent_module_id) {
@@ -1579,10 +1591,13 @@ function graphic_combined_module (
$i++;
}
- if($params_combined['projection'] && is_array($params_combined['projection'])){
- $date_array_projection = max($params_combined['projection']);
- $date_array['final_date'] = $date_array_projection[0] / 1000;
- $array_data['projection']['data']= $params_combined['projection'];
+ if($params_combined['projection']){
+ // If projection doesn't have data then don't draw graph
+ if ($output_projection != NULL) {
+ $date_array_projection = max($output_projection);
+ $date_array['final_date'] = $date_array_projection[0] / 1000;
+ $array_data['projection']['data']= $output_projection;
+ }
}
//summatory and average series
@@ -1705,14 +1720,16 @@ function graphic_combined_module (
if ($do_it_warning_min && $do_it_warning_max && $do_it_warning_inverse) {
$yellow_threshold = $compare_warning;
- $threshold_data['yellow_up'] = $yellow_up;
- $threshold_data['yellow_inverse'] = (bool)$yellow_inverse;
+ $threshold_data['yellow_threshold'] = $compare_warning;
+ $threshold_data['yellow_up'] = $yellow_up;
+ $threshold_data['yellow_inverse'] = (bool)$yellow_inverse;
}
if ($do_it_critical_min && $do_it_critical_max && $do_it_critical_inverse) {
$red_threshold = $compare_critical;
- $threshold_data['red_up'] = $red_up;
- $threshold_data['red_inverse'] = (bool)$red_inverse;
+ $threshold_data['red_threshold'] = $compare_critical;
+ $threshold_data['red_up'] = $red_up;
+ $threshold_data['red_inverse'] = (bool)$red_inverse;
}
$params['threshold_data'] = $threshold_data;
@@ -1734,6 +1751,8 @@ function graphic_combined_module (
break;
case CUSTOM_GRAPH_BULLET_CHART_THRESHOLD:
case CUSTOM_GRAPH_BULLET_CHART:
+ $number_elements = count($module_list);
+
if($params_combined['stacked'] == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD){
$acumulador = 0;
foreach ($module_list as $module_item) {
@@ -1823,8 +1842,13 @@ function graphic_combined_module (
$graph_values = $temp;
- $width = 1024;
- $height = 50;
+ if(!$params['vconsole']){
+ $width = 1024;
+ $height = 50;
+ }
+ else{
+ $height = $height/$number_elements;
+ }
$color = color_graph_array();
@@ -1851,6 +1875,7 @@ function graphic_combined_module (
case CUSTOM_GRAPH_GAUGE:
$i = 0;
+ $number_elements = count($module_list);
foreach ($module_list as $module_item) {
$automatic_custom_graph_meta = false;
if ($config['metaconsole']) {
@@ -1918,8 +1943,14 @@ function graphic_combined_module (
$color = color_graph_array();
- $width = 200;
- $height = 200;
+ if(!$params['vconsole']){
+ $width = 200;
+ $height = 200;
+ }
+ else{
+ $width = $width/$number_elements;
+ $height = $height/$number_elements;
+ }
$output = stacked_gauge(
$graph_values,
@@ -1988,8 +2019,11 @@ function graphic_combined_module (
$graph_values = $temp;
- $width = 1024;
- $height = 500;
+ if(!$params['vconsole']){
+ $width = 1024;
+ $height = 500;
+ }
+
$flash_charts = true;
if($params_combined['stacked'] == CUSTOM_GRAPH_HBARS){
@@ -2102,8 +2136,11 @@ function graphic_combined_module (
$graph_values = $temp;
- $width = 1024;
- $height = 500;
+
+ if(!$params['vconsole']){
+ $width = 1024;
+ $height = 500;
+ }
$color = color_graph_array();
@@ -2999,7 +3036,7 @@ function grafico_incidente_prioridad () {
}
return pie3d_graph($config['flash_charts'], $data, 320, 200,
- __('Other'), '', $water_mark,
+ __('Other'), '', '',
$config['fontpath'], $config['font_size']);
}
@@ -3040,7 +3077,7 @@ function graph_incidents_status () {
}
return pie3d_graph($config['flash_charts'], $data, 320, 200,
- __('Other'), '', $water_mark,
+ __('Other'), '', '',
$config['fontpath'], $config['font_size']);
}
@@ -3096,7 +3133,7 @@ function graphic_incident_group () {
}
return pie3d_graph($config['flash_charts'], $data, 320, 200,
- __('Other'), '', $water_mark,
+ __('Other'), '', '',
$config['fontpath'], $config['font_size']);
}
@@ -3151,7 +3188,7 @@ function graphic_incident_user () {
}
return pie3d_graph($config['flash_charts'], $data, 320, 200,
- __('Other'), '', $water_mark,
+ __('Other'), '', '',
$config['fontpath'], $config['font_size']);
}
@@ -3205,7 +3242,7 @@ function graphic_incident_source($width = 320, $height = 200) {
}
return pie3d_graph($config['flash_charts'], $data, $width, $height,
- __('Other'), '', $water_mark,
+ __('Other'), '', '',
$config['fontpath'], $config['font_size']);
}
@@ -4094,7 +4131,7 @@ function fullscale_data (
if($min_value != PHP_INT_MAX) {
$data["min" . $series_suffix]['data'][] = array($real_date , $min_value);
}
-
+
if($max_value != -PHP_INT_MAX) {
$data["max" . $series_suffix]['data'][] = array($real_date , $max_value);
}
@@ -4120,7 +4157,7 @@ function fullscale_data (
$min_value_total = $min_value;
}
//avg sum_total
- $sum_data_total += $sum_data;
+ $sum_data_total += $sum_data/$count_data;
//avg count_total
$count_data_total++;
@@ -4168,6 +4205,7 @@ function fullscale_data (
}
}
}
+
$data["sum" . $series_suffix]['min'] = $min_value_total;
$data["sum" . $series_suffix]['max'] = $max_value_total;
$data["sum" . $series_suffix]['avg'] = $sum_data_total/$count_data_total;
@@ -4232,12 +4270,12 @@ function fullscale_data (
if(isset($v["datos"]) && $v["datos"]){
//max
- if($v['datos'] >= $max_value){
- $max_value = $v['datos'];
+ if((float)$v['datos'] >= $max_value_max){
+ $max_value_max = $v['datos'];
}
//min
- if($v['datos'] <= $min_value){
- $min_value = $v['datos'];
+ if((float)$v['datos'] <= $min_value_min){
+ $min_value_min = $v['datos'];
}
//avg sum
$sum_data += $v["datos"];
@@ -4253,8 +4291,8 @@ function fullscale_data (
}
}
- $data["sum" . $series_suffix]['min'] = $min_value;
- $data["sum" . $series_suffix]['max'] = $max_value;
+ $data["sum" . $series_suffix]['min'] = $min_value_min;
+ $data["sum" . $series_suffix]['max'] = $max_value_max;
$data["sum" . $series_suffix]['avg'] = $sum_data/$count_data;
}
@@ -5075,4 +5113,53 @@ function graph_monitor_wheel ($width = 550, $height = 600, $filter = false) {
return d3_sunburst_graph ($graph_data, $width, $height, true);
}
+function get_baseline_data($agent_module_id, $date_array, $data_module_graph, $params){
+ $period = $date_array["period"];
+ $date = $date_array["final_date"];
+ $array_data = array();
+ for ($i = 0; $i < 4; $i++) {
+ $date_array = array();
+ $date_array["period"] = $period;
+ $date_array["final_date"] = $date - $period * $i;
+ $date_array["start_date"] = $date - $period * ($i + 1);
+
+ $data = grafico_modulo_sparse_data(
+ $agent_module_id,
+ $date_array,
+ $data_module_graph,
+ $params,
+ $i
+ );
+
+ $array_data[] = $data;
+
+ }
+ $result = array();
+ $array_data[1] = array_reverse($array_data[1]['sum1']['slice_data']);
+ $array_data[2] = array_reverse($array_data[2]['sum2']['slice_data']);
+ $array_data[3] = array_reverse($array_data[3]['sum3']['slice_data']);
+ foreach ($array_data[0]['sum0']['slice_data'] as $key => $value) {
+ $data1 = array_pop($array_data[1]);
+ $data2 = array_pop($array_data[2]);
+ $data3 = array_pop($array_data[3]);
+
+ $result['slice_data'][$key]['min'] = ($data1['min'] + $data2['min'] + $data3['min'] + $value['min']) / 4;
+ $result['slice_data'][$key]['avg'] = ($data1['avg'] + $data2['avg'] + $data3['avg'] + $value['avg']) / 4;
+ $result['slice_data'][$key]['max'] = ($data1['max'] + $data2['max'] + $data3['max'] + $value['max']) / 4;
+
+ $result['data'][] = array($key, $result['slice_data'][$key]['avg']);
+ }
+
+ $result['avg'] = ($array_data[0]['sum0']['avg'] + $array_data[1]['sum1']['avg'] + $array_data[2]['sum2']['avg'] +$array_data[3]['sum3']['avg'])/4;
+ $result['max'] = max($array_data[0]['sum0']['max'], $array_data[1]['sum1']['max'], $array_data[2]['sum2']['max'], $array_data[3]['sum3']['max']);
+ $result['min'] = min($array_data[0]['sum0']['min'], $array_data[1]['sum1']['min'], $array_data[2]['sum2']['min'], $array_data[3]['sum3']['min']);
+
+ $result['agent_module_id'] = $array_data[0]['sum0']['agent_module_id'];
+ $result['id_module_type'] = $array_data[0]['sum0']['id_module_type'];
+ $result['agent_name'] = $array_data[0]['sum0']['agent_name'];
+ $result['module_name'] = $array_data[0]['sum0']['module_name'];
+ $result['agent_alias'] = $array_data[0]['sum0']['agent_alias'];
+ return array('sum0' => $result);
+}
+
?>
diff --git a/pandora_console/include/functions_groups.php b/pandora_console/include/functions_groups.php
index b22bbad3ce..2ce647c324 100644
--- a/pandora_console/include/functions_groups.php
+++ b/pandora_console/include/functions_groups.php
@@ -270,22 +270,20 @@ function groups_get_childrens($parent, $groups = null, $onlyPropagate = false) {
if (empty($groups)) {
$groups = db_get_all_rows_in_table('tgrupo');
}
-
+
$return = array();
-
+
foreach ($groups as $key => $group) {
if ($group['id_grupo'] == 0) {
continue;
}
-
if ($group['propagate'] || $onlyPropagate) {
if ($group['parent'] == $parent) {
$return = $return + array($group['id_grupo'] => $group) + groups_get_childrens($group['id_grupo'], $groups, $onlyPropagate);
}
}
-
}
-
+
return $return;
}
@@ -300,23 +298,20 @@ function groups_get_parents($parent, $onlyPropagate = false, $groups = null) {
if (empty($groups)) {
$groups = db_get_all_rows_in_table('tgrupo');
}
-
+
$return = array();
-
foreach ($groups as $key => $group) {
if ($group['id_grupo'] == 0) {
continue;
}
-
+
if (($group['id_grupo'] == $parent)
&& ($group['propagate'] || !$onlyPropagate)) {
-
$return = $return +
array($group['id_grupo'] => $group) +
groups_get_parents($group['parent'], $onlyPropagate, $groups);
}
}
-
return $return;
}
@@ -373,32 +368,6 @@ function groups_give_disabled_group ($id_group) {
return (bool) db_get_value ('disabled', 'tgrupo', 'id_grupo', (int) $id_group);
}
-/**
- * Test if the param array is all groups in db.
- *
- * @param array $id_groups
- *
- * @return bool It's true when the array is all groups in db.
- */
-function groups_is_all_group($idGroups) {
- if (!is_array($idGroups))
- $arrayGroups = array($idGroups);
- else
- $arrayGroups = $idGroups;
-
- $groupsDB = db_get_all_rows_in_table ('tgrupo');
-
- $returnVar = true;
- foreach ($groupsDB as $group) {
- if (!in_array($group['id_grupo'], $arrayGroups)) {
- $returnVar = false;
- break;
- }
- }
-
- return $returnVar;
-}
-
/**
* Get group icon from group.
*
@@ -632,7 +601,7 @@ function groups_get_id ($group_name, $returnAllGroup = false) {
*
* @param int $id_group The group id to look for
* @param mixed filter array
- * @param bool True if users with all permissions in the group are retrieved
+ * @param bool True if users with all permissions in the group are retrieved
*
* @return array An array with all the users or an empty array
*/
@@ -641,7 +610,7 @@ function groups_get_users ($id_group, $filter = false, $return_user_all = false)
if (! is_array ($filter))
$filter = array ();
-
+
if($return_user_all){
if (is_array($id_group)){
$filter['id_grupo'] = $id_group;
@@ -655,18 +624,18 @@ function groups_get_users ($id_group, $filter = false, $return_user_all = false)
$filter['id_grupo'] = $id_group;
}
- $query = "SELECT tu.*
- FROM tusuario tu, tusuario_perfil tup
- WHERE tup.id_usuario = tu.id_user" ;
+ $query = "SELECT tu.*
+ FROM tusuario tu, tusuario_perfil tup
+ WHERE tup.id_usuario = tu.id_user" ;
if(is_array($filter)){
foreach ($filter as $key => $value) {
if($key != 'limit' && $key != 'order' &&
- $key != 'offset' &&$key != 'group'){
+ $key != 'offset' &&$key != 'group'){
$filter_array["tup.".$key] = $value;
}
else{
- $filter_array[$key] = $value;
+ $filter_array[$key] = $value;
}
}
$clause_sql = mysql_db_format_array_where_clause_sql($filter_array,'AND',false);
@@ -674,451 +643,16 @@ function groups_get_users ($id_group, $filter = false, $return_user_all = false)
$query .= " AND " . $clause_sql;
}
}
-
+
$result = db_get_all_rows_sql($query);
if ($result === false){
return array ();
}
-
+
return $result;
}
-/**
- * Returning data for a row in the groups view (Recursive function)
- *
- * @param int $id_group The group id of the row
- * @param array $group_all An array of all groups
- * @param array $group arrayy The group name and childs
- * @param array $printed_groups The printed groups list (by reference)
- *
- */
-function groups_get_group_row_data($id_group, $group_all, $group, &$printed_groups) {
- global $config;
-
- $rows = array();
- $row = array();
-
- if (isset($printed_groups[$id_group])) {
- return;
- }
-
- // Store printed group to not print it again
- $printed_groups[$id_group] = 1;
-
- if ($id_group < 0)
- return;
-
- // Get stats for this group
- $data = reporting_get_group_stats($id_group);
-
- if ($data["total_agents"] == 0)
- return; // Skip empty groups
-
- // Calculate entire row color
- if ($data["monitor_alerts_fired"] > 0) {
- $row["status"] = "group_view_alrm";
- }
- elseif ($data["monitor_critical"] > 0) {
- $row["status"] = "group_view_crit";
- }
- elseif ($data["monitor_warning"] > 0) {
- $row["status"] = "group_view_warn";
- }
- elseif (($data["monitor_unknown"] > 0) || ($data["agents_unknown"] > 0)) {
- $row["status"] = "group_view_unk";
- }
- elseif ($data["monitor_ok"] > 0) {
- $row["status"] = "group_view_ok";
- }
- else {
- $row["status"] = "group_view_normal";
- }
-
- // Group name
- $group_cell = __('Group');
- $row[$group_cell] = $group['prefix'];
- $row[$group_cell] .= "";
- $row[$group_cell] .= ui_print_group_icon ($id_group, true, "groups_small", '', false);
- $row[$group_cell] .= ui_print_truncate_text($group['name']);
- $row[$group_cell] .= "";
-
- $row['group_name'] = ui_print_truncate_text($group['name']);
-
- if ($id_group > 0)
- $icon = (string) db_get_value ('icon', 'tgrupo', 'id_grupo', (int) $id_group);
- else
- $icon = "world";
-
- $row['group_icon'] = html_print_image("images/groups_small/" . $icon . ".png",
- true, false, true);
-
- if (!isset($html)) {
- $html = false;
- }
-
- //Update network group
- if ($html) {
- echo "";
- if (check_acl ($config['id_user'], $id_group, "AW")) {
- echo '' .
- html_print_image("images/target.png", true, array("border" => '0', "alt" => __('Force'))) . '';
- }
- echo " | ";
- }
-
- // Total agents
- if ($id_group != 0) {
- $data["total_agents"] = db_get_sql ("SELECT COUNT(id_agente)
- FROM tagente
- WHERE id_grupo = $id_group AND disabled = 0");
- }
-
- // Total agents
- $row['links'][__('Agents')] = "index.php?" .
- "page=agents&group=" . $id_group;
- $row['counts'][__('Agents')] = $data["total_agents"];
-
- $row[__('Agents')] = "";
- $row[__('Agents')] .= $row['counts'][__('Agents')];
- $row[__('Agents')] .= "";
-
-
- // Agents unknown
- $row['links'][__('Agents unknown')] = "index.php?" .
- "page=agents&group=" . $id_group . "&status=" . AGENT_STATUS_UNKNOWN;
- $row['counts'][__('Agents unknown')] = $data["agents_unknown"];
-
- $row[__('Agents unknown')] = "";
- $row[__('Agents unknown')] .= $row['counts'][__('Agents unknown')];
- $row[__('Agents unknown')] .= "";
-
- // Monitors Unknown
- $row['links'][__('Unknown')] = "index.php?" .
- "page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_UNKNOWN;
- $row['counts'][__('Unknown')] = $data["monitor_unknown"];
-
- $row[__('Unknown')] = "";
- $row[__('Unknown')] .= $row['counts'][__('Unknown')];
- $row[__('Unknown')] .= "";
-
- // Monitors Not Init
- $row['links'][__('Not init')] = "index.php?" .
- "page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_NOT_INIT;
- $row['counts'][__('Not init')] = $data["monitor_unknown"];
-
- $row[__('Not init')] = "";
- $row[__('Not init')] .= $row['counts'][__('Not init')];
- $row[__('Not init')] .= "";
-
- // Monitors OK
- $row['links'][__('Normal')] = "index.php?" .
- "page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_NORMAL;
- $row['counts'][__('Normal')] = $data["monitor_ok"];
-
- $row[__('Normal')] = "";
- $row[__('Normal')] .= $row['counts'][__('Normal')];
- $row[__('Normal')] .= "";
-
- // Monitors Warning
- $row['links'][__('Warning')] = "index.php?" .
- "page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_WARNING;
- $row['counts'][__('Warning')] = $data["monitor_warning"];
-
- $row[__('Warning')] = "";
- $row[__('Warning')] .= $row['counts'][__('Normal')];
- $row[__('Warning')] .= "";
-
- // Monitors Critical
- $row['links'][__('Critical')] = "index.php?" .
- "page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_CRITICAL_BAD;
- $row['counts'][__('Critical')] = $data["monitor_critical"];
-
- $row[__('Critical')] = "";
- $row[__('Critical')] .= $row['counts'][__('Critical')];
- $row[__('Critical')] .= "";
-
- // Alerts fired
- $row['links'][__('Alerts fired')] = "index.php?" .
- "page=alerts&group=" . $id_group . "&status=fired";
- $row['counts'][__('Alerts fired')] = $data["monitor_alerts_fired"];
-
- $row[__('Alerts fired')] = "";
- $row[__('Alerts fired')] .= $row['counts'][__('Alerts fired')];
- $row[__('Alerts fired')] .= "";
-
- $rows[$id_group] = $row;
-
- foreach($group['childs'] as $child) {
- $sub_rows = groups_get_group_row_data($child, $group_all,
- $group_all[$child], $printed_groups);
-
- if (!$html) {
- if (!empty($sub_rows))
- $rows = $rows + $sub_rows;
- }
- }
-
- return $rows;
-}
-
-function groups_get_groups_with_agent($id_user = false, $privilege = "AR", $returnAllGroup = true, $returnAllColumns = false, $id_groups = null, $keys_field = 'id_grupo') {
- $groups = users_get_groups($id_user, $privilege, $returnAllGroup, $returnAllColumns, $id_groups, $keys_field);
-
- $return = array();
- foreach ($groups as $group) {
- $data = reporting_get_group_stats($group['id_grupo']);
-
- if ($data["total_agents"] != 0) {
- $return[] = $group;
- }
- }
-
- return $return;
-}
-
-/**
- * Print a row in the groups view (Recursive function)
- *
- * @param int $id_group The group id of the row
- * @param array $group_all An array of all groups
- * @param array $group arrayy The group name and childs
- * @param array $printed_groups The printed groups list (by reference)
- *
- */
-function groups_get_group_row($id_group, $group_all, $group, &$printed_groups) {
- global $config;
-
- if ($id_group < 0)
- return;
-
- if (isset($printed_groups[$id_group])) {
- return;
- }
-
- // Store printed group to not print it again
- $printed_groups[$id_group] = 1;
-
- // Get stats for this group
- $data = reporting_get_group_stats($id_group);
-
-
- if ($data["total_agents"] == 0) {
- if (!empty($group['childs'])) {
- $group_childrens = groups_get_childrens($id_group, null, true);
- $group_childrens_agents = groups_total_agents(array_keys($group_childrens));
-
- if (empty($group_childrens_agents)) {
- return; // Skip empty groups
- }
- }
- else {
- return; // Skip empty groups
- }
- }
-
- // Calculate entire row color
- if ($data["monitor_alerts_fired"] > 0) {
- $group_class = 'group_view_alrm';
- $status_image = ui_print_status_image ('agent_alertsfired_ball.png', "", true);
- }
- elseif ($data["monitor_critical"] > 0) {
- $group_class = 'group_view_crit';
- $status_image = ui_print_status_image ('agent_critical_ball.png', "", true);
- }
- elseif ($data["monitor_warning"] > 0) {
- $group_class = 'group_view_warn';
- $status_image = ui_print_status_image ('agent_warning_ball.png', "", true);
- }
- elseif (($data["monitor_unknown"] > 0) || ($data["agents_unknown"] > 0)) {
- $group_class = 'group_view_unk';
- $status_image = ui_print_status_image ('agent_no_monitors_ball.png', "", true);
- }
- elseif ($data["monitor_ok"] > 0) {
- $group_class = 'group_view_ok';
- $status_image = ui_print_status_image ('agent_ok_ball.png', "", true);
- }
- elseif ($data["agent_not_init"] > 0) {
- $group_class = 'group_view_not_init';
- $status_image = ui_print_status_image ('agent_no_data_ball.png', "", true);
- }
- else {
- $group_class = 'group_view_normal';
- $status_image = ui_print_status_image ('agent_no_data_ball.png', "", true);
- }
-
- ob_start();
-
- echo "";
-
- // Force
- echo "";
- if (check_acl ($config['id_user'], $id_group, "AW")) {
- echo '' .
- html_print_image("images/target.png", true, array("border" => '0', "title" => __('Force'))) . '';
- }
- echo " | ";
-
- // Status
- // echo "" . $status_image . " | ";
-
- // Group name
- echo " ";
- //echo $group['prefix'] . ui_print_group_icon ($id_group, true, "groups_small", 'font-size: 7.5pt');
- echo " ";
- echo $group['prefix'] . ui_print_truncate_text($group['name']);
- echo "";
- echo " | ";
-
- // Total agents
- echo "";
- if ($data["total_agents"] > 0)
- echo "";
-
- //Total agent field given by function reporting_get_group_stats return the number of agents
- //of this groups and its children. It was done to print empty fathers of children groups.
- //We need to recalculate the total agents for this group here to get only the total agents
- //for this group. Of course the group All (0) is a special case.
-
- if ($id_group != 0) {
- $data["total_agents"] = db_get_sql ("SELECT COUNT(id_agente)
- FROM tagente
- WHERE id_grupo = $id_group AND disabled = 0");
- }
-
- echo $data["total_agents"];
- echo "";
-
- // Agents unknown
- if ($data["agents_unknown"] > 0) {
- echo " | ";
- echo "";
- echo $data["agents_unknown"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
- // Agents not init
- if ($data["agent_not_init"] > 0) {
- echo "";
- echo "";
- echo $data["agent_not_init"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
- // Monitors Unknown
- if ($data["monitor_unknown"] > 0) {
- echo "";
- echo "";
- echo $data["monitor_unknown"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
-
- // Monitors Not Init
- if ($data["monitor_not_init"] > 0) {
- echo "";
- echo "";
- echo $data["monitor_not_init"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
-
- // Monitors OK
- echo "";
- if ($data["monitor_ok"] > 0) {
- echo "";
- echo $data["monitor_ok"];
- echo "";
- }
- else {
- echo " ";
- }
- echo " | ";
-
- // Monitors Warning
- if ($data["monitor_warning"] > 0) {
- echo "";
- echo "";
- echo $data["monitor_warning"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
- // Monitors Critical
- if ($data["monitor_critical"] > 0) {
- echo "";
- echo "";
- echo $data["monitor_critical"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
- // Alerts fired
- if ($data["monitor_alerts_fired"] > 0) {
- echo "";
- echo "";
- echo $data["monitor_alerts_fired"];
- echo "";
- echo " | ";
- }
- else {
- echo " | ";
- }
-
- echo "
";
-
- $row[$id_group] = ob_get_clean();
-
-
- foreach ($group['childs'] as $child) {
- if (array_key_exists($child, $group_all)) {
- $row_child = groups_get_group_row($child, $group_all, $group_all[$child], $printed_groups);
-
- if (!is_array_empty($row_child)) {
- $row = $row + $row_child;
- }
- }
- }
-
- return $row;
-}
-
/**
* Gets a group by id_group
*
@@ -1206,19 +740,7 @@ function groups_get_agents_counter ($group, $agent_filter = array(), $module_fil
$groups_clause = "AND ta.id_grupo IN ($group_str)";
$tags_clause = "";
- if ($strict_user && !empty($groups_and_tags)) {
- foreach ($groups as $group_id) {
- if (isset($groups_and_tags[$group_id]) && !empty($groups_and_tags[$group_id])) {
- $tags_str = $groups_and_tags[$group_id];
- $tags_clause .= " AND (ta.grupo <> $group_id
- OR (ta.grupo = $group_id
- AND tam.id_agente_modulo NOT IN (SELECT id_agente_modulo
- FROM ttag_module
- WHERE id_tag NOT IN ($tags_str) )))";
- }
- }
- }
-
+
$agent_name_filter = "";
$agent_status = AGENT_STATUS_ALL;
if (!empty($agent_filter)) {
@@ -1662,22 +1184,10 @@ function groups_get_monitors_counter ($group, $agent_filter = array(), $module_f
}
$group_str = implode (",", $groups);
- $groups_clause = "AND ta.id_grupo IN ($group_str)";
+ $groups_clause = "AND (ta.id_grupo IN ($group_str) OR tasg.id_group IN ($group_str))";
$tags_clause = "";
- if ($strict_user && !empty($groups_and_tags)) {
- foreach ($groups as $group_id) {
- if (isset($groups_and_tags[$group_id]) && !empty($groups_and_tags[$group_id])) {
- $tags_str = $groups_and_tags[$group_id];
- $tags_clause .= " AND (ta.grupo <> $group_id
- OR (ta.grupo = $group_id
- AND tam.id_agente_modulo NOT IN (SELECT id_agente_modulo
- FROM ttag_module
- WHERE id_tag NOT IN ($tags_str) )))";
- }
- }
- }
-
+
$agent_name_filter = "";
$agents_clause = "";
if (!empty($agent_filter)) {
@@ -1775,36 +1285,38 @@ function groups_get_monitors_counter ($group, $agent_filter = array(), $module_f
$modules_clause
INNER JOIN tagente ta
ON tam.id_agente = ta.id_agente
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
AND ta.disabled = 0
$agent_name_filter
$agents_clause
- $groups_clause
WHERE tam.disabled = 0
$module_name_filter
+ $groups_clause
$tags_clause";
}
else {
$status_columns_array = array();
- foreach ($module_status_array as $status) {
+ foreach ($status_array as $status) {
switch ($status) {
case AGENT_MODULE_STATUS_CRITICAL_ALERT:
case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $status_columns_array[] = 'ta.critical_count';
+ $status_columns_array['critical'] = 'critical_count';
break;
case AGENT_MODULE_STATUS_WARNING_ALERT:
case AGENT_MODULE_STATUS_WARNING:
- $status_columns_array[] = 'ta.warning_count';
+ $status_columns_array['warn'] = 'warning_count';
break;
case AGENT_MODULE_STATUS_UNKNOWN:
- $status_columns_array[] = 'ta.unknown_count';
+ $status_columns_array['unk'] = 'unknown_count';
break;
case AGENT_MODULE_STATUS_NO_DATA:
case AGENT_MODULE_STATUS_NOT_INIT:
- $status_columns_array[] = 'ta.notinit_count';
+ $status_columns_array['notinit'] = 'notinit_count';
break;
case AGENT_MODULE_STATUS_NORMAL_ALERT:
case AGENT_MODULE_STATUS_NORMAL:
- $status_columns_array[] = 'ta.normal_count';
+ $status_columns_array['normal'] = 'normal_count';
break;
default:
// The type doesn't exist
@@ -1816,13 +1328,16 @@ function groups_get_monitors_counter ($group, $agent_filter = array(), $module_f
$status_columns_str = implode(",", $status_columns_array);
- $sql = "SELECT SUM($status_columns_str)
- FROM tagente ta
+ $sql = "SELECT SUM($status_columns_str) FROM
+ (SELECT DISTINCT(ta.id_agente), $status_columns_str
+ FROM tagente ta LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
WHERE ta.disabled = 0
$agent_name_filter
$agents_clause
$groups_clause
- $tags_clause";
+ $tags_clause
+ ) AS t1";
}
$count = (int) db_get_sql ($sql);
@@ -1975,251 +1490,159 @@ function groups_get_not_init_monitors ($group, $agent_filter = array(), $module_
}
// Get alerts defined for a given group, except disabled
-
-function groups_monitor_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
-
- // If there are not groups to query, we jump to nextone
-
- if (empty ($group_array)) {
- return 0;
-
- }
- else if (!is_array ($group_array)) {
- $group_array = array($group_array);
- }
-
- $group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- if ($strict_user) {
- $sql = "SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- WHERE tagente.id_grupo = $id_group_strict AND tagente_modulo.id_agente = tagente.id_agente
- AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
- AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
- AND talert_template_modules.disabled = 0
- AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo";
- $count = db_get_sql ($sql);
- return $count;
- } else {
- //TODO REVIEW ORACLE AND POSTGRES
- return db_get_sql ("SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- 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 tagente_modulo.disabled = 0 AND tagente.disabled = 0
- AND talert_template_modules.disabled = 0
- AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo");
- }
+function groups_monitor_alerts ($group_array) {
+ $total = groups_monitor_alerts_total_counters($group_array);
+ return $total['total'];
}
// Get alert configured currently FIRED, except disabled
+function groups_monitor_fired_alerts ($group_array) {
+ $total = groups_monitor_alerts_total_counters($group_array);
+ return $total['fired'];
+}
-function groups_monitor_fired_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
-
+function groups_monitor_alerts_total_counters ($group_array) {
// If there are not groups to query, we jump to nextone
-
+ $default_total = array('total' => 0, 'fired' => 0);
if (empty ($group_array)) {
- return 0;
-
+ return $default_total;
}
else if (!is_array ($group_array)) {
$group_array = array($group_array);
}
-
- $group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- if ($strict_user) {
- $sql = "SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- WHERE tagente.id_grupo = $id_group_strict AND tagente_modulo.id_agente = tagente.id_agente
- AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
- AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
- AND talert_template_modules.disabled = 0
- AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo
- AND times_fired > 0 ";
- $count = db_get_sql ($sql);
- return $count;
+ $group_clause = implode (",", $group_array);
+ $group_clause = "(tasg.id_group IN ($group_clause) OR ta.id_grupo IN ($group_clause))";
+
+ $alerts = db_get_row_sql ("SELECT
+ COUNT(tatm.id) AS total,
+ SUM(IF(tatm.times_fired > 0, 1, 0)) AS fired
+ FROM talert_template_modules tatm
+ INNER JOIN tagente_modulo tam
+ ON tatm.id_agent_module = tam.id_agente_modulo
+ INNER JOIN tagente ta
+ ON ta.id_agente = tam.id_agente
+ WHERE ta.id_agente IN (
+ SELECT ta.id_agente
+ FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE ta.disabled = 0
+ AND $group_clause
+ ) AND tam.disabled = 0"
+ );
+
+ return ($alerts === false) ? $default_total : $alerts;
+}
+
+function groups_monitor_total_counters ($group_array, $search_in_testado = false) {
+ $default_total = array(
+ 'ok' => 0, 'critical' => 0, 'warning' => 0,
+ 'unknown' => 0, 'not_init' => 0, 'total' => 0
+ );
+ if (empty ($group_array)) {
+ return $default_total;
+ }
+ else if (!is_array ($group_array)) {
+ $group_array = array($group_array);
+ }
+ $group_clause = implode (",", $group_array);
+ $group_clause = "(tasg.id_group IN ($group_clause) OR ta.id_grupo IN ($group_clause))";
+
+ if ($search_in_testado) {
+ $condition_critical = modules_get_state_condition(AGENT_MODULE_STATUS_CRITICAL_ALERT);
+ $condition_warning = modules_get_state_condition(AGENT_MODULE_STATUS_WARNING_ALERT);
+ $condition_unknown = modules_get_state_condition(AGENT_MODULE_STATUS_UNKNOWN);
+ $condition_not_init = modules_get_state_condition(AGENT_MODULE_STATUS_NO_DATA);
+ $condition_normal = modules_get_state_condition(AGENT_MODULE_STATUS_NORMAL);
+ $sql =
+ "SELECT SUM(IF($condition_normal, 1, 0)) AS ok,
+ SUM(IF($condition_critical, 1, 0)) AS critical,
+ SUM(IF($condition_warning, 1, 0)) AS warning,
+ SUM(IF($condition_unknown, 1, 0)) AS unknown,
+ SUM(IF($condition_not_init, 1, 0)) AS not_init,
+ COUNT(tam.id_agente_modulo) AS total
+ FROM tagente ta
+ INNER JOIN tagente_modulo tam
+ ON ta.id_agente = tam.id_agente
+ INNER JOIN tagente_estado tae
+ ON tam.id_agente_modulo = tae.id_agente_modulo
+ WHERE ta.disabled = 0 AND tam.disabled = 0
+ AND ta.id_agente IN (
+ SELECT ta.id_agente FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE ta.disabled = 0
+ AND $group_clause
+ GROUP BY ta.id_agente
+ )
+ ";
} else {
- //TODO REVIEW ORACLE AND POSTGRES
- return db_get_sql ("SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- 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 tagente_modulo.disabled = 0 AND tagente.disabled = 0
- AND talert_template_modules.disabled = 0
- AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo
- AND times_fired > 0");
+ $sql =
+ "SELECT SUM(ta.normal_count) AS ok,
+ SUM(ta.critical_count) AS critical,
+ SUM(ta.warning_count) AS warning,
+ SUM(ta.unknown_count) AS unknown,
+ SUM(ta.notinit_count) AS not_init,
+ SUM(ta.total_count) AS total
+ FROM tagente ta
+ WHERE ta.disabled = 0
+ AND ta.id_agente IN (
+ SELECT ta.id_agente FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE ta.disabled = 0
+ AND $group_clause
+ GROUP BY ta.id_agente
+ )
+ ";
}
-
+ $monitors = db_get_row_sql($sql);
+
+ return ($monitors === false) ? $default_total : $monitors;
}
-/**
- * Total agents in a group, (by default except disabled ones)
- *
- * @param mixed Array or (comma separated) string with groups
- * @param bool Whether to count disabled agents
- *
- * @return mixed Return group count or false if something goes wrong
- *
- */
-function groups_total_agents ($group_array, $disabled = false) {
-
+function groups_agents_total_counters ($group_array) {
+ $default_total = array(
+ 'ok' => 0, 'critical' => 0, 'warning' => 0,
+ 'unknown' => 0, 'not_init' => 0, 'total' => 0
+ );
if (empty ($group_array)) {
- return 0;
-
+ return $default_total;
}
else if (!is_array ($group_array)) {
$group_array = array($group_array);
}
-
$group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- $sql = "SELECT COUNT(*) FROM tagente WHERE id_grupo IN $group_clause";
-
- if (!$disabled)
- $sql .= " AND disabled = 0";
-
- return db_get_sql ($sql);
-}
+ $group_clause = "(tasg.id_group IN ($group_clause) OR ta.id_grupo IN ($group_clause))";
-/**
- * Number of disabled agents in a group
- *
- * @param mixed Array or (comma separated) string with groups
- *
- * @return mixed Return group count or false if something goes wrong
- *
- */
-function groups_agent_disabled ($group_array) {
-
- if (empty ($group_array)) {
- return 0;
-
- }
- else if (!is_array ($group_array)) {
- $group_array = array($group_array);
- }
-
- $group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- $sql = "SELECT COUNT(*) FROM tagente WHERE id_grupo IN $group_clause AND disabled = 1";
-
- return db_get_sql ($sql);
-}
+ $condition_critical = agents_get_status_clause(AGENT_STATUS_CRITICAL);
+ $condition_warning = agents_get_status_clause(AGENT_STATUS_WARNING);
+ $condition_unknown = agents_get_status_clause(AGENT_STATUS_UNKNOWN);
+ $condition_not_init = agents_get_status_clause(AGENT_STATUS_NOT_INIT);
+ $condition_normal = agents_get_status_clause(AGENT_STATUS_NORMAL);
+ $sql =
+ "SELECT SUM(IF($condition_normal, 1, 0)) AS ok,
+ SUM(IF($condition_critical, 1, 0)) AS critical,
+ SUM(IF($condition_warning, 1, 0)) AS warning,
+ SUM(IF($condition_unknown, 1, 0)) AS unknown,
+ SUM(IF($condition_not_init, 1, 0)) AS not_init,
+ COUNT(ta.id_agente) AS total
+ FROM tagente ta
+ WHERE ta.disabled = 0
+ AND ta.id_agente IN (
+ SELECT ta.id_agente FROM tagente ta
+ LEFT JOIN tagent_secondary_group tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE ta.disabled = 0
+ AND $group_clause
+ GROUP BY ta.id_agente
+ )
+ ";
-/**
- * Return a group row for Groups managment list
- *
- * @param mixed Group info
- * @param int total number of groups
- * @param string (ref) Concatenation of branches class with the parent classes
- *
- * @return mixed Row with html_print_table format
- *
- */
-function groups_get_group_to_list($group, $groups_count, &$symbolBranchs, $has_children = false) {
- $tabulation = str_repeat(' ', $group['deep']);
-
- if ($group['id_grupo'] == 0) {
- $symbol = '-';
- }
- else {
- $symbol = '+';
- }
-
- $group_hash_branch = false;
- if (isset($group['hash_branch'])) {
- $group_hash_branch = $group['hash_branch'];
- }
-
- if ($group_hash_branch) {
- $data[0] = ''.$tabulation . ' ' .
- '' .
- $symbol . ' '. ui_print_truncate_text($group['nombre']) . '';
- }
- else {
- $data[0] = '' . $tabulation . ' ' . ui_print_truncate_text($group['nombre']) . '';
- }
- $data[1] = $group['id_grupo'];
- $data[2] = ui_print_group_icon($group['id_grupo'], true);
- $data[3] = $group['disabled'] ? __('Disabled') : __('Enabled');
- $data[4] = $group['description'];
- if ($group['id_grupo'] == 0) {
- $data[5] = '';
- }
- else {
- $data[5] = '' . html_print_image("images/config.png", true, array("alt" => __('Edit'), "title" => __('Edit'), "border" => '0'));
- //Check if there is only a group to unable delete it
- if ($groups_count > 2) {
- $confirm_message = __('Are you sure?');
- if ($has_children) {
- $confirm_message = __('The child groups will be updated to use the parent id of the deleted group') . ". " . $confirm_message;
- }
+ $agents = db_get_row_sql($sql);
- $data[5] .= ' ' .
- '' . html_print_image("images/cross.png", true, array("alt" => __('Delete'), "border" => '0'));
- }
- else {
- $data[5] .= ' ' .
- ui_print_help_tip(
- __('You cannot delete the last group. A common installation must have at least one group.'), true);
- }
- }
-
- return $data;
-}
-
-/**
- * Store to be printed the subgroups rows (Recursive)
- *
- * @param mixed Group info
- * @param mixed Hash list with all the groups of 2nd or higher level
- * @param string (ref) Concatenation of branches classes to control the symbols from Javascript
- * @param int total number of groups
- * @param obj (ref) table object in html_print_table format with the stored groups
- * @param int (ref) counter of the row stored
- * @param string (ref) Concatenation of branches class with the parent classes
- *
- */
-function groups_print_group_sons($group, $sons, &$branch_classes, $groups_count, &$table, &$iterator, &$symbolBranchs) {
- if (isset($sons[$group['id_grupo']])) {
- foreach($sons[$group['id_grupo']] as $key => $g) {
- $symbolBranchs .= ' symbol_branch_' . $g['parent'];
-
- $has_children = isset($sons[$g['id_grupo']]);
-
- $data = groups_get_group_to_list($g, $groups_count, $symbolBranchs, $has_children);
- array_push ($table->data, $data);
-
- $branch_classes[$g['id_grupo']] = $branch_classes[$g['parent']] . ' branch_' . $g['parent'];
- $table->rowclass[$iterator] = 'parent_' . $g['parent'] . $branch_classes[$g['id_grupo']];
-
- if ($g['deep'] == 0) {
- $table->rowstyle[$iterator] = '';
- }
- else {
- if ($g['parent'] != 0) {
- $table->rowstyle[$iterator] = 'display: none;';
- }
- }
-
- $iterator++;
-
- groups_print_group_sons($g, $sons, $branch_classes, $groups_count, $table, $iterator, $symbolBranchs);
- }
- }
+ return ($agents === false) ? $default_total : $agents;
}
/**
@@ -2314,108 +1737,47 @@ function groups_get_tree_keys ($groups, &$group_keys) {
}
}
-function groups_get_all_hierarchy_group ($id_group, $hierarchy = array()) {
- global $config;
-
- if ($id_group == 0) {
- $hierarchy = groups_get_childrens($id_group);
- }
- else {
- $hierarchy[] = $id_group;
- $parent = db_get_value('parent','tgrupo','id_grupo',$id_group);
-
- if ($parent !== 0) {
- $propagate = db_get_value('propagate','tgrupo','id_grupo',$parent);
-
- if ($propagate == 1) {
- //$childrens_ids_parent = array($parent);
- $hierarchy[] = $parent;
- $childrens = groups_get_childrens($parent);
- if (!empty($childrens)) {
- foreach ($childrens as $child) {
- //$childrens_ids_parent[] = (int)$child['id_grupo'];
- $hierarchy[] = (int)$child['id_grupo'];
- }
- }
-
- $hierarchy = groups_get_all_hierarchy_group ($parent, $hierarchy);
- }
- }
- }
- return $hierarchy;
-}
-
-
-
function group_get_data ($id_user = false, $user_strict = false, $acltags, $returnAllGroup = false, $mode = 'group', $agent_filter = array(), $module_filter = array()) {
global $config;
if ($id_user == false) {
$id_user = $config['id_user'];
}
-
+
$user_groups = array();
$user_tags = array();
- $groups_without_tags = array();
foreach ($acltags as $group => $tags) {
- if ($user_strict) { //Remove groups with tags
- if ($tags == '') {
- $groups_without_tags[$group] = $group;
- }
- }
$user_groups[$group] = groups_get_name($group);
if ($tags != '') {
$tags_group = explode(',', $tags);
-
+
foreach ($tags_group as $tag) {
$user_tags[$tag] = tags_get_name($tag);
}
}
}
-
- if ($user_strict) {
- $user_groups_ids = implode(',', array_keys($groups_without_tags));
- }
- else {
- $user_groups_ids = implode(',', array_keys($acltags));
- }
-
+
+ $user_groups_ids = implode(',', array_keys($acltags));
+
if (!empty($user_groups_ids)) {
- switch ($config["dbtype"]) {
- case "mysql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- break;
- case "postgresql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- ORDER BY nombre ASC");
- break;
- case "oracle":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- ORDER BY nombre ASC");
- break;
- }
+ $list_groups = db_get_all_rows_sql("
+ SELECT *
+ FROM tgrupo
+ WHERE id_grupo IN (" . $user_groups_ids . ")
+ ORDER BY nombre COLLATE utf8_general_ci ASC"
+ );
}
-
+
$list = array();
-
+
if ($list_groups == false) {
$list_groups = array();
}
-
+
if ($returnAllGroup) {
$i = 1;
$list[0]['_id_'] = 0;
$list[0]['_name_'] = __('All');
-
+
$list[0]['_agents_unknown_'] = 0;
$list[0]['_monitors_alerts_fired_'] = 0;
$list[0]['_total_agents_'] = 0;
@@ -2425,7 +1787,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_unknown_'] = 0;
$list[0]['_monitors_not_init_'] = 0;
$list[0]['_agents_not_init_'] = 0;
-
+
if ($mode == 'tactical') {
$list[0]['_agents_ok_'] = 0;
$list[0]['_agents_warning_'] = 0;
@@ -2436,81 +1798,93 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
else {
$i = 0;
}
-
- /*
+
+ /*
* Agent cache for metaconsole.
* Retrieve the statistic data from the cache table.
*/
- if (!$user_strict && is_metaconsole() && !empty($list_groups)) {
+ if (is_metaconsole() && !empty($list_groups)) {
$cache_table = 'tmetaconsole_agent';
-
- $sql_stats = "SELECT id_grupo, COUNT(id_agente) AS agents_total,
- SUM(total_count) AS monitors_total,
- SUM(normal_count) AS monitors_ok,
- SUM(warning_count) AS monitors_warning,
- SUM(critical_count) AS monitors_critical,
- SUM(unknown_count) AS monitors_unknown,
- SUM(notinit_count) AS monitors_not_init,
- SUM(fired_count) AS alerts_fired
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- GROUP BY id_grupo";
+
+ $sql_stats =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_total,
+ SUM(total_count) AS monitors_total,
+ SUM(normal_count) AS monitors_ok,
+ SUM(warning_count) AS monitors_warning,
+ SUM(critical_count) AS monitors_critical,
+ SUM(unknown_count) AS monitors_unknown,
+ SUM(notinit_count) AS monitors_not_init,
+ SUM(fired_count) AS alerts_fired
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ GROUP BY id_grupo"
+ ;
$data_stats = db_get_all_rows_sql($sql_stats);
-
- $sql_stats_unknown = "SELECT id_grupo, COUNT(id_agente) AS agents_unknown
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- AND critical_count = 0
- AND warning_count = 0
- AND unknown_count > 0
- GROUP BY id_grupo";
+
+ $sql_stats_unknown =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_unknown
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ AND critical_count = 0
+ AND warning_count = 0
+ AND unknown_count > 0
+ GROUP BY id_grupo"
+ ;
$data_stats_unknown = db_get_all_rows_sql($sql_stats_unknown);
-
- $sql_stats_not_init = "SELECT id_grupo, COUNT(id_agente) AS agents_not_init
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- AND (total_count = 0 OR total_count = notinit_count)
- GROUP BY id_grupo";
+
+ $sql_stats_not_init =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_not_init
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ AND (total_count = 0 OR total_count = notinit_count)
+ GROUP BY id_grupo"
+ ;
$data_stats_not_init = db_get_all_rows_sql($sql_stats_not_init);
-
+
if ($mode == 'tactical' || $mode == 'tree') {
- $sql_stats_ok = "SELECT id_grupo, COUNT(id_agente) AS agents_ok
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- AND critical_count = 0
- AND warning_count = 0
- AND unknown_count = 0
- AND normal_count > 0
- GROUP BY id_grupo";
+ $sql_stats_ok =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_ok
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ AND critical_count = 0
+ AND warning_count = 0
+ AND unknown_count = 0
+ AND normal_count > 0
+ GROUP BY id_grupo"
+ ;
$data_stats_ok = db_get_all_rows_sql($sql_stats_ok);
-
- $sql_stats_warning = "SELECT id_grupo, COUNT(id_agente) AS agents_warning
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- AND critical_count = 0
- AND warning_count > 0
- GROUP BY id_grupo";
+
+ $sql_stats_warning =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_warning
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ AND critical_count = 0
+ AND warning_count > 0
+ GROUP BY id_grupo"
+ ;
$data_stats_warning = db_get_all_rows_sql($sql_stats_warning);
-
- $sql_stats_critical = "SELECT id_grupo, COUNT(id_agente) AS agents_critical
- FROM $cache_table
- WHERE disabled = 0
- AND id_grupo IN ($user_groups_ids)
- AND critical_count > 0
- GROUP BY id_grupo";
+
+ $sql_stats_critical =
+ "SELECT id_grupo, COUNT(id_agente) AS agents_critical
+ FROM $cache_table
+ WHERE disabled = 0
+ AND id_grupo IN ($user_groups_ids)
+ AND critical_count > 0
+ GROUP BY id_grupo"
+ ;
$data_stats_critical = db_get_all_rows_sql($sql_stats_critical);
}
-
+
$stats_by_group = array();
if (!empty($data_stats)) {
foreach ($data_stats as $value) {
$group_id = (int) $value['id_grupo'];
-
+
$stats = array();
$stats['agents_total'] = (int) $value['agents_total'];
$stats['monitors_total'] = (int) $value['monitors_total'];
@@ -2522,7 +1896,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$stats['alerts_fired'] = (int) $value['alerts_fired'];
$stats_by_group[$group_id] = $stats;
}
-
+
if (!empty($stats_by_group)) {
if (!empty($data_stats_unknown)) {
foreach ($data_stats_unknown as $value) {
@@ -2567,26 +1941,26 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
}
}
}
-
+
foreach ($list_groups as $key => $item) {
$id = $item['id_grupo'];
-
- if (!$user_strict && is_metaconsole()) { // Agent cache
+
+ if (is_metaconsole()) { // Agent cache
$group_stat = array();
if (isset($stats_by_group[$id]))
$group_stat = $stats_by_group[$id];
-
+
$list[$i]['_id_'] = $id;
$list[$i]['_name_'] = $item['nombre'];
$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
-
+
if ($mode == 'tree' && !empty($item['parent']))
$list[$i]['_parent_id_'] = $item['parent'];
-
+
$list[$i]['_agents_unknown_'] = isset($group_stat['agents_unknown']) ? $group_stat['agents_unknown'] : 0;
$list[$i]['_monitors_alerts_fired_'] = isset($group_stat['alerts_fired']) ? $group_stat['alerts_fired'] : 0;
$list[$i]['_total_agents_'] = isset($group_stat['agents_total']) ? $group_stat['agents_total'] : 0;
-
+
// This fields are not in database
$list[$i]['_monitors_ok_'] = isset($group_stat['monitors_ok']) ? $group_stat['monitors_ok'] : 0;
$list[$i]['_monitors_critical_'] = isset($group_stat['monitors_critical']) ? $group_stat['monitors_critical'] : 0;
@@ -2594,38 +1968,38 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[$i]['_monitors_unknown_'] = isset($group_stat['monitors_unknown']) ? $group_stat['monitors_unknown'] : 0;
$list[$i]['_monitors_not_init_'] = isset($group_stat['monitors_not_init']) ? $group_stat['monitors_not_init'] : 0;
$list[$i]['_agents_not_init_'] = isset($group_stat['agents_not_init']) ? $group_stat['agents_not_init'] : 0;
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[$i]['_agents_ok_'] = isset($group_stat['agents_ok']) ? $group_stat['agents_ok'] : 0;
$list[$i]['_agents_warning_'] = isset($group_stat['agents_warning']) ? $group_stat['agents_warning'] : 0;
$list[$i]['_agents_critical_'] = isset($group_stat['agents_critical']) ? $group_stat['agents_critical'] : 0;
$list[$i]['_monitors_alerts_'] = isset($group_stat['alerts']) ? $group_stat['alerts'] : 0;;
-
+
$list[$i]["_monitor_alerts_fire_count_"] = $group_stat[0]["alerts_fired"];
$list[$i]["_total_checks_"] = $group_stat[0]["modules"];
$list[$i]["_total_alerts_"] = $group_stat[0]["alerts"];
}
if ($mode == 'tactical') {
- // Get total count of monitors for this group, except disabled.
+ // Get total count of monitors for this group, except disabled.
$list[$i]["_monitor_checks_"] = $list[$i]["_monitors_not_init_"] + $list[$i]["_monitors_unknown_"] + $list[$i]["_monitors_warning_"] + $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_ok_"];
-
+
// Calculate not_normal monitors
$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
-
+
if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_monitor_health_"] = 100;
}
-
+
if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_module_sanity_"] = 100;
}
-
+
if (isset($list[$i]["_alerts_"])) {
if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
@@ -2638,19 +2012,19 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[$i]["_alert_level_"] = 100;
$list[$i]["_alerts_"] = 0;
}
-
+
$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
-
+
if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_global_health_"] = 100;
}
-
+
$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
}
-
+
if ($returnAllGroup) {
$list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
$list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
@@ -2661,7 +2035,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
$list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
$list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
@@ -2669,7 +2043,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
}
}
-
+
if ($mode == 'group') {
if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0)
&& ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0)
@@ -2677,26 +2051,26 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
unset($list[$i]);
}
}
-
+
}
- else if (($config["realtimestats"] == 0) && !$user_strict) {
+ else if (($config["realtimestats"] == 0)) {
$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 = $id
ORDER BY nombre");
-
+
$list[$i]['_id_'] = $id;
$list[$i]['_name_'] = $item['nombre'];
$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
-
+
if ($mode == 'tree' && !empty($item['parent']))
$list[$i]['_parent_id_'] = $item['parent'];
-
+
$list[$i]['_agents_unknown_'] = $group_stat[0]["unknown"];
$list[$i]['_monitors_alerts_fired_'] = $group_stat[0]["alerts_fired"];
$list[$i]['_total_agents_'] = $group_stat[0]["agents"];
-
+
// This fields are not in database
$list[$i]['_monitors_ok_'] = (int) groups_get_normal_monitors($id);
$list[$i]['_monitors_critical_'] = (int) groups_get_critical_monitors($id);
@@ -2704,38 +2078,38 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[$i]['_monitors_unknown_'] = (int) groups_get_unknown_monitors($id);
$list[$i]['_monitors_not_init_'] = (int) groups_get_not_init_monitors($id);
$list[$i]['_agents_not_init_'] = (int) groups_get_not_init_agents($id);
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[$i]['_agents_ok_'] = $group_stat[0]["normal"];
$list[$i]['_agents_warning_'] = $group_stat[0]["warning"];
$list[$i]['_agents_critical_'] = $group_stat[0]["critical"];
$list[$i]['_monitors_alerts_'] = $group_stat[0]["alerts"];
-
+
$list[$i]["_monitor_alerts_fire_count_"] = $group_stat[0]["alerts_fired"];
$list[$i]["_total_checks_"] = $group_stat[0]["modules"];
$list[$i]["_total_alerts_"] = $group_stat[0]["alerts"];
}
if ($mode == 'tactical') {
- // Get total count of monitors for this group, except disabled.
+ // Get total count of monitors for this group, except disabled.
$list[$i]["_monitor_checks_"] = $list[$i]["_monitors_not_init_"] + $list[$i]["_monitors_unknown_"] + $list[$i]["_monitors_warning_"] + $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_ok_"];
-
+
// Calculate not_normal monitors
$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
-
+
if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_monitor_health_"] = 100;
}
-
+
if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_module_sanity_"] = 100;
}
-
+
if (isset($list[$i]["_alerts_"])) {
if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
@@ -2743,24 +2117,24 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
else {
$list[$i]["_alert_level_"] = 100;
}
- }
+ }
else {
$list[$i]["_alert_level_"] = 100;
$list[$i]["_alerts_"] = 0;
}
-
+
$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
-
+
if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_global_health_"] = 100;
}
-
+
$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
}
-
+
if ($returnAllGroup) {
$list[0]['_agents_unknown_'] += $group_stat[0]["unknown"];
$list[0]['_monitors_alerts_fired_'] += $group_stat[0]["alerts_fired"];
@@ -2771,7 +2145,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
$list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[0]['_agents_ok_'] += $group_stat[0]["normal"];
$list[0]['_agents_warning_'] += $group_stat[0]["warning"];
@@ -2779,7 +2153,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_alerts_'] += $group_stat[0]["alerts"];
}
}
-
+
if ($mode == 'group') {
if (! defined ('METACONSOLE')) {
if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0) && ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0) && ($list[$i]['_monitors_critical_'] == 0) && ($list[$i]['_monitors_warning_'] == 0) && ($list[$i]['_monitors_unknown_'] == 0) && ($list[$i]['_monitors_not_init_'] == 0) && ($list[$i]['_agents_not_init_'] == 0)) {
@@ -2792,56 +2166,55 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
}
}
}
-
}
else {
$list[$i]['_id_'] = $id;
$list[$i]['_name_'] = $item['nombre'];
$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
-
+
if ($mode == 'tree' && !empty($item['parent']))
$list[$i]['_parent_id_'] = $item['parent'];
-
+
$list[$i]['_monitors_ok_'] = (int) groups_get_normal_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_monitors_critical_'] = (int) groups_get_critical_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_monitors_warning_'] = (int) groups_get_warning_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_monitors_unknown_'] = (int) groups_get_unknown_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_monitors_not_init_'] = (int) groups_get_not_init_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
- $list[$i]['_monitors_alerts_fired_'] = groups_monitor_fired_alerts ($id, $user_strict, $id);
+ $list[$i]['_monitors_alerts_fired_'] = groups_monitor_fired_alerts ($id);
$list[$i]['_total_agents_'] = (int) groups_get_total_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_agents_unknown_'] = (int) groups_get_unknown_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_agents_not_init_'] = (int) groups_get_not_init_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[$i]['_agents_ok_'] = (int) groups_get_normal_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_agents_warning_'] = (int) groups_get_warning_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
$list[$i]['_agents_critical_'] = (int) groups_get_critical_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
- $list[$i]['_monitors_alerts_'] = groups_monitor_alerts ($id, $user_strict, $id);
-
+ $list[$i]['_monitors_alerts_'] = groups_monitor_alerts ($id);
+
// TODO
- //~ $list[$i]["_total_checks_"]
+ //~ $list[$i]["_total_checks_"]
//~ $list[$i]["_total_alerts_"]
-
- // Get total count of monitors for this group, except disabled.
+
+ // Get total count of monitors for this group, except disabled.
$list[$i]["_monitor_checks_"] = $list[$i]["_monitors_not_init_"] + $list[$i]["_monitors_unknown_"] + $list[$i]["_monitors_warning_"] + $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_ok_"];
-
+
// Calculate not_normal monitors
$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
-
+
if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_monitor_health_"] = 100;
}
-
+
if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_module_sanity_"] = 100;
}
-
+
if (isset($list[$i]["_alerts_"])) {
if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
@@ -2854,19 +2227,19 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[$i]["_alert_level_"] = 100;
$list[$i]["_alerts_"] = 0;
}
-
+
$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
-
+
if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
}
else {
$list[$i]["_global_health_"] = 100;
}
-
+
$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
}
-
+
if ($returnAllGroup) {
$list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
$list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
@@ -2877,7 +2250,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
$list[0]['_monitors_not_init_'] = $list[$i]['_monitors_not_init_'];
$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
-
+
if ($mode == 'tactical' || $mode == 'tree') {
$list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
$list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
@@ -2885,7 +2258,7 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
$list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
}
}
-
+
if ($mode == 'group') {
if (! defined ('METACONSOLE')) {
if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0) && ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0) && ($list[$i]['_monitors_critical_'] == 0) && ($list[$i]['_monitors_warning_'] == 0) && ($list[$i]['_monitors_unknown_'] == 0) && ($list[$i]['_monitors_not_init_'] == 0) && ($list[$i]['_agents_not_init_'] == 0)) {
@@ -2900,198 +2273,24 @@ function group_get_data ($id_user = false, $user_strict = false, $acltags, $retu
}
$i++;
}
-
- if ($user_strict) {
- foreach ($user_tags as $group_id => $tag_name) {
- $id = db_get_value('id_tag', 'ttag', 'name', $tag_name);
-
- $list[$i]['_id_'] = $id;
- $list[$i]['_name_'] = $tag_name;
- $list[$i]['_iconImg_'] = html_print_image ("images/tag_red.png", true, array ("style" => 'vertical-align: middle;'));
- $list[$i]['_is_tag_'] = 1;
-
- $list[$i]['_total_agents_'] = (int) tags_get_total_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_agents_unknown_'] = (int) tags_get_unknown_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_agents_not_init_'] = (int) tags_get_not_init_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_monitors_ok_'] = (int) tags_get_normal_monitors ($id, $acltags, $agent_filter, $module_filter);
- $list[$i]['_monitors_critical_'] = (int) tags_get_critical_monitors ($id, $acltags, $agent_filter, $module_filter);
- $list[$i]['_monitors_warning_'] = (int) tags_get_warning_monitors ($id, $acltags, $agent_filter, $module_filter);
- $list[$i]['_monitors_not_init_'] = (int) tags_get_not_init_monitors ($id, $acltags, $agent_filter, $module_filter);
- $list[$i]['_monitors_unknown_'] = (int) tags_get_unknown_monitors ($id, $acltags, $agent_filter, $module_filter);
- $list[$i]['_monitors_alerts_fired_'] = tags_monitors_fired_alerts($id, $acltags);
-
- if ($mode == 'tactical' || $mode == 'tree') {
- $list[$i]['_agents_ok_'] = (int) tags_get_normal_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_agents_warning_'] = (int) tags_get_warning_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_agents_critical_'] = (int) tags_get_critical_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
- $list[$i]['_monitors_alerts_'] = tags_get_monitors_alerts ($id, $acltags);
- }
- if ($mode == 'tactical') {
- // Get total count of monitors for this group, except disabled.
- $list[$i]["_monitor_checks_"] = $list[$i]["_monitors_not_init_"] + $list[$i]["_monitors_unknown_"] + $list[$i]["_monitors_warning_"] + $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_ok_"];
-
- // Calculate not_normal monitors
- $list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
-
- if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
- $list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list[$i]["_monitor_health_"] = 100;
- }
-
- if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
- $list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list[$i]["_module_sanity_"] = 100;
- }
-
- if (isset($list[$i]["_monitors_alerts_"])) {
- if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_monitors_alerts_"] > 0) {
- $list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_monitors_alerts_"] / 100)), 1);
- }
- else {
- $list[$i]["_alert_level_"] = 100;
- }
- }
- else {
- $list[$i]["_alert_level_"] = 100;
- $list[$i]["_monitors_alerts_"] = 0;
- }
-
- $list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
-
- if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
- $list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list[$i]["_global_health_"] = 100;
- }
-
- $list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
- }
-
- if ($returnAllGroup) {
- $list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
- $list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
- $list[0]['_total_agents_'] += $list[$i]['_total_agents_'];
- $list[0]['_monitors_ok_'] += $list[$i]['_monitors_ok_'];
- $list[0]['_monitors_critical_'] += $list[$i]['_monitors_critical_'];
- $list[0]['_monitors_warning_'] += $list[$i]['_monitors_warning_'];
- $list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
- $list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
- $list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
-
- if ($mode == 'tactical' || $mode == 'tree') {
- $list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
- $list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
- $list[0]['_agents_critical_'] += $list[$i]['_agents_critical_'];
- $list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
- }
- }
-
- if ($mode == 'group') {
- if (! defined ('METACONSOLE')) {
- if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0) && ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0) && ($list[$i]['_monitors_critical_'] == 0) && ($list[$i]['_monitors_warning_'] == 0) && ($list[$i]['_monitors_unknown_'] == 0) && ($list[$i]['_monitors_not_init_'] == 0) && ($list[$i]['_agents_not_init_'] == 0)) {
- unset($list[$i]);
- }
- }
- else {
- if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0) && ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0) && ($list[$i]['_monitors_critical_'] == 0) && ($list[$i]['_monitors_warning_'] == 0)) {
- unset($list[$i]);
- }
- }
- }
- $i++;
- }
- }
-
- return $list;
-}
-function group_get_groups_list($id_user = false, $user_strict = false, $access = 'AR', $force_group_and_tag = true, $returnAllGroup = false, $mode = 'group') {
- global $config;
-
- if ($id_user == false) {
- $id_user = $config['id_user'];
- }
-
- $acltags = tags_get_user_groups_and_tags ($id_user, $access, $user_strict);
-
- // If using metaconsole, the strict users will use the agent table of every node
- if (is_metaconsole() && $user_strict) {
- $servers = metaconsole_get_servers();
-
- $result_list = array ();
- foreach ($servers as $server) {
-
- if (metaconsole_connect($server) != NOERR) {
- continue;
- }
- $server_list = group_get_data ($id_user, $user_strict,
- $acltags, $returnAllGroup, $mode);
-
- foreach ($server_list as $server_item) {
- if (! isset ($result_list[$server_item['_name_']])) {
-
- $result_list[$server_item['_name_']] = $server_item;
- }
- else {
- $result_list[$server_item['_name_']]['_monitors_ok_'] += $server_item['_monitors_ok_'];
- $result_list[$server_item['_name_']]['_monitors_critical_'] += $server_item['_monitors_critical_'];
- $result_list[$server_item['_name_']]['_monitors_warning_'] += $server_item['_monitors_warning_'];
- $result_list[$server_item['_name_']]['_agents_unknown_'] += $server_item['_agents_unknown_'];
- $result_list[$server_item['_name_']]['_total_agents_'] += $server_item['_total_agents_'];
- $result_list[$server_item['_name_']]['_monitors_alerts_fired_'] += $server_item['_monitors_alerts_fired_'];
-
- if ($mode == 'tactical') {
- $result_list[$server_item['_name_']]['_agents_ok_'] += $server_item['_agents_ok_'];
- $result_list[$server_item['_name_']]['_agents_critical_'] += $server_item['_agents_critical_'];
- $result_list[$server_item['_name_']]['_agents_warning_'] += $server_item['_agents_warning_'];
- $result_list[$server_item['_name_']]['_monitors_alerts_'] += $server_item['_monitors_alerts_'];
-
- $result_list[$server_item['_name_']]["_monitor_checks_"] += $server_item["_monitor_checks_"];
- $result_list[$server_item['_name_']]["_monitor_not_normal_"] += $server_item["_monitor_not_normal_"];
- $result_list[$server_item['_name_']]["_monitor_health_"] += $server_item["_monitor_health_"];
- $result_list[$server_item['_name_']]["_module_sanity_"] += $server_item["_module_sanity_"];
- $result_list[$server_item['_name_']]["_alerts_"] += $server_item["_alerts_"];
- $result_list[$server_item['_name_']]["_alert_level_"] += $server_item["_alert_level_"];
- $result_list[$server_item['_name_']]["_monitor_bad_"] += $server_item["_monitor_bad_"];
- $result_list[$server_item['_name_']]["_global_health_"] += $server_item["_global_health_"];
- $result_list[$server_item['_name_']]["_server_sanity_"] += $server_item["_server_sanity_"];
- $result_list[$server_item['_name_']]["_monitor_alerts_fire_count_"] += $server_item["_monitor_alerts_fire_count_"];
- $result_list[$server_item['_name_']]["_total_checks_"] += $server_item["_total_checks_"];
- $result_list[$server_item['_name_']]["_total_alerts_"] += $server_item["_total_alerts_"];
- }
- }
- }
- metaconsole_restore_db();
-
- }
-
- return $result_list;
- }
- // If using metaconsole, the not strict users will use the metaconsole's agent cache table
- else {
- $result_list = group_get_data ($id_user, $user_strict, $acltags,
- $returnAllGroup, $mode);
-
- return $result_list;
- }
+ return $list;
}
function groups_get_group_deep ($id_group) {
global $config;
- $parents = groups_get_parents($id_group, false);
-
+
+ $groups = users_get_groups(false, "AR", true, true);
+
+ $parents = groups_get_parents($id_group, false, $groups);
+
if (empty($parents)) {
$deep = "";
}
else {
$deep = str_repeat(" ", count($parents));
}
-
+
return $deep;
}
diff --git a/pandora_console/include/functions_groupview.php b/pandora_console/include/functions_groupview.php
index db7eec8706..15b4d577bf 100644
--- a/pandora_console/include/functions_groupview.php
+++ b/pandora_console/include/functions_groupview.php
@@ -16,877 +16,179 @@
include_once ($config['homedir'] . "/include/functions_groups.php");
include_once ($config['homedir'] . "/include/functions_tags.php");
+include_once ($config['homedir'] . "/include/class/Tree.class.php");
+include_once ($config['homedir'] . "/include/class/TreeGroup.class.php");
-function groupview_get_all_data ($id_user = false, $user_strict = false, $acltags, $returnAllGroup = false, $agent_filter = array(), $module_filter = array(), $access = 'AR') {
- global $config;
- if ($id_user == false) {
- $id_user = $config['id_user'];
- }
-
- $user_groups = array();
- $user_tags = array();
-
- foreach ($acltags as $item) {
- $user_groups[$item["id_grupo"]] = $item["nombre"];
-
- if ($item["tags"] != '') {
- $tags_group = explode(',', $item["tags"]);
-
- foreach ($tags_group as $tag) {
- $user_tags[$tag] = tags_get_name($tag);
- }
- }
- }
-
- $user_groups_ids = implode(',', array_keys($acltags));
-
- if (!empty($user_groups_ids)) {
- if (is_metaconsole()) {
- switch ($config["dbtype"]) {
- case "mysql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- break;
- case "postgresql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- case "oracle":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- }
- }
- else {
- switch ($config["dbtype"]) {
- case "mysql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- break;
- case "postgresql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- case "oracle":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- }
- }
- }
-
- foreach ($list_groups as $group) {
- $list[$group['id_grupo']]['_name_'] = $group['nombre'];
- $list[$group['id_grupo']]['_id_'] = $group['id_grupo'];
- $list[$group['id_grupo']]['_monitors_critical_'] = 0;
- $list[$group['id_grupo']]['_monitors_warning_'] = 0;
- $list[$group['id_grupo']]['_monitors_unknown_'] = 0;
- $list[$group['id_grupo']]['_monitors_not_init_'] = 0;
- $list[$group['id_grupo']]['_monitors_ok_'] = 0;
- $list[$group['id_grupo']]['_agents_not_init_'] = 0;
- $list[$group['id_grupo']]['_agents_unknown_'] = 0;
- $list[$group['id_grupo']]['_agents_critical_'] = 0;
- $list[$group['id_grupo']]['_total_agents_'] = 0;
- $list[$group['id_grupo']]["_monitor_checks_"] = 0;
- $list[$group['id_grupo']]["_monitor_not_normal_"] = 0;
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = 0;
- }
- if ($list_groups == false) {
- $list_groups = array();
- }
-
- /*
- * Agent cache for metaconsole.
- * Retrieve the statistic data from the cache table.
- */
- if (is_metaconsole()) {
- foreach ($list_groups as $group) {
- $group_agents = db_get_row_sql("SELECT SUM(warning_count) AS _monitors_warning_,
- SUM(critical_count) AS _monitors_critical_,
- SUM(normal_count) AS _monitors_ok_,
- SUM(unknown_count) AS _monitors_unknown_,
- SUM(notinit_count) AS _monitors_not_init_,
- SUM(fired_count) AS _monitors_alerts_fired_,
- COUNT(*) AS _total_agents_, id_grupo, intervalo,
- ultimo_contacto, disabled
- FROM tmetaconsole_agent ta
- LEFT JOIN tmetaconsole_agent_secondary_group tasg
- ON ta.id_agente = tasg.id_agent
- WHERE (
- ta.id_grupo = " . $group['id_grupo'] . "
- OR tasg.id_group = " . $group['id_grupo'] . "
- ) AND disabled = 0 GROUP BY id_grupo");
- $list[$group['id_grupo']]['_monitors_critical_'] = (int)$group_agents['_monitors_critical_'];
- $list[$group['id_grupo']]['_monitors_warning_'] = (int)$group_agents['_monitors_warning_'];
- $list[$group['id_grupo']]['_monitors_unknown_'] = (int)$group_agents['_monitors_unknown_'];
- $list[$group['id_grupo']]['_monitors_not_init_'] = (int)$group_agents['_monitors_not_init_'];
- $list[$group['id_grupo']]['_monitors_ok_'] = (int)$group_agents['_monitors_ok_'];
-
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = (int)$group_agents['_monitors_alerts_fired_'];
-
- $list[$group['id_grupo']]['_total_agents_'] = (int)$group_agents['_total_agents_'];
-
- $list[$group['id_grupo']]["_monitor_checks_"] = $list[$group['id_grupo']]["_monitors_not_init_"] + $list[$group['id_grupo']]["_monitors_unknown_"] + $list[$group['id_grupo']]["_monitors_warning_"] + $list[$group['id_grupo']]["_monitors_critical_"] + $list[$group['id_grupo']]["_monitors_ok_"];
-
- // Calculate not_normal monitors
- $list[$group['id_grupo']]["_monitor_not_normal_"] = $list[$group['id_grupo']]["_monitor_checks_"] - $list[$group['id_grupo']]["_monitors_ok_"];
-
- $total_agents = $list[$group['id_grupo']]['_total_agents_'];
-
- if (($group['id_grupo'] != 0) && ($total_agents > 0)) {
- $agents = db_get_all_rows_sql("SELECT warning_count,
- critical_count,
- normal_count,
- unknown_count,
- notinit_count,
- fired_count,
- disabled
- FROM tmetaconsole_agent
- WHERE id_grupo = " . $group['id_grupo'] );
- foreach ($agents as $agent) {
- if ($agent['critical_count'] > 0) {
- $list[$group['id_grupo']]['_agents_critical_'] += 1;
- }
- else {
- if (($agent['critical_count'] == 0) && ($agent['warning_count'] == 0) && ($group_agents['disabled'] == 0) && ($agent['normal_count'] == 0)) {
- if ($agent['unknown_count'] > 0) {
- $list[$group['id_grupo']]['_agents_unknown_'] += 1;
- }
- }
- if (($agent['critical_count'] == 0) && ($agent['warning_count'] == 0) && ($group_agents['disabled'] == 0) && ($agent['normal_count'] == 0) && ($agent['unknown_count'] == 0)) {
- if ($agent['notinit_count'] > 0) {
- $list[$group['id_grupo']]['_agents_not_init_'] += 1;
- }
- }
- }
- }
- }
- }
- }
- else if (false) { //FIXME: The cached group view is wasted. Avoid to reach this code.
-
- $group_stat = db_get_all_rows_sql ("SELECT
- SUM(ta.normal_count) as normal, SUM(ta.critical_count) as critical,
- SUM(ta.warning_count) as warning,SUM(ta.unknown_count) as unknown,
- SUM(ta.notinit_count) as not_init, SUM(fired_count) as alerts_fired
- FROM tagente ta
- WHERE id_grupo IN ($user_groups_ids)");
-
- $list['_agents_unknown_'] = $group_stat[0]["unknown"];
- $list['_monitors_alerts_fired_'] = $group_stat[0]["alerts_fired"];
-
- $list['_monitors_ok_'] = $group_stat[0]["normal"];
- $list['_monitors_warning_'] = $group_stat[0]["warning"];
- $list['_monitors_critical_'] = $group_stat[0]["critical"];
- $list['_monitors_unknown_'] = $group_stat[0]["unknown"];
- $list['_monitors_not_init_'] = $group_stat[0]["not_init"];
- $total_agentes = agents_get_agents (false, array('count(*) as total_agents'), $access,false, false);
- $list['_total_agents_'] = $total_agentes[0]['total_agents'];
- $list["_monitor_alerts_fire_count_"] = $group_stat[0]["alerts_fired"];
-
- $list['_monitors_alerts_'] = groupview_monitor_alerts (explode(',',$user_groups_ids), $user_strict,explode(',',$user_groups_ids));
- // Get total count of monitors for this group, except disabled.
- $list["_monitor_checks_"] = $list["_monitors_not_init_"] + $list["_monitors_unknown_"] + $list["_monitors_warning_"] + $list["_monitors_critical_"] + $list["_monitors_ok_"];
-
- // Calculate not_normal monitors
- $list["_monitor_not_normal_"] = $list["_monitor_checks_"] - $list["_monitors_ok_"];
-
- if ($list["_monitor_not_normal_"] > 0 && $list["_monitor_checks_"] > 0) {
- $list["_monitor_health_"] = format_numeric (100 - ($list["_monitor_not_normal_"] / ($list["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list["_monitor_health_"] = 100;
- }
-
- if ($list["_monitors_not_init_"] > 0 && $list["_monitor_checks_"] > 0) {
- $list["_module_sanity_"] = format_numeric (100 - ($list["_monitors_not_init_"] / ($list["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list["_module_sanity_"] = 100;
- }
-
- if (isset($list["_alerts_"])) {
- if ($list["_monitors_alerts_fired_"] > 0 && $list["_alerts_"] > 0) {
- $list["_alert_level_"] = format_numeric (100 - ($list["_monitors_alerts_fired_"] / ($list["_alerts_"] / 100)), 1);
- }
- else {
- $list["_alert_level_"] = 100;
- }
- }
- else {
- $list["_alert_level_"] = 100;
- $list["_alerts_"] = 0;
- }
-
- $list["_monitor_bad_"] = $list["_monitors_critical_"] + $list["_monitors_warning_"];
-
- if ($list["_monitor_bad_"] > 0 && $list["_monitor_checks_"] > 0) {
- $list["_global_health_"] = format_numeric (100 - ($list["_monitor_bad_"] / ($list["_monitor_checks_"] / 100)), 1);
- }
- else {
- $list["_global_health_"] = 100;
- }
-
- $list["_server_sanity_"] = format_numeric (100 - $list["_module_sanity_"], 1);
- }
- else {
- foreach ($list_groups as $group) {
- $agent_not_init = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_NOT_INIT),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_not_init_'] = isset ($agent_not_init[0]['total']) ? $agent_not_init[0]['total'] : 0;
- $agent_unknown = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_UNKNOWN),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_unknown_'] = isset ($agent_unknown[0]['total']) ? $agent_unknown[0]['total'] : 0;
- $agent_critical = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_CRITICAL),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_critical_'] = isset ($agent_critical[0]['total']) ? $agent_critical[0]['total'] : 0;
- $agent_total = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo']),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_total_agents_'] = isset ($agent_total[0]['total']) ? $agent_total[0]['total'] : 0;
- $list[$group['id_grupo']]["_monitor_not_normal_"] = $list[$group['id_grupo']]["_monitor_checks_"] - $list[$group['id_grupo']]["_monitors_ok_"];
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = groupview_monitor_fired_alerts ($group['id_grupo'], $user_strict,array($group['id_grupo']));
- $result_list = db_get_all_rows_sql("SELECT COUNT(*) as contado, estado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- AND ta.id_grupo = " . $group['id_grupo'] . "
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.utimestamp > 0
- GROUP BY estado");
- if ($result_list) {
- foreach ($result_list as $result) {
- switch ($result['estado']) {
- case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $list[$group['id_grupo']]['_monitors_critical_'] = (int)$result['contado'];
- break;
- case AGENT_MODULE_STATUS_WARNING_ALERT:
- break;
- case AGENT_MODULE_STATUS_WARNING:
- $list[$group['id_grupo']]['_monitors_warning_'] = (int)$result['contado'];
- break;
- case AGENT_MODULE_STATUS_UNKNOWN:
- $list[$group['id_grupo']]['_monitors_unknown_'] = (int)$result['contado'];
- break;
- }
- }
- }
- $result_normal = db_get_row_sql("SELECT COUNT(*) as contado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- AND ta.id_grupo = " . $group['id_grupo'] . "
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.estado = 0
- AND (tae.utimestamp > 0 OR tam.id_tipo_modulo IN(21,22,23,100))
- GROUP BY estado");
- $list[$group['id_grupo']]['_monitors_ok_'] = isset ($result_normal['contado']) ? $result_normal['contado'] : 0;
-
- $result_not_init = db_get_row_sql("SELECT COUNT(*) as contado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- AND ta.id_grupo = " . $group['id_grupo'] . "
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.utimestamp = 0
- AND tae.estado IN (".AGENT_MODULE_STATUS_NO_DATA.",".AGENT_MODULE_STATUS_NOT_INIT." )
- AND tam.id_tipo_modulo NOT IN (21,22,23,100)
- GROUP BY estado");
- $list[$group['id_grupo']]['_monitors_not_init_'] = isset ($result_not_init['contado']) ? $result_not_init['contado'] : 0;
- }
- }
- return $list;
-}
-
-function groupview_status_modules_agents($id_user = false, $user_strict = false, $access = 'AR', $force_group_and_tag = true, $returnAllGroup = false) {
- global $config;
-
- if ($id_user == false) {
- $id_user = $config['id_user'];
- }
-
- //$acltags = tags_get_user_groups_and_tags ($id_user, $access, $user_strict);
- $acltags = users_get_groups ($id_user, $access, true, true);
-
- $result_list = groupview_get_all_data ($id_user, $user_strict,
- $acltags, false, array(), array(), $access);
- return $result_list;
-}
-
-function groupview_monitor_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
-
- // If there are not groups to query, we jump to nextone
-
- if (empty ($group_array)) {
- return 0;
-
- }
- else if (!is_array ($group_array)) {
- $group_array = array($group_array);
- }
-
- $group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- if ($strict_user) {
- $group_clause_strict = implode (",", $id_group_strict);
- $group_clause_strict = "(" . $group_clause_strict . ")";
- if ($group_clause_strict !== '()') {
- $sql = "SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- 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";
- }
- $count = db_get_sql ($sql);
- return $count;
- } else {
- //TODO REVIEW ORACLE AND POSTGRES
- return db_get_sql ("SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- 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");
- }
-}
-
-function groupview_monitor_fired_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
-
- // If there are not groups to query, we jump to nextone
- if (empty ($group_array)) {
- return 0;
- }
- else if (!is_array ($group_array)) {
- $group_array = array($group_array);
- }
-
- $group_clause = implode (",", $group_array);
- $group_clause = "(" . $group_clause . ")";
-
- return db_get_sql ("SELECT COUNT(talert_template_modules.id)
- FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
- 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");
-}
-
-function groupview_get_groups_list($id_user = false, $user_strict = false, $access = 'AR', $force_group_and_tag = true, $returnAllGroup = false) {
- global $config;
-
- if ($id_user == false) {
- $id_user = $config['id_user'];
- }
-
- $acltags = users_get_groups($id_user, $access, true, true);
- $result_list = groupview_get_data ($id_user, $user_strict, $acltags,
- $returnAllGroup, array(), array(), $access);
-
- return $result_list;
-}
-
-function groupview_get_data ($id_user = false, $user_strict = false, $acltags, $returnAllGroup = false, $agent_filter = array(), $module_filter = array(), $access = 'AR') {
- global $config;
- if ($id_user == false) {
- $id_user = $config['id_user'];
- }
-
- $user_groups = array();
- $user_tags = array();
-
- foreach ($acltags as $item) {
- $user_groups[$item["id_grupo"]] = $item["nombre"];
-
- if ($item["tags"] != '') {
- $tags_group = explode(',', $item["tags"]);
-
- foreach ($tags_group as $tag) {
- $user_tags[$tag] = tags_get_name($tag);
- }
- }
- }
-
- $groups_with_privileges = implode(',', array_keys($acltags));
-
- if (!$user_strict)
- $acltags[0] = 0;
-
- $user_groups_ids = implode(',', array_keys($acltags));
-
- if (!empty($user_groups_ids)) {
- if (is_metaconsole()) {
- switch ($config["dbtype"]) {
- case "mysql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND (
- id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- OR id_grupo IN (SELECT id_group FROM tmetaconsole_agent_secondary_group WHERE id_group IN (" . $user_groups_ids . "))
- )
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- break;
- case "postgresql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- case "oracle":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tmetaconsole_agent WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- }
- }
- else {
- switch ($config["dbtype"]) {
- case "mysql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND (
- id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- OR id_grupo IN (SELECT id_group FROM tagent_secondary_group WHERE id_group IN (" . $user_groups_ids . "))
- )
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- break;
- case "postgresql":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- case "oracle":
- $list_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $user_groups_ids . ")
- AND id_grupo IN (SELECT id_grupo FROM tagente WHERE disabled = 0)
- ORDER BY nombre ASC");
- break;
- }
- }
- }
-
- //Add the group "All" at first
- $group_all = array('id_grupo'=>0, 'nombre'=>'All', 'icon'=>'', 'parent'=>'', 'propagate'=>0, 'disabled'=>0,
- 'custom_id'=>'', 'id_skin'=>0, 'description'=>'', 'contact'=>'', 'other'=>'', 'password'=>'');
- if ($list_groups !== false) {
- array_unshift($list_groups, $group_all);
- } else {
- $list_groups = array($group_all);
- }
-
- if (!$user_strict) {
- //Takes the parents even without agents, first ids
- $fathers_id = '';
- $list_father_groups = array();
- foreach ($list_groups as $group) {
- if ($group['parent'] != '') {
- $grup = $group['parent'];
- while ($grup != 0) {
- $recursive_fathers = db_get_row_sql ("SELECT parent FROM tgrupo
- WHERE id_grupo = " . $grup);
- $grup = $recursive_fathers['parent'];
- if (!strpos($fathers_id, $grup)) {
- $fathers_id .= ',' . $grup;
- }
- }
- if (!strpos($fathers_id, $group['parent'])) {
- $fathers_id .= ',' . $group['parent'];
- }
- }
- }
- //Eliminate the first comma
- $fathers_id = substr($fathers_id, 1);
- while ($fathers_id{0} == ',') {
- $fathers_id = substr($fathers_id, 1);
- }
- //Takes the parents even without agents, complete groups
- if ($fathers_id) {
- $list_father_groups = db_get_all_rows_sql("
- SELECT *
- FROM tgrupo
- WHERE id_grupo IN (" . $fathers_id . ")
- AND id_grupo IN (" . $groups_with_privileges . ")
- ORDER BY nombre COLLATE utf8_general_ci ASC");
- if (!empty($list_father_groups)) {
- //Merges the arrays and eliminates the duplicates groups
- $list_groups = array_merge($list_groups, $list_father_groups);
- }
- }
- $list_groups = groupview_array_unique_multidim($list_groups, 'id_grupo');
- //Order groups (Father-children)
- $ordered_groups = groupview_order_groups_for_parents($list_groups);
- $ordered_ids = array();
- $ordered_ids = groupview_order_group_ids($ordered_groups, $ordered_ids);
- $final_list = array();
- array_push($final_list, $group_all);
-
- foreach ($ordered_ids as $key) {
- if ($key == 'All') {
- continue;
- }
- $complete_group = db_get_row_sql("
- SELECT *
- FROM tgrupo
- WHERE nombre = '" . $key . "'");
- array_push($final_list, $complete_group);
- }
-
- $list_groups = $final_list;
- }
-
- $list = array();
- foreach ($list_groups as $group) {
- $list[$group['id_grupo']]['_name_'] = $group['nombre'];
- $list[$group['id_grupo']]['_id_'] = $group['id_grupo'];
- $list[$group['id_grupo']]['icon'] = $group['icon'];
- $list[$group['id_grupo']]['_monitors_critical_'] = 0;
- $list[$group['id_grupo']]['_monitors_warning_'] = 0;
- $list[$group['id_grupo']]['_monitors_unknown_'] = 0;
- $list[$group['id_grupo']]['_monitors_not_init_'] = 0;
- $list[$group['id_grupo']]['_monitors_ok_'] = 0;
- $list[$group['id_grupo']]['_agents_not_init_'] = 0;
- $list[$group['id_grupo']]['_agents_unknown_'] = 0;
- $list[$group['id_grupo']]['_agents_critical_'] = 0;
- $list[$group['id_grupo']]['_total_agents_'] = 0;
- $list[$group['id_grupo']]["_monitor_checks_"] = 0;
- $list[$group['id_grupo']]["_monitor_not_normal_"] = 0;
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = 0;
- }
-
- if ($list_groups == false) {
- $list_groups = array();
- }
-
- if (is_metaconsole() || ($config["realtimestats"] == 0)) { // Agent cache
- $list = group_view_get_cache_stats ($list, $list_groups, $user_groups_ids);
- } else {
- foreach ($list_groups as $group) {
- // If id group is 0 get all accesses groups
- $group_id = $group['id_grupo'] == 0
- ? $user_groups_ids
- : $group['id_grupo'];
- $agent_not_init = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_NOT_INIT),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_not_init_'] = isset ($agent_not_init[0]['total']) ? $agent_not_init[0]['total'] : 0;
- $agent_unknown = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_UNKNOWN),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_unknown_'] = isset ($agent_unknown[0]['total']) ? $agent_unknown[0]['total'] : 0;
- $agent_critical = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo'],
- 'status' => AGENT_STATUS_CRITICAL),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_agents_critical_'] = isset ($agent_critical[0]['total']) ? $agent_critical[0]['total'] : 0;
- $agent_total = agents_get_agents(array (
- 'disabled' => 0,
- 'id_grupo' => $group['id_grupo']),
- array ('COUNT(DISTINCT id_agente) as total'), $access, false);
- $list[$group['id_grupo']]['_total_agents_'] = isset ($agent_total[0]['total']) ? $agent_total[0]['total'] : 0;
- $list[$group['id_grupo']]["_monitor_not_normal_"] = $list[$group['id_grupo']]["_monitor_checks_"] - $list[$group['id_grupo']]["_monitors_ok_"];
- $list[$group['id_grupo']]["_monitor_not_normal_"] = $list[$group['id_grupo']]["_monitor_checks_"] - $list[$group['id_grupo']]["_monitors_ok_"];
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = groupview_monitor_fired_alerts ($group['id_grupo'], $user_strict,$group['id_grupo']);
- $result_list = db_get_all_rows_sql("SELECT COUNT(*) as contado, estado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- LEFT JOIN tagent_secondary_group tasg
- ON tasg.id_agent = ta.id_agente
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.utimestamp > 0
- AND (
- ta.id_grupo IN (" . $group_id . ")
- OR tasg.id_group IN (" . $group_id . ")
- )
- GROUP BY estado");
- if ($result_list) {
- foreach ($result_list as $result) {
- switch ($result['estado']) {
- case AGENT_MODULE_STATUS_CRITICAL_BAD:
- $list[$group['id_grupo']]['_monitors_critical_'] = (int)$result['contado'];
- break;
- case AGENT_MODULE_STATUS_WARNING_ALERT:
- break;
- case AGENT_MODULE_STATUS_WARNING:
- $list[$group['id_grupo']]['_monitors_warning_'] = (int)$result['contado'];
- break;
- case AGENT_MODULE_STATUS_UNKNOWN:
- $list[$group['id_grupo']]['_monitors_unknown_'] = (int)$result['contado'];
- break;
- }
- }
- }
-
- $result_normal = db_get_row_sql("SELECT COUNT(*) as contado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- LEFT JOIN tagent_secondary_group tasg
- ON tasg.id_agent = ta.id_agente
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.estado = 0
- AND (tae.utimestamp > 0 OR tam.id_tipo_modulo IN(21,22,23,100))
- AND (
- ta.id_grupo IN (" . $group_id . ")
- OR tasg.id_group IN (" . $group_id . ")
- )
- GROUP BY estado");
- $list[$group['id_grupo']]['_monitors_ok_'] = isset ($result_normal['contado']) ? $result_normal['contado'] : 0;
-
- $result_not_init = db_get_row_sql("SELECT COUNT(*) as contado
- FROM tagente_estado tae INNER JOIN tagente ta
- ON tae.id_agente = ta.id_agente
- AND ta.disabled = 0
- LEFT JOIN tagent_secondary_group tasg
- ON tasg.id_agent = ta.id_agente
- INNER JOIN tagente_modulo tam
- ON tae.id_agente_modulo = tam.id_agente_modulo
- AND tam.disabled = 0
- WHERE tae.utimestamp = 0 AND
- tae.estado IN (".AGENT_MODULE_STATUS_NO_DATA.",".AGENT_MODULE_STATUS_NOT_INIT." )
- AND tam.id_tipo_modulo NOT IN (21,22,23,100)
- AND (
- ta.id_grupo IN (" . $group_id . ")
- OR tasg.id_group IN (" . $group_id . ")
- )
- GROUP BY estado");
- $list[$group['id_grupo']]['_monitors_not_init_'] = isset ($result_not_init['contado']) ? $result_not_init['contado'] : 0;
- }
- }
-
- return $list;
-}
-
-//Order the groups by parents
-function groupview_order_groups_for_parents ($view_groups) {
- $final_groups = array();
- // Index the groups
- $groups = array();
- foreach ($view_groups as $item) {
- $groups[$item['id_grupo']] = $item;
- }
- // Build the group hierarchy
- foreach ($groups as $id => $group) {
- $groups[$id]['have_parent'] = false;
- if (!isset($groups[$id]['parent']))
- continue;
- $parent = $groups[$id]['parent'];
- // Parent exists
- if (isset($groups[$parent])) {
- if (!isset($groups[$parent]['children']))
- $groups[$parent]['children'] = array();
- // Store a reference to the group into the parent
- $groups[$parent]['children'][] = &$groups[$id];
-
- // This group was introduced into a parent
- $groups[$id]['have_parent'] = true;
- }
- }
-
- // Sort the children groups
- for ($i = 0; $i < count($groups); $i++) {
- if (isset($groups[$i]['children']))
- usort($groups[$i]['children'], function ($a, $b) {
- return strcmp($a["nombre"], $b["nombre"]);
- });
- }
- // Extract the root groups
- foreach ($groups as $group) {
- if (!$group['have_parent'])
- $final_groups[] = $group;
- }
- // Sort the root groups
- usort($final_groups, function ($a, $b) {
- return strcmp($a["name"], $b["name"]);
- });
-
- return $final_groups;
-}
-
-function groupview_order_group_ids($groups, $ordered_ids){
+function groupview_plain_groups($groups) {
+ $group_result = array();
foreach ($groups as $group) {
+ $plain_child = array();
if (!empty($group['children'])) {
- $ordered_ids[$group['id_grupo']] = $group['nombre'];
- $ordered_ids = groupview_order_group_ids($group['children'], $ordered_ids);
- }
- else {
- $ordered_ids[$group['id_grupo']] = $group['nombre'];
+ $plain_child = groupview_plain_groups($group['children']);
+ unset($group['children']);
}
+ $group_result[] = $group;
+ $group_result = array_merge($group_result, $plain_child);
}
- return $ordered_ids;
+ return $group_result;
}
-//Function to eliminate duplicates groups in multidimensional array
-function groupview_array_unique_multidim($groups, $key){
- $temp_group = array();
- $i = 0;
- $key_group = array();
- foreach($groups as $group){
- if(!in_array($group[$key],$key_group)){
- $key_group[$i] = $group[$key];
- $temp_group[$i] = $group;
- }
- $i++;
- }
- return $temp_group;
+function groupview_get_modules_counters($groups_ids = false) {
+ if(empty($groups_ids)){
+ return array();
+ }
+
+ $groups_ids = implode(',', $groups_ids);
+ $table = is_metaconsole() ? 'tmetaconsole_agent' : 'tagente';
+ $table_sec = is_metaconsole()
+ ? 'tmetaconsole_agent_secondary_group'
+ : 'tagent_secondary_group';
+
+ $fields = array (
+ "g" ,
+ "SUM(module_normal) AS total_module_normal",
+ "SUM(module_critical) AS total_module_critical",
+ "SUM(module_warning) AS total_module_warning",
+ "SUM(module_unknown) AS total_module_unknown",
+ "SUM(module_not_init) AS total_module_not_init",
+ "SUM(module_alerts) AS total_module_alerts",
+ "SUM(module_total) AS total_module"
+ );
+
+ $fields_impl = implode(',', $fields);
+ $sql = "SELECT $fields_impl FROM
+ (
+ SELECT SUM(ta.normal_count) AS module_normal,
+ SUM(ta.critical_count) AS module_critical,
+ SUM(ta.warning_count) AS module_warning,
+ SUM(ta.unknown_count) AS module_unknown,
+ SUM(ta.notinit_count) AS module_not_init,
+ SUM(ta.fired_count) AS module_alerts,
+ SUM(ta.total_count) AS module_total,
+ ta.id_grupo AS g
+ FROM $table ta
+ WHERE ta.id_grupo IN ($groups_ids)
+ GROUP BY ta.id_grupo
+ UNION ALL
+ SELECT SUM(ta.normal_count) AS module_normal,
+ SUM(ta.critical_count) AS module_critical,
+ SUM(ta.warning_count) AS module_warning,
+ SUM(ta.unknown_count) AS module_unknown,
+ SUM(ta.notinit_count) AS module_not_init,
+ SUM(ta.fired_count) AS module_alerts,
+ SUM(ta.total_count) AS module_total,
+ tasg.id_group AS g
+ FROM $table ta
+ INNER JOIN $table_sec tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE tasg.id_group IN ($groups_ids)
+ GROUP BY tasg.id_group
+ ) x GROUP BY g";
+ return db_get_all_rows_sql($sql);
}
-/**
- * Get the stats to group view using the cache
- *
- * @param array Skeleton to fill with the group information
- * @param array Groups information
- * @param string Groups that user has access separated by commas
- */
-function group_view_get_cache_stats ($list, $list_groups, $user_groups_ids) {
+function groupview_get_all_counters($tree_group) {
+ $all_name = __("All");
+ $group_acl = $tree_group->getGroupAclCondition();
+ $table = is_metaconsole() ? 'tmetaconsole_agent' : 'tagente';
+ $table_sec = is_metaconsole()
+ ? 'tmetaconsole_agent_secondary_group'
+ : 'tagent_secondary_group';
+ $sql =
+ "SELECT SUM(ta.normal_count) AS _monitors_ok_,
+ SUM(ta.critical_count) AS _monitors_critical_,
+ SUM(ta.warning_count) AS _monitors_warning_,
+ SUM(ta.unknown_count) AS _monitors_unknown_,
+ SUM(ta.notinit_count) AS _monitors_not_init_,
+ SUM(ta.fired_count) AS _monitors_alerts_fired_,
+ SUM(ta.total_count) AS _monitor_checks_,
+ SUM(IF(ta.critical_count > 0, 1, 0)) AS _agents_critical_,
+ SUM(IF(ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count > 0, 1, 0)) AS _agents_unknown_,
+ SUM(IF(ta.total_count = ta.notinit_count, 1, 0)) AS _agents_not_init_,
+ COUNT(ta.id_agente) AS _total_agents_,
+ '$all_name' AS _name_,
+ 0 AS _id_,
+ '' AS _icon_
+ FROM $table ta
+ WHERE ta.disabled = 0
+ AND ta.id_agente IN (
+ SELECT ta.id_agente FROM $table ta
+ LEFT JOIN $table_sec tasg
+ ON ta.id_agente = tasg.id_agent
+ WHERE ta.disabled = 0
+ $group_acl
+ GROUP BY ta.id_agente
+ )
+ ";
+ $data = db_get_row_sql($sql);
+ $data["_monitor_not_normal_"] = $data["_monitor_checks_"] - $data["_monitors_ok_"];
+ return $data;
+}
- $table_agent = 'tagente';
- $table_secondary = 'tagent_secondary_group';
- // Change the metaconsole tables
- if (is_metaconsole()) {
- $table_agent = 'tmetaconsole_agent';
- $table_secondary = 'tmetaconsole_agent_secondary_group';
+function groupview_get_groups_list($id_user = false, $access = 'AR', $is_not_paginated = false) {
+ global $config;
+ if ($id_user == false) {
+ $id_user = $config['id_user'];
}
- // Walk for each group
- foreach ($list_groups as $group) {
- // If id group is 0 get all accesses groups
- $group_id = $group['id_grupo'] == 0
- ? $user_groups_ids
- : $group['id_grupo'];
- $group_agents = db_get_row_sql("SELECT SUM(warning_count) AS _monitors_warning_,
- SUM(critical_count) AS _monitors_critical_,
- SUM(normal_count) AS _monitors_ok_,
- SUM(unknown_count) AS _monitors_unknown_,
- SUM(notinit_count) AS _monitors_not_init_,
- SUM(fired_count) AS _monitors_alerts_fired_,
- COUNT(*) AS _total_agents_, id_grupo, intervalo,
- ultimo_contacto, disabled
- FROM $table_agent ta
- LEFT JOIN $table_secondary tasg
- ON tasg.id_agent = ta.id_agente
- WHERE (
- ta.id_grupo IN (" . $group_id . ")
- OR tasg.id_group IN (" . $group_id . ")
- )
- AND disabled = 0");
+ $tree_group = new TreeGroup("group", "group");
+ $tree_group->setPropagateCounters(false);
+ $tree_group->setFilter( array(
+ 'searchAgent' => '',
+ 'statusAgent' => AGENT_STATUS_ALL,
+ 'searchModule' => '',
+ 'statusModule' => -1,
+ 'groupID' => 0,
+ 'tagID' => 0,
+ 'show_not_init_agents' => 1,
+ 'show_not_init_modules' => 1
+ ));
+ $info = $tree_group->getArray();
+ $info = groupview_plain_groups($info);
+ $counter = count($info);
- $list[$group['id_grupo']]['_monitors_critical_'] = (int)$group_agents['_monitors_critical_'];
- $list[$group['id_grupo']]['_monitors_warning_'] = (int)$group_agents['_monitors_warning_'];
- $list[$group['id_grupo']]['_monitors_unknown_'] = (int)$group_agents['_monitors_unknown_'];
- $list[$group['id_grupo']]['_monitors_not_init_'] = (int)$group_agents['_monitors_not_init_'];
- $list[$group['id_grupo']]['_monitors_ok_'] = (int)$group_agents['_monitors_ok_'];
- $list[$group['id_grupo']]['_monitors_alerts_fired_'] = (int)$group_agents['_monitors_alerts_fired_'];
- $list[$group['id_grupo']]['_total_agents_'] = (int)$group_agents['_total_agents_'];
- $list[$group['id_grupo']]["_monitor_checks_"] = $list[$group['id_grupo']]["_monitors_not_init_"]
- + $list[$group['id_grupo']]["_monitors_unknown_"]
- + $list[$group['id_grupo']]["_monitors_warning_"]
- + $list[$group['id_grupo']]["_monitors_critical_"]
- + $list[$group['id_grupo']]["_monitors_ok_"];
+ $offset = get_parameter('offset', 0);
+ $groups_view = $is_not_paginated
+ ? $info
+ : array_slice($info, $offset, $config['block_size']);
+ $agents_counters = array_reduce($groups_view, function($carry, $item){
+ $carry[$item['id']] = $item;
+ return $carry;
+ }, array());
- if ($group['icon'])
- $list[$group['id_grupo']]["_iconImg_"] = html_print_image ("images/".$group['icon'].".png", true, array ("style" => 'vertical-align: middle;'));
+ $modules_counters = groupview_get_modules_counters(array_keys($agents_counters));
+ $modules_counters = array_reduce($modules_counters, function($carry, $item){
+ $carry[$item['g']] = $item;
+ return $carry;
+ }, array());
- // Calculate not_normal monitors
- $list[$group['id_grupo']]["_monitor_not_normal_"] = $list["_monitor_checks_"] - $list["_monitors_ok_"];
+ $total_counters = array();
- $total_agents = $list[$group['id_grupo']]['_total_agents_'];
+ foreach ($agents_counters as $id_group => $agent_counter) {
+ $list[$id_group]['_name_'] = $agent_counter['name'];
+ $list[$id_group]['_id_'] = $agent_counter['id'];
+ $list[$id_group]['_iconImg_'] = $agent_counter['icon'];
- if ($total_agents > 0) {
- $agents = db_get_all_rows_sql(sprintf ("SELECT warning_count,
- critical_count,
- normal_count,
- unknown_count,
- notinit_count,
- fired_count,
- disabled
- FROM $table_agent ta
- LEFT JOIN $table_secondary tasg
- ON ta.id_agente = tasg.id_agent
- WHERE ta.id_grupo IN (%s) OR tasg.id_group IN (%s)",
- $group_id, $group_id));
- foreach ($agents as $agent) {
- if ($agent['critical_count'] > 0) {
- $list[$group['id_grupo']]['_agents_critical_'] += 1;
- }
- else {
- if (($agent['critical_count'] == 0) && ($agent['warning_count'] == 0) && ($group_agents['disabled'] == 0) && ($agent['normal_count'] == 0)) {
- if ($agent['unknown_count'] > 0) {
- $list[$group['id_grupo']]['_agents_unknown_'] += 1;
- }
- }
- if (($agent['critical_count'] == 0) && ($agent['warning_count'] == 0) && ($group_agents['disabled'] == 0) && ($agent['normal_count'] == 0) && ($agent['unknown_count'] == 0)) {
- if ($agent['notinit_count'] > 0) {
- $list[$group['id_grupo']]['_agents_not_init_'] += 1;
- }
- }
- }
- }
- }
+ $list[$id_group]['_agents_not_init_'] = $agent_counter['counters']['not_init'];
+ $list[$id_group]['_agents_unknown_'] = $agent_counter['counters']['unknown'];
+ $list[$id_group]['_agents_critical_'] = $agent_counter['counters']['critical'];
+ $list[$id_group]['_total_agents_'] = $agent_counter['counters']['total'];
+
+ $list[$id_group]['_monitors_critical_'] = (int)$modules_counters[$id_group]['total_module_critical'];
+ $list[$id_group]['_monitors_warning_'] = (int)$modules_counters[$id_group]['total_module_warning'];
+ $list[$id_group]['_monitors_unknown_'] = (int)$modules_counters[$id_group]['total_module_unknown'];
+ $list[$id_group]['_monitors_not_init_'] = (int)$modules_counters[$id_group]['total_module_not_init'];
+ $list[$id_group]['_monitors_ok_'] = (int)$modules_counters[$id_group]['total_module_normal'];
+ $list[$id_group]["_monitor_checks_"] = (int)$modules_counters[$id_group]['total_module'];
+ $list[$id_group]["_monitor_not_normal_"] = $list[$group['id_grupo']]["_monitor_checks_"] - $list[$group['id_grupo']]['_monitors_ok_'];
+ $list[$id_group]['_monitors_alerts_fired_'] = (int)$modules_counters[$id_group]['total_module_alerts'];
}
- return $list;
+
+ array_unshift($list, groupview_get_all_counters($tree_group));
+ return array(
+ 'groups' => $list,
+ 'counter' => $counter
+ );
}
?>
diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php
index a941a96790..932e8a3457 100644
--- a/pandora_console/include/functions_html.php
+++ b/pandora_console/include/functions_html.php
@@ -47,13 +47,13 @@ else{
/**
* Prints the print_r with < pre > tags
*/
-function html_debug_print ($var, $file = '') {
+function html_debug_print ($var, $file = '', $oneline = false) {
$more_info = '';
if (is_string($var)) {
$more_info = 'size: ' . strlen($var);
}
elseif (is_bool($var)) {
- $more_info = 'val: ' .
+ $more_info = 'val: ' .
($var ? 'true' : 'false');
}
elseif (is_null($var)) {
@@ -62,10 +62,13 @@ function html_debug_print ($var, $file = '') {
elseif (is_array($var)) {
$more_info = count($var);
}
-
+
if ($file === true)
$file = '/tmp/logDebug';
-
+
+ if($oneline && is_string($var))
+ $var = preg_replace("/[\t|\n| ]+/", " ", $var);
+
if (strlen($file) > 0) {
$f = fopen($file, "a");
ob_start();
@@ -85,8 +88,13 @@ function html_debug_print ($var, $file = '') {
}
// Alias for "html_debug_print"
-function html_debug ($var, $file = '') {
- html_debug_print ($var, $file);
+function html_debug ($var, $file = '', $oneline = false) {
+ html_debug_print ($var, $file, $oneline);
+}
+
+// Alias for "html_debug_print"
+function hd ($var, $file = '', $oneline = false) {
+ html_debug_print ($var, $file, $oneline);
}
function html_f2str($function, $params) {
@@ -704,37 +712,36 @@ function html_print_extended_select_for_post_process($name, $selected = '',
$script = '', $nothing = '', $nothing_value = '0', $size = false,
$return = false, $select_style = false, $unique_name = true,
$disabled = false, $no_change = 0) {
-
+
global $config;
-
+
require_once($config['homedir'] . "/include/functions_post_process.php");
-
-
+
$fields = post_process_get_custom_values();
+
if($no_change != 0){
$fields[-1] = __('No change');
}
$selected_float = (float)$selected;
$found = false;
-
- if (array_key_exists($selected, $fields))
+
+ if (array_key_exists(number_format($selected, 14, '.', ','), $fields))
$found = true;
-
+
if (!$found) {
$fields[$selected] = floatval($selected);
}
-
-
+
if ($unique_name === true) {
$uniq_name = uniqid($name);
}
else {
$uniq_name = $name;
}
-
+
ob_start();
-
+
echo '';
html_print_select ($fields, $uniq_name . '_select', $selected,
"" . $script, $nothing, $nothing_value, false, false, false,
@@ -747,10 +754,10 @@ function html_print_extended_select_for_post_process($name, $selected = '',
'style' => 'width: 18px;')) .
'';
echo '
';
-
+
echo '';
html_print_input_text ($uniq_name . '_text', $selected, '', 20);
-
+
html_print_input_hidden($name, $selected, false, $uniq_name);
echo '
' .
html_print_image('images/default_list.png', true,
@@ -759,20 +766,17 @@ function html_print_extended_select_for_post_process($name, $selected = '',
'title' => __('List'),
'style' => 'width: 18px;')) . '';
echo '
';
-
+
echo "";
-
+
$returnString = ob_get_clean();
-
-
-
-
+
if ($return)
return $returnString;
else
@@ -2462,4 +2466,70 @@ function html_print_timezone_select ($name, $selected = "") {
return html_print_select($timezones, $name, $selected, "", __("None"), "", true, false, false);
}
+/**
+ * Enclose a text into a result_div
+ *
+ * @param string Text to enclose
+ *
+ * @return string Text inside the result_div
+ */
+function html_print_result_div ($text) {
+ $text = preg_replace ('/', '<', $text);
+ $text = preg_replace ('/>/', '>', $text);
+ $text = preg_replace ('/\n/i','
',$text);
+ $text = preg_replace ('/\s/i',' ',$text);
+
+ $enclose = "";
+ $enclose .= $text;
+ $enclose .= "
";
+ return $enclose;
+}
+
+/**
+ * Print order arrows links
+ *
+ * @param array Base tags to build url
+ * @param string Order key to add to URL
+ * @param string Value to sort ascendent
+ * @param string Value to sort descendent
+ *
+ * @return string HTML code to display both arrows.
+ */
+function html_print_sort_arrows ($params, $order_tag, $up = 'up', $down = 'down') {
+ // Build the queries
+ $params[$order_tag] = $up;
+ $url_up = "index.php?" . http_build_query($params, '', '&');
+ $params[$order_tag] = $down;
+ $url_down = "index.php?" . http_build_query($params, '', '&');
+
+ // Build the links
+ return ' ' .
+ '' .
+ html_print_image("images/sort_up.png", true) .
+ '' .
+ '' .
+ html_print_image("images/sort_down.png", true) .
+ ''
+ ;
+}
+
+/**
+ * Print an input hidden with a new csrf token generated
+ */
+function html_print_csrf_hidden () {
+ html_print_input_hidden('csrf_code', generate_csrf_code());
+}
+
+/**
+ * Print an error if csrf is incorrect
+ */
+function html_print_csrf_error () {
+ if (validate_csrf_code()) return false;
+
+ ui_print_error_message (
+ __('%s cannot verify the origin of the request. Try again, please.',
+ get_product_name())
+ );
+ return true;
+}
?>
diff --git a/pandora_console/include/functions_modules.php b/pandora_console/include/functions_modules.php
index 59e88d9cdf..1349b6dadd 100755
--- a/pandora_console/include/functions_modules.php
+++ b/pandora_console/include/functions_modules.php
@@ -441,9 +441,9 @@ function modules_update_agent_module ($id, $values,
}
$result = @db_process_sql_update ('tagente_modulo', $values, $where);
-
+
if ($result == false) {
- if ($result_disable == ERR_GENERIC ){
+ if ($result_disable === ERR_GENERIC ){
return ERR_DB;
}
else{
@@ -476,7 +476,7 @@ function modules_create_agent_module ($id_agent, $name, $values = false, $disabl
global $config;
if (!$disableACL) {
- if (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;
}
@@ -537,51 +537,20 @@ function modules_create_agent_module ($id_agent, $name, $values = false, $disabl
// Sync modules start in unknown status
$status = AGENT_MODULE_STATUS_NO_DATA;
}
- switch ($config["dbtype"]) {
- case "mysql":
- $result = db_process_sql_insert ('tagente_estado',
- array ('id_agente_modulo' => $id_agent_module,
- 'datos' => 0,
- 'timestamp' => '01-01-1970 00:00:00',
- 'estado' => $status,
- 'known_status' => $status,
- 'id_agente' => (int) $id_agent,
- 'utimestamp' => 0,
- 'status_changes' => 0,
- 'last_status' => $status,
- 'last_known_status' => $status
- ));
- break;
- case "postgresql":
- $result = db_process_sql_insert ('tagente_estado',
- array ('id_agente_modulo' => $id_agent_module,
- 'datos' => 0,
- 'timestamp' => null,
- 'estado' => $status,
- 'known_status' => $status,
- 'id_agente' => (int) $id_agent,
- 'utimestamp' => 0,
- 'status_changes' => 0,
- 'last_status' => $status,
- 'last_known_status' => $status
- ));
- break;
- case "oracle":
- $result = db_process_sql_insert ('tagente_estado',
- array ('id_agente_modulo' => $id_agent_module,
- 'datos' => 0,
- 'timestamp' => '#to_date(\'1970-01-01 00:00:00\', \'YYYY-MM-DD HH24:MI:SS\')',
- 'estado' => $status,
- 'known_status' => $status,
- 'id_agente' => (int) $id_agent,
- 'utimestamp' => 0,
- 'status_changes' => 0,
- 'last_status' => $status,
- 'last_known_status' => $status
- ));
- break;
- }
-
+
+ $result = db_process_sql_insert ('tagente_estado', array (
+ 'id_agente_modulo' => $id_agent_module,
+ 'datos' => 0,
+ 'timestamp' => '01-01-1970 00:00:00',
+ 'estado' => $status,
+ 'known_status' => $status,
+ 'id_agente' => (int) $id_agent,
+ 'utimestamp' => 0,
+ 'status_changes' => 0,
+ 'last_status' => $status,
+ 'last_known_status' => $status
+ ));
+
if ($result === false) {
db_process_sql_delete ('tagente_modulo',
array ('id_agente_modulo' => $id_agent_module));
@@ -758,34 +727,7 @@ function modules_format_delete_log4x($id)
* @return array An array with module information
*/
function modules_get_agentmodule ($id_agentmodule) {
- global $config;
-
- switch ($config['dbtype']) {
- case "mysql":
- case "postgresql":
- return db_get_row ('tagente_modulo', 'id_agente_modulo', (int) $id_agentmodule);
- break;
- case "oracle":
- $fields = db_get_all_rows_filter('USER_TAB_COLUMNS',
- 'TABLE_NAME = \'TAGENTE_MODULO\' AND COLUMN_NAME <> \'MAX_CRITICAL\' AND COLUMN_NAME <> \'MIN_CRITICAL\' AND COLUMN_NAME <> \'POST_PROCESS\' AND COLUMN_NAME <> \'MAX_WARNING\' AND COLUMN_NAME <> \'MIN_WARNING\'', 'COLUMN_NAME');
- foreach ($fields as $field) {
- $fields_[] = $field['column_name'];
- }
- $fields = implode(',', $fields_);
-
- $result = db_process_sql("
- SELECT TO_NUMBER(MAX_CRITICAL) as max_critical,
- TO_NUMBER(MIN_CRITICAL) as min_critical,
- TO_NUMBER(MAX_WARNING) as max_warning,
- TO_NUMBER(MIN_WARNING) as min_warning,
- TO_NUMBER(POST_PROCESS) as post_process,
- " . $fields . "
- FROM tagente_modulo
- WHERE id_agente_modulo = " . $id_agentmodule);
-
- return $result[0];
- break;
- }
+ return db_get_row ('tagente_modulo', 'id_agente_modulo', (int) $id_agentmodule);
}
function modules_get_table_data($id_agent_module) {
@@ -838,14 +780,14 @@ function modules_get_raw_data($id_agent_module, $date_init, $date_end) {
return $data;
}
-function modules_get_agent_group($id_agent_module) {
+function modules_get_agent_groups($id_agent_module) {
$return = false;
$id_agent = modules_get_agentmodule_agent(
$id_agent_module);
if (!empty($id_agent)) {
- $return = agents_get_agent_group($id_agent);
+ $return = agents_get_all_groups_agent($id_agent);
}
return $return;
@@ -1999,8 +1941,6 @@ function modules_get_status($id_agent_module, $db_status, $data, &$status, &$tit
// Get unknown agents by using the status code in modules
function modules_agents_unknown ($module_name) {
-
- //TODO REVIEW ORACLE AND POSTGRES
return db_get_sql ("SELECT COUNT( DISTINCT tagente.id_agente)
FROM tagente_estado, tagente, tagente_modulo
WHERE tagente.disabled = 0
@@ -2022,8 +1962,6 @@ function modules_agents_ok ($module_name) {
//This query grouped all modules by agents and select the MAX value for status which has the value 0
//If MAX(estado) is 0 it means all modules has status 0 => OK
//Then we count the agents of the group selected to know how many agents are in OK status
-
- //TODO REVIEW ORACLE AND POSTGRES
return db_get_sql ("SELECT COUNT(max_estado)
FROM (
SELECT MAX(tagente_estado.estado) as max_estado
@@ -2046,9 +1984,7 @@ function modules_agents_critical ($module_name) {
//The status values are: 0 OK; 1 Critical; 2 Warning; 3 Unkown
//If estado = 1 it means at leas 1 module is in critical status so the agent is critical
//Then we count the agents of the group selected to know how many agents are in critical status
-
- //TODO REVIEW ORACLE AND POSTGRES
-
+
return db_get_sql ("SELECT COUNT( DISTINCT tagente_estado.id_agente)
FROM tagente_estado, tagente, tagente_modulo
WHERE tagente.disabled = 0 AND tagente_estado.utimestamp != 0
@@ -2070,8 +2006,6 @@ function modules_agents_warning ($module_name) {
//If MIN(estado) is 2 it means at least one module is warning and there is no critical modules
//Then we count the agents of the group selected to know how many agents are in warning status
- //TODO REVIEW ORACLE AND POSTGRES
-
return db_get_sql ("SELECT COUNT(min_estado)
FROM (SELECT MAX(tagente_estado.estado) as min_estado
FROM tagente_estado, tagente, tagente_modulo
@@ -2753,8 +2687,14 @@ function get_module_realtime_link_graph ($module) {
* with some user action through the console
* @param int New status
* @param int Agent module to force new status
+ * @param int Agent id to force state recalculations
*/
-function force_set_module_status ($status, $id_agent_module) {
+function force_set_module_status ($status, $id_agent_module, $id_agent) {
+ // Force recalculate counters
+ db_process_sql_update('tagente',
+ array('update_module_count' => 1),
+ array('id_agente' => $id_agent)
+ );
return db_process_sql_update( 'tagente_estado',
array(
'estado' => $status,
@@ -2764,4 +2704,114 @@ function force_set_module_status ($status, $id_agent_module) {
array('id_agente_modulo' => $id_agent_module)
);
}
-?>
+function modules_get_modules_status ($mod_status_id) {
+
+ $diferent_types = get_priorities ();
+
+ $mod_status_desc = '';
+ switch ($mod_status_id) {
+ case AGENT_MODULE_STATUS_NORMAL:
+ $mod_status_desc = __('NORMAL');
+ break;
+ case AGENT_MODULE_STATUS_CRITICAL_BAD:
+ $mod_status_desc = __('CRITICAL');
+ break;
+ case AGENT_MODULE_STATUS_WARNING:
+ $mod_status_desc = __('WARNING');
+ break;
+ case AGENT_MODULE_STATUS_UNKNOWN:
+ $mod_status_desc = __('UNKNOWN');
+ break;
+ case AGENT_MODULE_STATUS_NOT_INIT:
+ $mod_status_desc = __('NOT INIT');
+ break;
+ case AGENT_MODULE_STATUS_ALL:
+ $mod_status_desc = __('ALL');
+ break;
+ case AGENT_MODULE_STATUS_CRITICAL_ALERT:
+ $mod_status_desc = __('CRITICAL');
+ break;
+ case AGENT_MODULE_STATUS_NO_DATA:
+ $mod_status_desc = __('NO DATA');
+ break;
+ case AGENT_MODULE_STATUS_NORMAL_ALERT:
+ $mod_status_desc = __('NORMAL');
+ break;
+ case AGENT_MODULE_STATUS_NOT_NORMAL:
+ $mod_status_desc = __('NOT NORMAL');
+ break;
+ case AGENT_MODULE_STATUS_WARNING_ALERT:
+ $mod_status_desc = __('WARNING');
+ break;
+ default:
+ if (isset($config['text_char_long'])) {
+ foreach ($diferent_types as $key => $type) {
+ if ($key == $mod_status_id) {
+ $mod_status_desc = ui_print_truncate_text($type,
+ $config['text_char_long'], false, true, false);
+ }
+ }
+ }
+ break;
+ }
+
+ return $mod_status_desc;
+}
+
+function modules_get_counter_by_states($state) {
+ switch ($state) {
+ case AGENT_MODULE_STATUS_CRITICAL_ALERT:
+ case AGENT_MODULE_STATUS_CRITICAL_BAD:
+ return "critical_count";
+ case AGENT_MODULE_STATUS_WARNING_ALERT:
+ case AGENT_MODULE_STATUS_WARNING:
+ return "warning_count";
+ break;
+ case AGENT_MODULE_STATUS_UNKNOWN:
+ return "unknown_count";
+ case AGENT_MODULE_STATUS_NO_DATA:
+ case AGENT_MODULE_STATUS_NOT_INIT:
+ return "notinit_count";
+ case AGENT_MODULE_STATUS_NORMAL_ALERT:
+ case AGENT_MODULE_STATUS_NORMAL:
+ return "normal_count";
+ }
+
+ // If the state is not an expected state, return condition
+ // to not show any data
+ return false;
+}
+
+function modules_get_state_condition($state) {
+ switch ($state) {
+ case AGENT_MODULE_STATUS_CRITICAL_ALERT:
+ case AGENT_MODULE_STATUS_CRITICAL_BAD:
+ return "(
+ tae.estado = ".AGENT_MODULE_STATUS_CRITICAL_ALERT."
+ OR tae.estado = ".AGENT_MODULE_STATUS_CRITICAL_BAD."
+ )";
+ case AGENT_MODULE_STATUS_WARNING_ALERT:
+ case AGENT_MODULE_STATUS_WARNING:
+ return "(
+ tae.estado = ".AGENT_MODULE_STATUS_WARNING_ALERT."
+ OR tae.estado = ".AGENT_MODULE_STATUS_WARNING."
+ )";
+ case AGENT_MODULE_STATUS_UNKNOWN:
+ return "tae.estado = ".AGENT_MODULE_STATUS_UNKNOWN." ";
+ case AGENT_MODULE_STATUS_NO_DATA:
+ case AGENT_MODULE_STATUS_NOT_INIT:
+ return "(
+ tae.estado = ".AGENT_MODULE_STATUS_NO_DATA."
+ OR tae.estado = ".AGENT_MODULE_STATUS_NOT_INIT."
+ )";
+ case AGENT_MODULE_STATUS_NORMAL_ALERT:
+ case AGENT_MODULE_STATUS_NORMAL:
+ return "(
+ tae.estado = ".AGENT_MODULE_STATUS_NORMAL_ALERT."
+ OR tae.estado = ".AGENT_MODULE_STATUS_NORMAL."
+ )";
+ }
+ // If the state is not an expected state, return no condition
+ return "1=1";
+}
+?>
\ No newline at end of file
diff --git a/pandora_console/include/functions_profile.php b/pandora_console/include/functions_profile.php
index 4876969d9e..62306ec060 100644
--- a/pandora_console/include/functions_profile.php
+++ b/pandora_console/include/functions_profile.php
@@ -68,7 +68,7 @@ function profile_get_profiles ($filter = false) {
* @param int Group ID (default 1 => All)
* @param string Assign User who assign the profile to user.
* @param string tags where the view of the user in this group will be restricted
- * @param bool Profile is secondary or not
+ * @param bool Profile is marked to not provide hierarchy
*
* @return mixed Number id if succesful, false if not
*/
@@ -77,7 +77,7 @@ function profile_create_user_profile ($id_user,
$id_group = 0,
$assignUser = false,
$tags = '',
- $is_secondary = false
+ $no_hierarchy = false
) {
global $config;
@@ -86,7 +86,7 @@ function profile_create_user_profile ($id_user,
return false;
// Secondary server is an enterprise function
- if (!enterprise_installed() && $is_secondary) return false;
+ if (!enterprise_installed() && $no_hierarchy) return false;
// Checks if the user exists
$result_user = users_get_user_by_id($id_user);
@@ -95,9 +95,6 @@ function profile_create_user_profile ($id_user,
return false;
}
- // Cannot mix secondary and primary profiles
- if (!profile_check_group_mode($id_user, $id_group, $is_secondary)) return false;
-
if (isset ($config["id_user"])) {
//Usually this is set unless we call it while logging in (user known by auth scheme but not by pandora)
$assign = $config["id_user"];
@@ -114,7 +111,7 @@ function profile_create_user_profile ($id_user,
"id_grupo" => $id_group,
"tags" => $tags,
"assigned_by" => $assign,
- "is_secondary" => $is_secondary ? 1 : 0
+ "no_hierarchy" => $no_hierarchy ? 1 : 0
);
return db_process_sql_insert ("tusuario_perfil", $insert);
@@ -147,35 +144,16 @@ function profile_delete_profile ($id_profile) {
return (bool)db_process_sql_delete('tperfil', array('id_perfil' => $id_profile));
}
-/**
- * Check if a group can be added being secondary or normal
- *
- * @param int User ID you want to check
- * @param int Group ID you want to check
- * @param bool Mode of profile will be inserted
- *
- * @return bool False if there is a group with the mode already added
- */
-function profile_check_group_mode($user_id, $group_id, $is_secondary) {
- $inserted_type = (int)db_get_value_sql(sprintf(
- 'SELECT COUNT(*) FROM tusuario_perfil WHERE
- id_grupo=%d AND is_secondary=%d AND id_usuario="%s"',
- $group_id, !$is_secondary ? 1 : 0, $user_id)
- );
- return $inserted_type === 0;
-}
-
/**
* Print the table to display, create and delete profiles
*
* @param int User id
- * @param string Title of the table view
* @param bool Show the tags select or not
*/
-function profile_print_profile_table ($id, $title, $is_secondary = false) {
+function profile_print_profile_table ($id) {
global $config;
- $is_secondary = enterprise_installed() ? $is_secondary : false;
+ $title = __('Profiles/Groups assigned to this user');
$table = new stdClass();
$table->width = '100%';
@@ -196,17 +174,15 @@ function profile_print_profile_table ($id, $title, $is_secondary = false) {
$table->style[0] = 'font-weight: bold';
$table->style[1] = 'font-weight: bold';
}
- $table->head[0] = __('Profile name');
- $table->head[1] = __('Group');
- if (!$is_secondary) {
- $table->head[2] = __('Tags');
- }
- $table->head[3] = __('Action');
- $table->align[3] = 'center';
+ $table->head["name"] = __('Profile name');
+ $table->head["group"] = __('Group');
+ $table->head["tags"] = __('Tags');
+ $table->head["hierarchy"] = __('No hierarchy');
+ $table->head["actions"] = __('Action');
+ $table->align["actions"] = 'center';
$result = db_get_all_rows_filter ("tusuario_perfil", array (
- "id_usuario" => $id,
- "is_secondary" => $is_secondary ? 1 : 0
+ "id_usuario" => $id
));
if ($result === false) {
@@ -220,67 +196,64 @@ function profile_print_profile_table ($id, $title, $is_secondary = false) {
$data = array ();
- $data[0] = ''.profile_get_name ($profile['id_perfil']).'';
- $data[1] = ui_print_group_icon($profile["id_grupo"], true);
+ $data["name"] = ''.profile_get_name ($profile['id_perfil']).'';
+ $data["group"] = ui_print_group_icon($profile["id_grupo"], true);
if (!defined('METACONSOLE')) {
- $data[1] .= '';
+ $data["group"] .= '';
}
- $data[1] .= ' ' . ui_print_truncate_text(groups_get_name ($profile['id_grupo'], True), GENERIC_SIZE_TEXT);
- if (!defined('METACONSOLE'))
- $data[1] .= '';
+ $data["group"] .= ' ' . ui_print_truncate_text(groups_get_name ($profile['id_grupo'], True), GENERIC_SIZE_TEXT);
+ if (!defined('METACONSOLE')) $data["group"] .= '';
- if (!$is_secondary) {
- if(empty($profile["tags"])) {
- $data[2] = '';
- }
- else {
- $tags_ids = explode(',',$profile["tags"]);
- $tags = tags_get_tags($tags_ids);
- $data[2] = tags_get_tags_formatted($tags);
- }
+ if(empty($profile["tags"])) {
+ $data["tags"] = '';
+ }
+ else {
+ $tags_ids = explode(',',$profile["tags"]);
+ $tags = tags_get_tags($tags_ids);
+ $data["tags"] = tags_get_tags_formatted($tags);
}
- $data[3] = '';
+ $data["hierarchy"] = $profile['no_hierarchy'] ? __("Yes") : __("No");
+
+ $data["actions"] = '';
array_push ($table->data, $data);
}
$data = array ();
- $data[0] = '';
+ $data["hierarchy"] = html_print_checkbox ('no_hierarchy', 1, false, true) .
+ ui_print_help_icon("no_hierarchy", true);
+
+ $data["actions"] = html_print_input_image ('add', 'images/add.png', 1, '', true);
+ $data["actions"] .= html_print_input_hidden ('id', $id, true);
+ $data["actions"] .= html_print_input_hidden ('add_profile', 1, true);
+ $data["actions"] .= '';
array_push ($table->data, $data);
diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php
index 81938d66c9..1f019934e9 100755
--- a/pandora_console/include/functions_reporting.php
+++ b/pandora_console/include/functions_reporting.php
@@ -395,7 +395,8 @@ function reporting_make_reporting_data($report = null, $id_report,
$content,
$type,
$force_width_chart,
- $force_height_chart);
+ $force_height_chart
+ );
break;
case 'netflow_area':
$report['contents'][] = reporting_netflow(
@@ -628,7 +629,6 @@ function reporting_make_reporting_data($report = null, $id_report,
}
$index_content++;
}
-
return reporting_check_structure_report($report);
}
@@ -1552,7 +1552,7 @@ function reporting_event_report_group($report, $content,
function reporting_event_report_module($report, $content,
$type = 'dinamic', $force_width_chart = null,
$force_height_chart = null, $pdf=0) {
-
+
global $config;
if($pdf){
@@ -1563,20 +1563,29 @@ function reporting_event_report_module($report, $content,
}
$return['type'] = 'event_report_module';
-
+
if (empty($content['name'])) {
$content['name'] = __('Event Report Module');
}
-
+
+ $id_server = false;
+ if(is_metaconsole()){
+ $id_server = metaconsole_get_id_server($content["server_name"]);
+ 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']));
+ $return['subtitle'] = agents_get_alias($content['id_agent']) . " - " .
+ io_safe_output(modules_get_agentmodule_name($content['id_agent_module']));
+
+ if(is_metaconsole()){
+ metaconsole_restore_db();
+ }
+
$return["description"] = $content["description"];
$return["date"] = reporting_get_date_text($report, $content);
$return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : '';
-
+
$event_filter = $content['style'];
$return['show_summary_group'] = $event_filter['show_summary_group'];
//filter
@@ -1585,22 +1594,18 @@ function reporting_event_report_module($report, $content,
$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_validated_vs_unvalidated = $event_filter['event_graph_validated_vs_unvalidated'];
-
- $id_server = false;
- if(is_metaconsole()){
- $id_server = metaconsole_get_id_server($content["server_name"]);
- }
+
//data events
$data = reporting_get_module_detailed_event (
- $content['id_agent_module'], $content['period'], $report["datetime"],
- $show_summary_group, $filter_event_severity, $filter_event_type,
+ $content['id_agent_module'], $content['period'], $report["datetime"],
+ $show_summary_group, $filter_event_severity, $filter_event_type,
$filter_event_status, $filter_event_filter_search, $force_width_chart,
- $event_graph_by_user_validator, $event_graph_by_criticity,
+ $event_graph_by_user_validator, $event_graph_by_criticity,
$event_graph_validated_vs_unvalidated, $ttl, $id_server);
if (empty($data)) {
@@ -1608,7 +1613,7 @@ function reporting_event_report_module($report, $content,
}
else {
$return['data'] = array_reverse($data);
- }
+ }
if ($config['metaconsole']) {
metaconsole_restore_db();
@@ -1621,7 +1626,7 @@ function reporting_event_report_module($report, $content,
else{
$return['total_events'] = 0;
}
-
+
return reporting_check_structure_content($return);
}
@@ -2807,18 +2812,17 @@ function agents_get_network_interfaces_array(
$row_interface['chart'] = null;
$width = null;
- $height = null;
$params =array(
'period' => $content['period'],
'width' => $width,
- 'height' => $height,
'unit_name' => array_fill(0, count($interface['traffic']), __("bytes/s")),
'date' => $report["datetime"],
'only_image'=> $pdf,
'homeurl' => $config['homeurl'],
'fullscale' => $fullscale,
- 'server_id' => $id_meta
+ 'server_id' => $id_meta,
+ 'height' => $config['graph_image_height']
);
$params_combined = array(
@@ -2866,14 +2870,27 @@ function reporting_alert_get_fired($id_agent_module, $id_alert_template_module,
$id_alert_template_module,
$period,
$datetime);
+
+ if (!is_numeric ($datetime)) {
+ $datetime = time_w_fixed_tz($datetime);
+ }
+ if (empty ($datetime)) {
+ $datetime = get_system_time();
+ }
+
+ $datelimit = $datetime - $period;
+ $empty = '----------------------------';
if (empty($firedTimes)) {
$firedTimes = array();
- $firedTimes[0]['timestamp'] = '----------------------------';
+ $firedTimes[0]['timestamp'] = $empty;
}
foreach ($firedTimes as $fireTime) {
+ if($fireTime['utimestamp'] > $datelimit && $fireTime['utimestamp'] <= $datetime)
$fired[] = $fireTime['timestamp'];
+ else
+ $fired[] = $empty;
}
return $fired;
@@ -2956,6 +2973,16 @@ function reporting_alert_report_group($report, $content) {
foreach ($alerts as $template => $actions) {
+ $datetime = (int) $report["datetime"];
+ if (!is_numeric ($datetime)) {
+ $datetime = time_w_fixed_tz($datetime);
+ }
+ if (empty ($datetime)) {
+ $datetime = get_system_time();
+ }
+ $period = (int) $content["period"];
+ $datelimit = $datetime - $period;
+
$data_action = array();
$data_action['actions'] = array();
@@ -2964,7 +2991,7 @@ function reporting_alert_report_group($report, $content) {
foreach ($actions["custom"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -2977,7 +3004,7 @@ function reporting_alert_report_group($report, $content) {
foreach ($actions["default"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -2990,7 +3017,7 @@ function reporting_alert_report_group($report, $content) {
foreach ($actions["unavailable"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3073,6 +3100,16 @@ function reporting_alert_report_agent($report, $content) {
foreach ($alerts as $template => $actions) {
+ $datetime = (int) $report["datetime"];
+ if (!is_numeric ($datetime)) {
+ $datetime = time_w_fixed_tz($datetime);
+ }
+ if (empty ($datetime)) {
+ $datetime = get_system_time();
+ }
+ $period = (int) $content["period"];
+ $datelimit = $datetime - $period;
+
$data_action = array();
$data_action['actions'] = array();
@@ -3081,7 +3118,7 @@ function reporting_alert_report_agent($report, $content) {
foreach ($actions["custom"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3094,7 +3131,7 @@ function reporting_alert_report_agent($report, $content) {
foreach ($actions["default"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3107,7 +3144,7 @@ function reporting_alert_report_agent($report, $content) {
foreach ($actions["unavailable"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3186,13 +3223,18 @@ function reporting_alert_report_module($report, $content) {
// Alerts over $id_agent_module
$alerts = alerts_get_effective_alert_actions($content['id_agent_module']);
- if ($alerts === false){
- return;
- }
-
$ntemplates = 0;
foreach ($alerts as $template => $actions) {
+ $datetime = (int) $report["datetime"];
+ if (!is_numeric ($datetime)) {
+ $datetime = time_w_fixed_tz($datetime);
+ }
+ if (empty ($datetime)) {
+ $datetime = get_system_time();
+ }
+ $period = (int) $content["period"];
+ $datelimit = $datetime - $period;
$data_action = array();
$data_action['actions'] = array();
@@ -3202,7 +3244,7 @@ function reporting_alert_report_module($report, $content) {
foreach ($actions["custom"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3215,7 +3257,7 @@ function reporting_alert_report_module($report, $content) {
foreach ($actions["default"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3228,7 +3270,7 @@ function reporting_alert_report_module($report, $content) {
foreach ($actions["unavailable"] as $action) {
$data_action[$naction]["name"] = $action["name"];
$fired = $action["fired"];
- if ($fired == 0){
+ if ($fired == 0 || ($fired <= $datelimit || $fired > $datetime)){
$data_action[$naction]['fired'] = '----------------------------';
}
else {
@@ -3474,79 +3516,6 @@ function reporting_netflow($report, $content, $type,
return reporting_check_structure_content($return);
}
-function reporting_simple_baseline_graph($report, $content,
- $type = 'dinamic', $force_width_chart = null,
- $force_height_chart = null) {
-
- 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['type'] = 'simple_baseline_graph';
-
- if (empty($content['name'])) {
- $content['name'] = __('Simple baseline graph');
- }
-
- $module_name = io_safe_output(
- modules_get_agentmodule_name($content['id_agent_module']));
- $agent_name = io_safe_output(
- modules_get_agentmodule_agent_alias ($content['id_agent_module']));
-
- $return['title'] = $content['name'];
- $return['subtitle'] = $agent_name . " - " . $module_name;
- $return["description"] = $content["description"];
- $return["date"] = reporting_get_date_text($report, $content);
- $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : '';
-
- // Get chart
- reporting_set_conf_charts($width, $height, $only_image, $type,
- $content, $ttl);
-
- $baseline_data = enterprise_hook(
- 'reporting_enterprise_get_baseline',
- array (
- $content['id_agent_module'],
- $content['period'],
- $report["datetime"]
- )
- );
-
- if ($baseline_data === ENTERPRISE_NOT_HOOK) {
- $baseline_data = array ();
- }
-
- switch ($type) {
- case 'dinamic':
- case 'static':
- $params =array(
- 'agent_module_id' => $content['id_agent_module'],
- 'period' => $content['period'],
- 'date' => $report["datetime"],
- 'only_image' => $only_image,
- 'homeurl' => ui_get_full_url(false, false, false, false),
- 'ttl' => $ttl,
- 'array_data_create' => $baseline_data,
- 'server_id' => $id_meta
- );
-
- $return['chart'] = grafico_modulo_sparse ($params);
- break;
- case 'data':
- break;
- }
-
- if ($config['metaconsole']) {
- metaconsole_restore_db();
- }
-
- return reporting_check_structure_content($return);
-}
-
function reporting_prediction_date($report, $content) {
global $config;
@@ -3622,31 +3591,20 @@ function reporting_projection_graph($report, $content,
switch ($type) {
case 'dinamic':
case 'static':
- $output_projection = forecast_projection_graph(
- $content['id_agent_module'],
- $content['period'],
- $content['top_n_value']
- );
-
- // If projection doesn't have data then don't draw graph
- if ($output_projection == NULL) {
- $output_projection = false;
- }
-
$params =array(
'period' => $content['period'],
'width' => $width,
- 'height' => $height,
'date' => $report["datetime"],
'unit' => '',
'only_image' => $pdf,
'homeurl' => ui_get_full_url(false, false, false, false) . '/',
'ttl' => $ttl,
- 'server_id' => $id_meta
+ 'server_id' => $id_meta,
+ 'height' => $config['graph_image_height']
);
$params_combined = array(
- 'projection' => $output_projection
+ 'projection' => $content['top_n_value'],
);
$return['chart'] = graphic_combined_module(
@@ -3875,131 +3833,131 @@ function reporting_value($report, $content, $type,$pdf) {
$return['agent_name'] = $agent_name;
$return['module_name'] = $module_name;
-
+
if($pdf){
$only_image = 1;
}
$params =array(
- 'agent_module_id' => $content['id_agent_module'],
- 'period' => $content['period'],
- 'width' => '600px',
- 'pure' => false,///true
- 'date' => $report["datetime"],
- 'only_image' => $only_image,
- 'homeurl' => ui_get_full_url(false, false, false, false),
- 'ttl' => 1,///2
- 'type_graph' => $config['type_module_charts'],
- 'time_interval' => $content['lapse'],
- 'server_id' => $id_meta
+ 'agent_module_id' => $content['id_agent_module'],
+ 'period' => $content['period'],
+ 'width' => '600px',
+ 'pure' => false,///true
+ 'date' => $report["datetime"],
+ 'only_image' => $only_image,
+ 'homeurl' => ui_get_full_url(false, false, false, false),
+ 'ttl' => 1,///2
+ 'type_graph' => $config['type_module_charts'],
+ 'time_interval' => $content['lapse'],
+ 'server_id' => $id_meta,
+ 'height' => $config['graph_image_height'],
+ 'fullscale' => true
);
-
- switch ($type) {
+ switch ($type) {
case 'max':
- if($content['lapse_calc'] == 0){
- $value = reporting_get_agentmodule_data_max(
- $content['id_agent_module'], $content['period'], $report["datetime"]);
- if (!$config['simple_module_value']) {
- $formated_value = $value;
+ if($content['lapse_calc'] == 0){
+ $value = reporting_get_agentmodule_data_max(
+ $content['id_agent_module'], $content['period'], $report["datetime"]);
+ if (!$config['simple_module_value']) {
+ $formated_value = $value;
+ }
+ else {
+ $formated_value = format_for_graph($value, $config['graph_precision']) . " " . $unit;
+ }
}
- else {
- $formated_value = format_for_graph($value, $config['graph_precision']) . " " . $unit;
- }
- }
- else{
- $value = '
-
-
- ';
- if($content['visual_format'] == 1 || $content['visual_format'] == 2 || $content['visual_format'] == 3){
+ else{
+ $value = '
+
+
+ ';
+ 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.'
+ |
+
+ ';
+ }
+
+ $value .= '
+ |
+
+ |
+ ';
+
+ if($content['visual_format'] == 2 || $content['visual_format'] == 3){
+ $params['force_interval'] = 'max_only';
+ $value .= grafico_modulo_sparse($params);
+ }
$value .= '
-
+
+
+
+
+ ';
+
+ if($content['visual_format'] == 1 || $content['visual_format'] == 3){
+
+ $value .= '
+
- '.__("Agent").'
- |
-
- '.__("Module").'
+ '.__("Lapse").'
|
'.__("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.'
- |
- ';
+ | ';
+ $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module'], true);
+ $date_reference = getdate();
+
+ for ($i=$date_reference[0]; $i > ($date_reference[0]-$content["period"]); $i -= $content["lapse"]) {
+
+ $value .= ' '. date("Y-m-d H:i:s", ($i-$content["lapse"]+1)).' to '.date("Y-m-d H:i:s",$i).' | ';
+
+ if ($i>$time_begin['utimestamp']) {
+ $value .= format_for_graph(reporting_get_agentmodule_data_max(
+ $content['id_agent_module'], $content["lapse"], $i), $config['graph_precision']) . ' ' . $unit.' | ';
+ } else {
+ $value .= 'N/A';
+ }
+
+ }
+
+ $value .=' ';
}
+ $value .= '
+ |
+
+ ';
- $value .= '
- |
-
- |
- ';
+ $formated_value = $value;
+ }
- if($content['visual_format'] == 2 || $content['visual_format'] == 3){
- $params['force_interval'] = 'max_only';
- $value .= grafico_modulo_sparse($params);
- }
-
- $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']);
- $date_reference = getdate();
-
- for ($i=$date_reference[0]; $i > ($date_reference[0]-$content["period"]); $i -= $content["lapse"]) {
-
- $value .= ' '. date("Y-m-d H:i:s", ($i-$content["lapse"]+1)).' to '.date("Y-m-d H:i:s",$i).' | ';
-
- if($i>$time_begin['utimestamp']){
- $value .= format_for_graph(reporting_get_agentmodule_data_max(
- $content['id_agent_module'], $content["lapse"], $i), $config['graph_precision']) . ' ' . $unit.' | ';
- }
- else{
- $value .= 'N/A';
- }
-
- }
-
- $value .=' ';
- }
- $value .= '
- |
-
-
';
-
- $formated_value = $value;
- }
-
- break;
+ break;
case 'min':
if($content['lapse_calc'] == 0){
$value = reporting_get_agentmodule_data_min(
@@ -4110,111 +4068,111 @@ function reporting_value($report, $content, $type,$pdf) {
break;
case 'avg':
- if($content['lapse_calc'] == 0){
- $value = reporting_get_agentmodule_data_average(
- $content['id_agent_module'], $content['period'], $report["datetime"]);
- if (!$config['simple_module_value']) {
- $formated_value = $value;
+ if($content['lapse_calc'] == 0){
+ $value = reporting_get_agentmodule_data_average(
+ $content['id_agent_module'], $content['period'], $report["datetime"]);
+ if (!$config['simple_module_value']) {
+ $formated_value = $value;
+ }
+ else {
+ $formated_value = format_for_graph($value, $config['graph_precision']) . " " . $unit;
+ }
}
- else {
- $formated_value = format_for_graph($value, $config['graph_precision']) . " " . $unit;
- }
- }
- else{
- $value = '
-
-
- ';
+ else{
+ $value = '
+
+
+ ';
+
+ 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.'
+ |
+
+ ';
+
+ }
+
+ $value .= '
+ |
+
+ |
+ ';
+ if($content['visual_format'] == 2 || $content['visual_format'] == 3){
+ $params['force_interval'] = 'avg_only';
+ $value .= grafico_modulo_sparse($params);
+ }
- if($content['visual_format'] == 1 || $content['visual_format'] == 2 || $content['visual_format'] == 3){
$value .= '
-
+
+
+
+
+ ';
+
+ if($content['visual_format'] == 1 || $content['visual_format'] == 3){
+
+ $value .= '
+
- '.__("Agent").'
- |
-
- '.__("Module").'
+ '.__("Lapse").'
|
'.__("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.'
- |
- ';
-
+ | ';
+ $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module']);
+ $date_reference = getdate();
+
+ for ($i=$date_reference[0]; $i > ($date_reference[0]-$content["period"]); $i -= $content["lapse"]) {
+
+ $value .= ' '. date("Y-m-d H:i:s", ($i-$content["lapse"]+1)).' to '.date("Y-m-d H:i:s",$i).' | ';
+
+ if($i>$time_begin['utimestamp']){
+ $value .= format_for_graph(reporting_get_agentmodule_data_average(
+ $content['id_agent_module'], $content["lapse"], $i), $config['graph_precision']) . ' ' . $unit.' | ';
+ }
+ else{
+ $value .= 'N/A';
+ }
+
+ }
+
+ $value .=' ';
}
- $value .= '
- |
-
- |
- ';
- if($content['visual_format'] == 2 || $content['visual_format'] == 3){
- $params['force_interval'] = 'avg_only';
- $value .= grafico_modulo_sparse($params);
- }
+ $value .= '
+
+ |
+
+ ';
- $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();
-
- for ($i=$date_reference[0]; $i > ($date_reference[0]-$content["period"]); $i -= $content["lapse"]) {
-
- $value .= ' '. date("Y-m-d H:i:s", ($i-$content["lapse"]+1)).' to '.date("Y-m-d H:i:s",$i).' | ';
-
- if($i>$time_begin['utimestamp']){
- $value .= format_for_graph(reporting_get_agentmodule_data_average(
- $content['id_agent_module'], $content["lapse"], $i), $config['graph_precision']) . ' ' . $unit.' | ';
- }
- else{
- $value .= 'N/A';
- }
-
- }
-
- $value .=' ';
- }
-
- $value .= '
-
- |
-
-
';
+ $formated_value = $value;
- $formated_value = $value;
-
- }
- break;
+ }
+ break;
case 'sum':
$value = reporting_get_agentmodule_data_sum(
@@ -6278,6 +6236,8 @@ function reporting_custom_graph($report, $content, $type = 'dinamic',
global $config;
+ $modules = array();
+
require_once ($config["homedir"] . '/include/functions_graph.php');
if ($config['metaconsole']) {
@@ -6289,14 +6249,42 @@ function reporting_custom_graph($report, $content, $type = 'dinamic',
$graph = db_get_row ("tgraph", "id_graph", $content['id_gs']);
$return = array();
$return['type'] = 'custom_graph';
-
if (empty($content['name'])) {
if ($type_report == "custom_graph") {
$content['name'] = __('Custom graph');
+ $graphs = db_get_all_rows_field_filter ("tgraph", "id_graph", $content['id_gs']);
+ $id_graph = $content['id_gs'];
+ }
+ else if($type_report == "automatic_graph"){
+ $content['name'] = __('Automatic combined graph');
+ $graphs[0]["stacked"] = '';
+ $graphs[0]["summatory_series"] = '';
+ $graphs[0]["average_series"] = '';
+ $graphs[0]["modules_series"] = '';
+ $graphs[0]["fullscale"] = $content['style']['fullscale'];
+ if(is_array($content['id_agent_module'])){
+ foreach ($content['id_agent_module'] as $key => $value) {
+ if($content['each_agent']){
+ $modules[] = $value;
+ }
+ else{
+ $modules[] = $value['module'];
+ }
+ }
+ }
+ else{
+ $modules[] = $content['id_agent_module'];
+ }
+ $id_graph = 0;
}
else {
$content['name'] = __('Simple graph');
}
+ } else {
+ if ($type_report == "custom_graph") {
+ $graphs = db_get_all_rows_field_filter ("tgraph", "id_graph", $content['id_gs']);
+ $id_graph = $content['id_gs'];
+ }
}
$return['title'] = $content['name'];
@@ -6304,30 +6292,27 @@ function reporting_custom_graph($report, $content, $type = 'dinamic',
$return["description"] = $content["description"];
$return["date"] = reporting_get_date_text(
$report,
- $content);
-
- $graphs = db_get_all_rows_field_filter ("tgraph", "id_graph", $content['id_gs']);
+ $content
+ );
$return['chart'] = '';
$width =null;
- $height =null;
switch ($type) {
case 'dinamic':
case 'static':
-
$params =array(
'period' => $content['period'],
'width' => $width,
- 'height' => $height,
'date' => $report["datetime"],
'only_image' => $pdf,
'homeurl' => ui_get_full_url(false, false, false, false),
'ttl' => $ttl,
'percentil' => $graphs[0]["percentil"],
'fullscale' => $graphs[0]["fullscale"],
- 'server_id' => $id_meta
+ 'server_id' => $id_meta,
+ 'height' => $config['graph_image_height']
);
$params_combined = array(
@@ -6335,7 +6320,7 @@ function reporting_custom_graph($report, $content, $type = 'dinamic',
'summatory' => $graphs[0]["summatory_series"],
'average' => $graphs[0]["average_series"],
'modules_series' => $graphs[0]["modules_series"],
- 'id_graph' => $content['id_gs']
+ 'id_graph' => $id_graph
);
$return['chart'] = graphic_combined_module(
@@ -6432,7 +6417,8 @@ function reporting_simple_graph($report, $content, $type = 'dinamic',
'show_unknown' => true,
'percentil' => ($content['style']['percentil'] == 1) ? $config['percentil'] : null,
'fullscale' => $fullscale,
- 'server_id' => $id_meta
+ 'server_id' => $id_meta,
+ 'height' => $config['graph_image_height']
);
$return['chart'] = grafico_modulo_sparse($params);
@@ -6459,15 +6445,14 @@ function reporting_simple_graph($report, $content, $type = 'dinamic',
function reporting_get_date_text($report = null, $content = null) {
global $config;
-
+
$return = array();
$return['date'] = null;
$return['period'] = null;
$return['from'] = null;
$return['to'] = null;
-
+
if (!empty($report) && !empty($content)) {
-
if ($content['period'] == 0) {
$es = json_decode($content['external_source'], true);
if ($es['date'] == 0) {
@@ -6483,7 +6468,7 @@ function reporting_get_date_text($report = null, $content = null) {
$return['to'] = $report["datetime"];
}
}
-
+
return $return;
}
@@ -6499,7 +6484,7 @@ function reporting_check_structure_report($return) {
$return['datetime'] = "";
if (!isset($return['period']))
$return['period'] = "";
-
+
return $return;
}
@@ -6519,7 +6504,7 @@ function reporting_check_structure_content($report) {
$report["date"]['from'] = "";
$report["date"]['to'] = "";
}
-
+
return $report;
}
@@ -6968,91 +6953,46 @@ function reporting_get_group_stats ($id_group = 0, $access = 'AR') {
continue;
}
}
-
+
if (!empty($group_array)) {
- // FOR THE FUTURE: Split the groups into groups with tags restrictions and groups without it
- // To calculate in the light way the non tag restricted and in the heavy way the others
- /*
- $group_restricted_data = tags_get_acl_tags($config['id_user'], $group_array, $access, 'data');
- $tags_restricted_groups = array_keys($group_restricted_data);
-
- $no_tags_restricted_groups = $group_array;
- foreach ($no_tags_restricted_groups as $k => $v) {
- if (in_array($v, $tags_restricted_groups)) {
- unset($no_tags_restricted_groups[$k]);
- }
- }
- */
-
- if (!empty($group_array)) {
- // Get monitor NOT INIT, except disabled AND async modules
- $data["monitor_not_init"] += (int) groups_get_not_init_monitors ($group_array, array(), array(), false, false, true);
-
- // Get monitor OK, except disabled and non-init
- $data["monitor_ok"] += (int) groups_get_normal_monitors ($group_array, array(), array(), false, false, true);
-
- // Get monitor CRITICAL, except disabled and non-init
- $data["monitor_critical"] += (int) groups_get_critical_monitors ($group_array, array(), array(), false, false, true);
-
- // Get monitor WARNING, except disabled and non-init
- $data["monitor_warning"] += (int) groups_get_warning_monitors ($group_array, array(), array(), false, false, true);
-
- // Get monitor UNKNOWN, except disabled and non-init
- $data["monitor_unknown"] += (int) groups_get_unknown_monitors ($group_array, array(), array(), false, false, true);
-
- // Get alerts configured, except disabled
- $data["monitor_alerts"] += groups_monitor_alerts ($group_array) ;
-
- // Get alert configured currently FIRED, except disabled
- $data["monitor_alerts_fired"] += groups_monitor_fired_alerts ($group_array);
-
- // Calculate totals using partial counts from above
-
- // Get TOTAL non-init modules, except disabled ones and async modules
- $data["total_not_init"] += $data["monitor_not_init"];
-
- // Get TOTAL agents in a group
- $data["total_agents"] += (int) groups_get_total_agents ($group_array, array(), array(), false, false, true);
-
- // Get Agents OK
- $data["agent_ok"] += (int) groups_get_normal_agents ($group_array, array(), array(), false, false, true);
-
- // Get Agents Warning
- $data["agent_warning"] += (int) groups_get_warning_agents ($group_array, array(), array(), false, false, true);
-
- // Get Agents Critical
- $data["agent_critical"] += (int) groups_get_critical_agents ($group_array, array(), array(), false, false, true);
-
- // Get Agents Unknown
- $data["agent_unknown"] += (int) groups_get_unknown_agents ($group_array, array(), array(), false, false, true);
-
- // Get Agents Not init
- $data["agent_not_init"] += (int) groups_get_not_init_agents ($group_array, array(), array(), false, false, true);
- }
-
- // Get total count of monitors for this group, except disabled.
- $data["monitor_checks"] = $data["monitor_not_init"] + $data["monitor_unknown"] + $data["monitor_warning"] + $data["monitor_critical"] + $data["monitor_ok"];
-
- // Calculate not_normal monitors
- $data["monitor_not_normal"] += $data["monitor_checks"] - $data["monitor_ok"];
+ $monitors_info = groups_monitor_total_counters($group_array, true);
+ // Get monitor NOT INIT, except disabled AND async modules
+ $data["monitor_not_init"] += $monitors_info['not_init'];
+ $data["total_not_init"] += $data["monitor_not_init"];
+ // Get monitor OK, except disabled and non-init
+ $data["monitor_ok"] += $monitors_info['ok'];
+ // Get monitor CRITICAL, except disabled and non-init
+ $data["monitor_critical"] += $monitors_info['critical'];
+ // Get monitor WARNING, except disabled and non-init
+ $data["monitor_warning"] += $monitors_info['warning'];
+ // Get monitor UNKNOWN, except disabled and non-init
+ $data["monitor_unknown"] += $monitors_info['unknown'];
+ $data["monitor_checks"] += $monitors_info['total'];
+
+ // Get alerts configured, except disabled
+ $alerts_info = groups_monitor_alerts_total_counters ($group_array);
+ $data["monitor_alerts"] += $alerts_info['total'];
+ // Get alert configured currently FIRED, except disabled
+ $data["monitor_alerts_fired"] += $alerts_info['fired'];
+
+ $agents_info = groups_agents_total_counters($group_array);
+ // Get TOTAL agents in a group
+ $data["total_agents"] += $agents_info['total'];
+ // Get Agents OK
+ $data["agent_ok"] += $agents_info['ok'];
+ // Get Agents Warning
+ $data["agent_warning"] += $agents_info['warning'];
+ // Get Agents Critical
+ $data["agent_critical"] += $agents_info['critical'];
+ // Get Agents Unknown
+ $data["agent_unknown"] += $agents_info['unknown'];
+ // Get Agents Not init
+ $data["agent_not_init"] += $agents_info['not_init'];
}
-
- // Get total count of monitors for this group, except disabled.
-
- $data["monitor_checks"] = $data["monitor_not_init"] + $data["monitor_unknown"] + $data["monitor_warning"] + $data["monitor_critical"] + $data["monitor_ok"];
-
- /*
- Monitor health (percentage)
- Data health (percentage)
- Global health (percentage)
- Module sanity (percentage)
- Alert level (percentage)
-
- Server Sanity 0% Uninitialized modules
-
- */
}
-
+ // Calculate not_normal monitors
+ $data["monitor_not_normal"] += $data["monitor_checks"] - $data["monitor_ok"];
+
if ($data["monitor_unknown"] > 0 && $data["monitor_checks"] > 0) {
$data["monitor_health"] = format_numeric (100 - ($data["monitor_not_normal"] / ($data["monitor_checks"] / 100)), 1);
}
diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php
index 9ed6ab16e1..fd4d0a2c76 100644
--- a/pandora_console/include/functions_reporting_html.php
+++ b/pandora_console/include/functions_reporting_html.php
@@ -1960,6 +1960,12 @@ function reporting_html_alert_report($table, $item, $pdf = 0) {
$table1->data = array ();
$table1->rowspan = array();
$table1->valign = array();
+
+ if ($item['data'] == null) {
+ $table->data['alerts']['cell'] = ui_print_empty_data ( __('No alerts defined') , '', true) ;
+ return true;
+ }
+
$table1->head['agent'] = __('Agent');
$table1->head['module'] = __('Module');
$table1->head['template'] = __('Template');
diff --git a/pandora_console/include/functions_reports.php b/pandora_console/include/functions_reports.php
index dfa3d3d490..b836f534a2 100755
--- a/pandora_console/include/functions_reports.php
+++ b/pandora_console/include/functions_reports.php
@@ -95,10 +95,12 @@ function reports_get_reports ($filter = false, $fields = false,
$filter[] = sprintf ('private = 0 OR (private = 1 AND id_user = "%s")',
$config['id_user']);
*/
+ $filter['hidden'] = 0;
if (is_array ($fields)) {
$fields[] = 'id_group';
$fields[] = 'id_user';
$fields[] = 'id_group_edit';
+ $fields[] = 'hidden';
}
$reports = array ();
diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php
index c6698d70cd..7ca704f465 100644
--- a/pandora_console/include/functions_snmp_browser.php
+++ b/pandora_console/include/functions_snmp_browser.php
@@ -36,7 +36,7 @@ function snmp_browser_print_tree ($tree, $id = 0, $depth = 0, $last = 0, $last_a
// Get the base URL for images
if ($url === false) {
- $url = ui_get_full_url('operation/tree');
+ $url = ui_get_full_url('operation/tree', false, false, false);
}
// Leaf
@@ -604,8 +604,8 @@ function snmp_browser_print_container ($return = false, $width = '100%', $height
$table3->data[2][2] = html_print_input_text ('snmp3_browser_auth_user', '', '', 15, 60, true);
$table3->data[2][3] = ''.__('Auth password').'';
$table3->data[2][4] = html_print_input_password ('snmp3_browser_auth_pass', '', '', 15, 60, true);
- $table3->data[2][4] .= html_print_input_hidden('active_snmp_v3', 0, true);
-
+ $table3->data[2][4] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_fsb', true);
+
$table3->data[5][0] = ''.__('Privacy method').'';
$table3->data[5][1] = html_print_select(array('DES' => __('DES'), 'AES' => __('AES')), 'snmp3_browser_privacy_method', '', '', '', '', true);
$table3->data[5][2] = ''.__('Privacy pass').'';
diff --git a/pandora_console/include/functions_tags.php b/pandora_console/include/functions_tags.php
index 2ee8826f47..ba031c0cff 100644
--- a/pandora_console/include/functions_tags.php
+++ b/pandora_console/include/functions_tags.php
@@ -1184,23 +1184,25 @@ function tags_get_tags_for_module_search($id_user = false, $access = 'AR') {
function tags_check_acl_by_module($id_module = 0, $id_user = false,
$access = 'AW') {
-
global $config;
-
-
+
$return = false;
-
+
if (!empty($id_module)) {
$tags = tags_get_module_tags($id_module);
- $group = modules_get_agent_group($id_module);
-
+ $groups = modules_get_agent_groups($id_module);
+
if ($id_user === false) {
$id_user = $config["id_user"];
}
-
- $return = tags_check_acl($id_user, $group, $access, $tags, true);
+
+ foreach ($groups as $group) {
+ if (tags_check_acl($id_user, $group, $access, $tags, true)) {
+ return true;
+ }
+ }
}
-
+
return $return;
}
@@ -1275,6 +1277,8 @@ function tags_check_acl($id_user, $id_group, $access, $tags = array(), $flag_id_
if (in_array($tag, $acls[$group])) {
return true;
+ } else if (empty($acls[$group])) {
+ return true;
}
}
}
@@ -2478,17 +2482,10 @@ function tags_get_all_user_agents ($id_tag = false, $id_user = false,
}
$select_fields = implode(',',$fields);
-
+
$groups_clause = "";
- if ($strict_user) {
- if (!empty($groups_and_tags)) {
- $groups_clause = " AND ".tags_get_acl_tags_module_condition($groups_and_tags, "tagente_modulo");
- }
- }
- else {
- $groups_clause = " AND tagente.id_grupo IN (".implode(',', array_keys($groups_and_tags)).")";
- }
-
+ $groups_clause = " AND tagente.id_grupo IN (".implode(',', array_keys($groups_and_tags)).")";
+
if (!empty($filter['id_group'])) {
if (is_array($filter['id_group']))
$groups_str = implode(",", $filter['id_group']);
diff --git a/pandora_console/include/functions_treeview.php b/pandora_console/include/functions_treeview.php
index 5c50f853b8..20d1f577bc 100755
--- a/pandora_console/include/functions_treeview.php
+++ b/pandora_console/include/functions_treeview.php
@@ -266,35 +266,19 @@ function treeview_printModuleTable($id_module, $server_data = false, $no_head =
$last_data_str .= " ";
$last_data_str .= html_print_image('images/clock2.png', true, array('title' => $last_data["timestamp"], 'width' => '18px'));
-
- $is_snapshot = is_snapshot_data ( $last_data["datos"] );
- if (($config['command_snapshot']) && ($is_snapshot)) {
- $link = ui_get_snapshot_link( array(
- 'id_module' => $module['id_agente_modulo'],
- 'last_data' => $last_data['datos'],
- 'timestamp' => $last_data['timestamp'],
- 'interval' => $module['current_interval'],
- 'module_name' => $module['module_name']
- ));
- if(!is_image_data($last_data["datos"])){
- $salida = '' .
- html_print_image('images/default_list.png', true,
- array('border' => '0',
- 'alt' => '',
- 'title' => __('Snapshot view'))) . ' ';
- }
- else {
- $salida = '' .
- html_print_image('images/photo.png', true,
- array('border' => '0',
- 'alt' => '',
- 'title' => __('Snapshot view'))) . ' ';
- }
- }
-
-
- $last_data_str .= $salida;
+ $is_snapshot = is_snapshot_data ( $last_data["datos"] );
+ $is_large_image = is_text_to_black_string ($last_data["datos"]);
+ if (($config['command_snapshot']) && ($is_snapshot || $is_large_image)) {
+ $link = ui_get_snapshot_link( array(
+ 'id_module' => $module['id_agente_modulo'],
+ 'interval' => $module['current_interval'],
+ 'module_name' => $module['module_name'],
+ 'id_node' => empty($server_id) ? 0 : $server_id
+ ));
+ $salida = ui_get_snapshot_image($link, $is_snapshot) . ' ';
+ }
+ $last_data_str .= $salida;
}
else {
$last_data_str = '' . __('No data') . '';
diff --git a/pandora_console/include/functions_ui.php b/pandora_console/include/functions_ui.php
index d3871c4929..4d07f2d9fc 100755
--- a/pandora_console/include/functions_ui.php
+++ b/pandora_console/include/functions_ui.php
@@ -827,22 +827,39 @@ function ui_format_alert_row ($alert, $agent = true, $url = '', $agent_style = f
$description = io_safe_output($template['name']);
$data = array ();
-
- if (!defined('METACONSOLE')) {
- if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) {
- $policyInfo = policies_is_alert_in_policy2($alert['id'], false);
- if ($policyInfo === false)
- $data[$index['policy']] = '';
- else {
- $img = 'images/policies.png';
-
+
+ if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) {
+ if(is_metaconsole()){
+ $node = metaconsole_get_connection_by_id($alert['server_data']['id']);
+ if (metaconsole_load_external_db($node) !== NOERR) {
+ // Restore the default connection.
+ metaconsole_restore_db();
+ $errors++;
+ break;
+ }
+ }
+
+ $policyInfo = policies_is_alert_in_policy2($alert['id'], false);
+ if ($policyInfo === false)
+ $data[$index['policy']] = '';
+ else {
+ $img = 'images/policies.png';
+ if(!is_metaconsole()){
$data[$index['policy']] = '' .
html_print_image($img,true, array('title' => $policyInfo['name'])) .
'';
+ }else{
+ $data[$index['policy']] = '' .
+ html_print_image($img,true, array('title' => $policyInfo['name'])) .
+ '';
}
}
+
+ if(is_metaconsole()){
+ metaconsole_restore_db();
+ }
}
-
+
// Standby
$data[$index['standby']] = '';
if (isset ($alert["standby"]) && $alert["standby"] == 1) {
@@ -877,8 +894,8 @@ function ui_format_alert_row ($alert, $agent = true, $url = '', $agent_style = f
$agent_name = false;
$id_agent = modules_get_agentmodule_agent ($alert["id_agent_module"]);
}
-
- if (defined('METACONSOLE') && !can_user_access_node ()) {
+
+ if (defined('METACONSOLE') || !can_user_access_node ()) {
$data[$index['agent_name']] = ui_print_truncate_text($agent_name, 'agent_small', false, true, false, '[…]', 'font-size:7.5pt;');
}
else {
@@ -889,7 +906,7 @@ function ui_format_alert_row ($alert, $agent = true, $url = '', $agent_style = f
$data[$index['agent_name']] .= ' '.$agente["alias"].'';
}
}
-
+
$data[$index['module_name']] =
ui_print_truncate_text (isset($alert['agent_module_name']) ? $alert['agent_module_name'] : modules_get_agentmodule_name ($alert["id_agent_module"]), 'module_small', false, true, true, '[…]', 'font-size: 7.2pt');
}
@@ -2500,11 +2517,23 @@ function ui_print_page_header ($title, $icon = "", $return = false,
";
}
- if ($help != "")
- $buffer .= "" .
- ui_print_help_icon ($help, true, '', 'images/help_w.png') . "
";
- $buffer .= ' ';
-
+ if(!is_metaconsole()){
+ if ($help != ""){
+ $buffer .= "" .
+ ui_print_help_icon ($help, true, '', 'images/help_w.png') . "
";
+ }
+ }
+
+ $buffer .= '';
+
+ if(is_metaconsole()){
+ if ($help != ""){
+ $buffer .= "" . ui_print_help_icon ($help, true, '', 'images/help_30.png') . "
";
+ }
+ }
+
+ $buffer .= '