1<?php
2
3// Pandora FMS - http://pandorafms.com
4// ==================================================
5// Copyright (c) 2005-2010 Artica Soluciones Tecnologicas
6// Please see http://pandorafms.org for full contribution list
7
8// This program is free software; you can redistribute it and/or
9// modify it under the terms of the  GNU Lesser General Public License
10// as published by the Free Software Foundation; version 2
11
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15// GNU General Public License for more details.
16
17require_once ($config['homedir'].'/include/functions_users.php');
18
19/**
20 * Check if the group is in use in the Pandora DB.
21 *
22 * @param integer $idGroup The id of group.
23 *
24 * @return bool Return false if the group is unused in the Pandora, else true.
25 */
26function groups_check_used($idGroup) {
27	global $config;
28
29	$return = array();
30	$return['return'] = false;
31	$return['tables'] = array();
32
33	switch ($config["dbtype"]) {
34		case "mysql":
35		case "postgresql":
36			$numRows = db_get_num_rows('SELECT *
37				FROM tagente WHERE id_grupo = ' . $idGroup . ';');
38			break;
39		case "oracle":
40			$numRows = db_get_num_rows('SELECT *
41				FROM tagente WHERE id_grupo = ' . $idGroup);
42			break;
43	}
44	if ($numRows > 0) {
45		$return['return'] = true;
46		$return['tables'][] = __('Agents');
47	}
48
49	switch ($config["dbtype"]) {
50		case "mysql":
51		case "postgresql":
52			$numRows = db_get_num_rows('SELECT *
53				FROM talert_actions WHERE id_group = ' . $idGroup . ';');
54			break;
55		case "oracle":
56			$numRows = db_get_num_rows('SELECT *
57				FROM talert_actions WHERE id_group = ' . $idGroup);
58			break;
59	}
60
61	if ($numRows > 0) {
62		$return['return'] = true;
63		$return['tables'][] = __('Alert Actions');
64	}
65
66	switch ($config["dbtype"]) {
67		case "mysql":
68		case "postgresql":
69			$numRows = db_get_num_rows('SELECT * FROM talert_templates WHERE id_group = ' . $idGroup . ';');
70			break;
71		case "oracle":
72			$numRows = db_get_num_rows('SELECT * FROM talert_templates WHERE id_group = ' . $idGroup);
73			break;
74	}
75
76	if ($numRows > 0) {
77		$return['return'] = true;
78		$return['tables'][] = __('Alert Templates');
79	}
80
81	switch ($config["dbtype"]) {
82		case "mysql":
83		case "postgresql":
84			$numRows = db_get_num_rows('SELECT * FROM trecon_task WHERE id_group = ' . $idGroup . ';');
85			break;
86		case "oracle":
87			$numRows = db_get_num_rows('SELECT * FROM trecon_task WHERE id_group = ' . $idGroup);
88			break;
89	}
90	if ($numRows > 0) {
91		$return['return'] = true;
92		$return['tables'][] = __('Recon task');
93	}
94
95	switch ($config["dbtype"]) {
96		case "mysql":
97		case "postgresql":
98			$numRows = db_get_num_rows('SELECT * FROM tgraph WHERE id_group = ' . $idGroup . ';');
99			break;
100		case "oracle":
101			$numRows = db_get_num_rows('SELECT * FROM tgraph WHERE id_group = ' . $idGroup);
102			break;
103	}
104	if ($numRows > 0) {
105		$return['return'] = true;
106		$return['tables'][] = __('Graphs');
107	}
108
109	switch ($config["dbtype"]) {
110		case "mysql":
111		case "postgresql":
112			$numRows = db_get_num_rows('SELECT * FROM treport WHERE id_group = ' . $idGroup . ';');
113			break;
114		case "oracle":
115			$numRows = db_get_num_rows('SELECT * FROM treport WHERE id_group = ' . $idGroup);
116			break;
117	}
118	if ($numRows > 0) {
119		$return['return'] = true;
120		$return['tables'][] = __('Reports');
121	}
122
123	switch ($config["dbtype"]) {
124		case "mysql":
125		case "postgresql":
126			$numRows = db_get_num_rows('SELECT * FROM tlayout WHERE id_group = ' . $idGroup . ';');
127			break;
128		case "oracle":
129			$numRows = db_get_num_rows('SELECT * FROM tlayout WHERE id_group = ' . $idGroup);
130			break;
131	}
132
133	if ($numRows > 0) {
134		$return['return'] = true;
135		$return['tables'][] = __('Layout visual console');
136	}
137
138	switch ($config["dbtype"]) {
139		case "mysql":
140		case "postgresql":
141			$numRows = db_get_num_rows('SELECT * FROM tplanned_downtime WHERE id_group = ' . $idGroup . ';');
142			break;
143		case "oracle":
144			$numRows = db_get_num_rows('SELECT * FROM tplanned_downtime WHERE id_group = ' . $idGroup);
145			break;
146	}
147	if ($numRows > 0) {
148		$return['return'] = true;
149		$return['tables'][] = __('Plannet down time');
150	}
151
152	switch ($config["dbtype"]) {
153		case "mysql":
154		case "postgresql":
155			$numRows = db_get_num_rows('SELECT * FROM tgraph WHERE id_group = ' . $idGroup . ';');
156			break;
157		case "oracle":
158			$numRows = db_get_num_rows('SELECT * FROM tgraph WHERE id_group = ' . $idGroup);
159			break;
160	}
161	if ($numRows > 0) {
162		$return['return'] = true;
163		$return['tables'][] = __('Graphs');
164	}
165	switch ($config["dbtype"]) {
166		case "mysql":
167		case "postgresql":
168			$numRows = db_get_num_rows('SELECT * FROM tgis_map WHERE group_id = ' . $idGroup . ';');
169			break;
170		case "oracle":
171			$numRows = db_get_num_rows('SELECT * FROM tgis_map WHERE group_id = ' . $idGroup);
172			break;
173	}
174	if ($numRows > 0) {
175		$return['return'] = true;
176		$return['tables'][] = __('GIS maps');
177	}
178
179	switch ($config["dbtype"]) {
180		case "mysql":
181		case "postgresql":
182			$numRows = db_get_num_rows('SELECT * FROM tgis_map_connection WHERE group_id = ' . $idGroup . ';');
183			break;
184		case "oracle":
185			$numRows = db_get_num_rows('SELECT * FROM tgis_map_connection WHERE group_id = ' . $idGroup);
186			break;
187	}
188	if ($numRows > 0) {
189		$return['return'] = true;
190		$return['tables'][] = __('GIS connections');
191	}
192
193	switch ($config["dbtype"]) {
194		case "mysql":
195		case "postgresql":
196			$numRows = db_get_num_rows('SELECT * FROM tgis_map_layer WHERE tgrupo_id_grupo = ' . $idGroup . ';');
197			break;
198		case "oracle":
199			$numRows = db_get_num_rows('SELECT * FROM tgis_map_layer WHERE tgrupo_id_grupo = ' . $idGroup);
200			break;
201	}
202	if ($numRows > 0) {
203		$return['return'] = true;
204		$return['tables'][] = __('GIS map layers');
205	}
206	switch ($config["dbtype"]) {
207		case "mysql":
208		case "postgresql":
209			$numRows = db_get_num_rows('SELECT * FROM tnetwork_map WHERE id_group = ' . $idGroup . ';');
210			break;
211		case "oracle":
212			$numRows = db_get_num_rows('SELECT * FROM tnetwork_map WHERE id_group = ' . $idGroup);
213			break;
214	}
215	if ($numRows > 0) {
216		$return['return'] = true;
217		$return['tables'][] = __('Network maps');
218	}
219
220	$hookEnterprise = enterprise_include_once('include/functions_groups.php');
221	if ($hookEnterprise !== ENTERPRISE_NOT_HOOK) {
222		$returnEnterprise = enterprise_hook('groups_check_used_group_enterprise', array($idGroup));
223
224		if ($returnEnterprise['return']) {
225			$return['return'] = true;
226			$return['tables'] = array_merge($return['tables'], $returnEnterprise['tables']);
227		}
228	}
229
230	return $return;
231}
232
233/**
234 * Return a array of id_group of childrens (to branches down)
235 *
236 * @param integer $parent The id_group parent to search the childrens.
237 * @param array $groups The groups, its for optimize the querys to DB.
238 */
239function groups_get_childrens($parent, $groups = null, $onlyPropagate = false) {
240	if (empty($groups)) {
241		$groups = db_get_all_rows_in_table('tgrupo');
242	}
243
244	$return = array();
245
246	foreach ($groups as $key => $group) {
247		if ($group['id_grupo'] == 0) {
248			continue;
249		}
250
251		if ($group['propagate'] || $onlyPropagate) {
252			if ($group['parent'] == $parent) {
253				$return = $return + array($group['id_grupo'] => $group) + groups_get_childrens($group['id_grupo'], $groups, $onlyPropagate);
254			}
255		}
256
257	}
258
259	return $return;
260}
261
262/**
263 * Return a array of id_group of parents (to roots up).
264 *
265 * @param integer $parent The id_group parent to search the parent.
266 * @param boolean $onlyPropagate Flag to search only parents that true to propagate.
267 * @param array $groups The groups, its for optimize the querys to DB.
268 */
269function groups_get_parents($parent, $onlyPropagate = false, $groups = null) {
270	if (empty($groups)) {
271		$groups = db_get_all_rows_in_table('tgrupo');
272	}
273
274	$return = array();
275
276	foreach ($groups as $key => $group) {
277		if ($group['id_grupo'] == 0) {
278			continue;
279		}
280
281		if (($group['id_grupo'] == $parent)
282			&& ($group['propagate'] || !$onlyPropagate)) {
283
284			$return = $return +
285				array($group['id_grupo'] => $group) +
286				groups_get_parents($group['parent'], $onlyPropagate, $groups);
287		}
288	}
289
290	return $return;
291}
292
293/**
294 * Filter out groups the user doesn't have access to
295 *
296 * Access can be:
297 * IR - Incident Read
298 * IW - Incident Write
299 * IM - Incident Management
300 * AR - Agent Read
301 * AW - Agent Write
302 * LW - Alert Write
303 * UM - User Management
304 * DM - DB Management
305 * LM - Alert Management
306 * PM - Pandora Management
307 *
308 * @param int $id_user User id
309 * @param mixed $id_group Group ID(s) to check
310 * @param string $access Access privilege
311 *
312 * @return array Groups the user DOES have acces to (or an empty array)
313 */
314function groups_safe_acl ($id_user, $id_groups, $access) {
315	if (!is_array ($id_groups) && check_acl ($id_user, $id_groups, $access)) {
316		/* Return all the user groups if it's the group All */
317		if ($id_groups == 0)
318		return array_keys (users_get_groups ($id_user, $access));
319		return array ($id_groups);
320	}
321	elseif (!is_array ($id_groups)) {
322		return array ();
323	}
324
325	foreach ($id_groups as $group) {
326		//Check ACL. If it doesn't match, remove the group
327		if (!check_acl ($id_user, $group, $access)) {
328			unset ($id_groups[$group]);
329		}
330	}
331
332	return $id_groups;
333}
334
335/**
336 * Get disabled field of a group
337 *
338 * @param int id_group Group id
339 *
340 * @return bool Disabled field of given group
341 */
342function groups_give_disabled_group ($id_group) {
343	return (bool) db_get_value ('disabled', 'tgrupo', 'id_grupo', (int) $id_group);
344}
345
346/**
347 * Test if the param array is all groups in db.
348 *
349 * @param array $id_groups
350 *
351 * @return bool It's true when the array is all groups in db.
352 */
353function groups_is_all_group($idGroups) {
354	if (!is_array($idGroups))
355	$arrayGroups = array($idGroups);
356	else
357	$arrayGroups = $idGroups;
358
359	$groupsDB = db_get_all_rows_in_table ('tgrupo');
360
361	$returnVar = true;
362	foreach ($groupsDB as $group) {
363		if (!in_array($group['id_grupo'], $arrayGroups)) {
364			$returnVar = false;
365			break;
366		}
367	}
368
369	return $returnVar;
370}
371
372/**
373 * Get group icon from group.
374 *
375 * @param int id_group Id group to get the icon
376 *
377 * @return string Icon path of the given group
378 */
379function groups_get_icon ($id_group) {
380	if ($id_group == 0) {
381		return 'world';
382	}
383	else {
384		$icon = (string) db_get_value ('icon', 'tgrupo', 'id_grupo', (int) $id_group);
385
386		if ($icon == '') {
387			$icon = 'without_group';
388		}
389
390		return $icon;
391	}
392}
393
394/**
395 * Get all groups in array with index as id_group.
396 *
397 * @param bool Whether to return All group or not
398 *
399 * @return Array with all groups selected
400 */
401function groups_get_all($groupWithAgents = false) {
402	global $config;
403
404	$sql = 'SELECT id_grupo, nombre FROM tgrupo';
405
406	global $config;
407
408	if ($groupWithAgents)
409	$sql .= ' WHERE id_grupo IN (
410		SELECT id_grupo
411		FROM tagente
412		GROUP BY id_grupo)';
413
414	switch ($config['dbtype']) {
415		case "mysql":
416		case "postgresql":
417			$sql .= ' ORDER BY nombre DESC';
418			break;
419		case "oracle":
420			$sql .= ' ORDER BY dbms_lob.substr(nombre,4000,1) DESC';
421			break;
422	}
423
424	$rows = db_get_all_rows_sql ($sql);
425
426	if ($rows === false) {
427		$rows = array();
428	}
429
430	$return = array();
431	foreach ($rows as $row) {
432		if (check_acl ($config['id_user'], $row["id_grupo"], "AR"))
433		$return[$row['id_grupo']] = $row['nombre'];
434	}
435
436	return $return;
437}
438
439/**
440 * Get all groups recursive from an initial group.
441 *
442 * @param int Id of the parent group
443 * @param bool Whether to return All group or not
444 *
445 * @return Array with all result groups
446 */
447function groups_get_id_recursive($id_parent, $all = false) {
448	$return = array();
449
450	$return = array_merge($return, array($id_parent));
451
452	//Check propagate
453	$id = db_get_value_filter('id_grupo', 'tgrupo', array('id_grupo' => $id_parent, 'propagate' => 1));
454
455	if (($id !== false) || $all) {
456		$children = db_get_all_rows_filter("tgrupo", array('parent' => $id_parent, 'disabled' => 0), array('id_grupo'));
457		if ($children === false) {
458			$children = array();
459		}
460		else {
461			$temp = array();
462			foreach ($children as $id_children) {
463				$temp = array_merge($temp, array($id_children['id_grupo']));
464			}
465			$children = $temp;
466		}
467
468		foreach ($children as $id_children) {
469			$return = array_merge($return, groups_get_id_recursive($id_children, $all));
470		}
471	}
472
473	return $return;
474}
475
476function groups_flatten_tree_groups($tree, $deep) {
477	foreach ($tree as $key => $group) {
478		$return[$key] = $group;
479		unset($return[$key]['branch']);
480		$return[$key]['deep'] = $deep;
481
482		if (!empty($group['branch'])) {
483			$return = $return +
484				groups_flatten_tree_groups($group['branch'], $deep + 1);
485		}
486	}
487
488	return $return;
489}
490
491/**
492 * Make with a list of groups a treefied list of groups.
493 *
494 * @param array $groups The list of groups to create the treefield list.
495 * @param integer $parent The id_group of parent actual scan branch.
496 * @param integer $deep The level of profundity in the branch.
497 *
498 * @return array The treefield list of groups.
499 */
500function groups_get_groups_tree_recursive($groups, $trash = 0, $trash2 = 0) {
501	$return = array();
502
503	$tree = $groups;
504	foreach($groups as $key => $group) {
505		if ($group['id_grupo'] == 0) {
506			continue;
507		}
508
509		// If the user has ACLs on a gruop but not in his father,
510		// we consider it as a son of group "all"
511		if(!in_array($group['parent'], array_keys($groups))) {
512			$group['parent'] = 0;
513		}
514
515		$tree[$group['parent']]['hash_branch'] = 1;
516		$tree[$group['parent']]['branch'][$key] = &$tree[$key];
517
518	}
519
520	// Depends on the All group we give different format
521	if (isset($groups[0])) {
522		$tree = array($tree[0]);
523	}
524	else {
525		$tree = $tree[0]['branch'];
526	}
527
528	$return = groups_flatten_tree_groups($tree, 0);
529
530	return $return;
531}
532
533/**
534 * Get agent status of a group.
535 *
536 * @param integer If of the group.
537 *
538 * @return int Status of the agents.
539 */
540function groups_get_status ($id_group = 0, $strict_user = false) {
541	global $config;
542
543	require_once ($config['homedir'].'/include/functions_reporting.php');
544
545	if ($strict_user) {
546		$acltags = tags_get_user_module_and_tags ($config['id_user'], 'AR', $strict_user);
547		$group_status = group_get_data ($config['id_user'], $strict_user, $acltags, false, 'group');
548		$data['monitor_alerts_fired'] = $groups_status['_monitors_alerts_fired_'];
549		$data['agent_critical'] = $groups_status['_agents_critical_'];
550		$data['agent_warning'] = $groups_status['_agents_warning_'];
551		$data['agent_unknown'] = $groups_status['_agents_unknown_'];
552
553	} else {
554		$data = reporting_get_group_stats($id_group);
555	}
556
557	if ($data['monitor_alerts_fired'] > 0) {
558		return AGENT_STATUS_ALERT_FIRED;
559	}
560	elseif ($data['agent_critical'] > 0) {
561		return AGENT_STATUS_CRITICAL;
562	}
563	elseif ($data['agent_warning'] > 0) {
564		return AGENT_STATUS_WARNING;
565	}
566	elseif ($data['agent_unknown'] > 0) {
567		return AGENT_STATUS_UNKNOWN;
568	}
569	else {
570		return AGENT_STATUS_NORMAL;
571	}
572}
573
574/**
575 * This function gets the group name for a given group id
576 *
577 * @param int The group id
578 * @param boolean $returnAllGroup Flag the return group, by default false.
579 *
580 * @return string The group name
581 */
582function groups_get_name ($id_group, $returnAllGroup = false) {
583	if ($id_group > 0)
584		return (string) db_get_value ('nombre', 'tgrupo', 'id_grupo', (int) $id_group);
585	elseif ($returnAllGroup)
586		return __("All");
587}
588
589/**
590 * Return the id of a group given its name.
591 *
592 * @param string Name of the group.
593 *
594 * @return int The id of the given group.
595 */
596function groups_get_id ($group_name, $returnAllGroup = false) {
597	return db_get_value ('id_grupo', 'tgrupo', 'nombre',  $group_name);
598}
599
600/**
601 * Get all the users belonging to a group.
602 *
603 * @param int $id_group The group id to look for
604 * @param mixed filter array
605 * @param bool True if users with all permissions in the group are retrieved
606 * @param bool Is id_group an array or not #Fix
607 *
608 * @return array An array with all the users or an empty array
609 */
610function groups_get_users ($id_group, $filter = false, $return_user_all = false, $_is_array = false) {
611	global $config;
612
613	if (! is_array ($filter))
614		$filter = array ();
615
616	$filter['id_grupo'] = $id_group;
617
618	$result_a = array();
619	// Juanma (05/05/2014) Fix: Check for number/array id_group variable
620	if ($_is_array && is_array($id_group) && !empty($id_group)) {
621		$result_a = db_get_all_rows_filter ("tusuario_perfil", $filter);
622	} else {
623		if (!is_array($id_group) && !empty($id_group)) {
624			$result_a = db_get_all_rows_filter ("tusuario_perfil", $filter);
625		}
626
627	}
628
629	$result_b = array();
630	if ($return_user_all) {
631		// The users of the group All (0) will be also returned
632		$filter['id_grupo'] = 0;
633		$result_b = db_get_all_rows_filter ("tusuario_perfil", $filter);
634	}
635
636	if ($result_a == false && $result_b == false)
637		$result = false;
638	elseif ($result_a == false)
639		$result = $result_b;
640	elseif ($result_b == false)
641		$result = $result_a;
642	else
643		$result = array_merge($result_a, $result_b);
644
645	if ($result === false)
646		return array ();
647
648	//This removes stale users from the list. This can happen if switched to another auth scheme
649	//(internal users still exist) or external auth has users removed/inactivated from the list (eg. LDAP)
650	$retval = array ();
651	foreach ($result as $key => $user) {
652		if (!is_user ($user)) {
653			unset ($result[$key]);
654		}
655		else {
656			array_push ($retval, get_user_info ($user));
657		}
658	}
659
660	return $retval;
661}
662
663/**
664 * Returning data for a row in the groups view (Recursive function)
665 *
666 * @param int $id_group The group id of the row
667 * @param array $group_all An array of all groups
668 * @param array $group arrayy The group name and childs
669 * @param array $printed_groups The printed groups list (by reference)
670 *
671 */
672function groups_get_group_row_data($id_group, $group_all, $group, &$printed_groups) {
673	global $config;
674
675	$rows = array();
676	$row = array();
677
678	if (isset($printed_groups[$id_group])) {
679		return;
680	}
681
682	// Store printed group to not print it again
683	$printed_groups[$id_group] = 1;
684
685	if ($id_group < 0)
686		return;
687
688	// Get stats for this group
689	$data = reporting_get_group_stats($id_group);
690
691	if ($data["total_agents"] == 0)
692		return; // Skip empty groups
693
694	// Calculate entire row color
695	if ($data["monitor_alerts_fired"] > 0) {
696		$row["status"] = "group_view_alrm";
697	}
698	elseif ($data["monitor_critical"] > 0) {
699		$row["status"] = "group_view_crit";
700	}
701	elseif ($data["monitor_warning"] > 0) {
702		$row["status"] = "group_view_warn";
703	}
704	elseif (($data["monitor_unknown"] > 0) || ($data["agents_unknown"] > 0)) {
705		$row["status"] = "group_view_unk";
706	}
707	elseif ($data["monitor_ok"] > 0) {
708		$row["status"] = "group_view_ok";
709	}
710	else {
711		$row["status"] = "group_view_normal";
712	}
713
714	// Group name
715	$group_cell = __('Group');
716	$row[$group_cell] = $group['prefix'];
717	$row[$group_cell] .= "<a href='index.php?page=agents&group=" . $id_group . "'>";
718	$row[$group_cell] .= ui_print_group_icon ($id_group, true, "groups_small", '', false);
719	$row[$group_cell] .= ui_print_truncate_text($group['name']);
720	$row[$group_cell] .= "</a>";
721
722	$row['group_name'] = ui_print_truncate_text($group['name']);
723
724	if ($id_group > 0)
725		$icon = (string) db_get_value ('icon', 'tgrupo', 'id_grupo', (int) $id_group);
726	else
727		$icon = "world";
728
729	$row['group_icon'] = html_print_image("images/groups_small/" . $icon . ".png",
730		true, false, true);
731
732	if (!isset($html)) {
733		$html = false;
734	}
735
736	//Update network group
737	if ($html) {
738		echo "<td class='group_view_data'  style='text-align: center; vertica-align: middle;'>";
739		if (check_acl ($config['id_user'], $id_group, "AW")) {
740			echo '<a href="index.php?sec=estado&sec2=operation/agentes/group_view&update_netgroup='.$id_group.'">' .
741				html_print_image("images/target.png", true, array("border" => '0', "alt" => __('Force'))) . '</a>';
742		}
743		echo "</td>";
744	}
745
746	// Total agents
747	if ($id_group != 0) {
748		$data["total_agents"] = db_get_sql ("SELECT COUNT(id_agente)
749			FROM tagente
750			WHERE id_grupo = $id_group AND disabled = 0");
751	}
752
753	// Total agents
754	$row['links'][__('Agents')] = "index.php?" .
755		"page=agents&group=" . $id_group;
756	$row['counts'][__('Agents')] = $data["total_agents"];
757
758	$row[__('Agents')] = "<a class='link_count' href='" . $row['links'][__('Agents')] . "'>";
759	$row[__('Agents')] .= $row['counts'][__('Agents')];
760	$row[__('Agents')] .= "</a>";
761
762
763	// Agents unknown
764	$row['links'][__('Agents unknown')] = "index.php?" .
765		"page=agents&group=" . $id_group . "&status=" . AGENT_STATUS_UNKNOWN;
766	$row['counts'][__('Agents unknown')] = $data["agents_unknown"];
767
768	$row[__('Agents unknown')] = "<a class='link_count' href='" . $row['counts'][__('Agents unknown')] . "'>";
769	$row[__('Agents unknown')] .= $row['counts'][__('Agents unknown')];
770	$row[__('Agents unknown')] .= "</a>";
771
772	// Monitors Unknown
773	$row['links'][__('Unknown')] = "index.php?" .
774		"page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_UNKNOWN;
775	$row['counts'][__('Unknown')] = $data["monitor_unknown"];
776
777	$row[__('Unknown')] = "<a class='link_count' href='" . $row['links'][__('Unknown')] . "'>";
778	$row[__('Unknown')] .= $row['counts'][__('Unknown')];
779	$row[__('Unknown')] .= "</a>";
780
781	// Monitors Not Init
782	$row['links'][__('Not init')] = "index.php?" .
783		"page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_NOT_INIT;
784	$row['counts'][__('Not init')] = $data["monitor_unknown"];
785
786	$row[__('Not init')] = "<a class='link_count' href='" . $row['links'][__('Not init')] . "'>";
787	$row[__('Not init')] .= $row['counts'][__('Not init')];
788	$row[__('Not init')] .= "</a>";
789
790	// Monitors OK
791	$row['links'][__('Normal')] = "index.php?" .
792		"page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_NORMAL;
793	$row['counts'][__('Normal')] = $data["monitor_ok"];
794
795	$row[__('Normal')] = "<a class='link_count' href='" . $row['links'][__('Normal')] . "'>";
796	$row[__('Normal')] .= $row['counts'][__('Normal')];
797	$row[__('Normal')] .= "</a>";
798
799	// Monitors Warning
800	$row['links'][__('Warning')] = "index.php?" .
801		"page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_WARNING;
802	$row['counts'][__('Warning')] = $data["monitor_warning"];
803
804	$row[__('Warning')] = "<a class='link_count' href='" . $row['links'][__('Warning')] . "'>";
805	$row[__('Warning')] .= $row['counts'][__('Normal')];
806	$row[__('Warning')] .= "</a>";
807
808	// Monitors Critical
809	$row['links'][__('Critical')] = "index.php?" .
810		"page=modules&group=" . $id_group . "&status=" . AGENT_MODULE_STATUS_CRITICAL_BAD;
811	$row['counts'][__('Critical')] = $data["monitor_critical"];
812
813	$row[__('Critical')] = "<a class='link_count' href='" . $row['links'][__('Critical')] . "'>";
814	$row[__('Critical')] .= $row['counts'][__('Critical')];
815	$row[__('Critical')] .= "</a>";
816
817	// Alerts fired
818	$row['links'][__('Alerts fired')] = "index.php?" .
819		"page=alerts&group=" . $id_group . "&status=fired";
820	$row['counts'][__('Alerts fired')] = $data["monitor_alerts_fired"];
821
822	$row[__('Alerts fired')] = "<a class='link_count' href='" . $row['links'][__('Alerts fired')] . "'>";
823	$row[__('Alerts fired')] .= $row['counts'][__('Alerts fired')];
824	$row[__('Alerts fired')] .= "</a>";
825
826	$rows[$id_group] = $row;
827
828	foreach($group['childs'] as $child) {
829		$sub_rows = groups_get_group_row_data($child, $group_all,
830			$group_all[$child], $printed_groups);
831
832		if (!$html) {
833			if (!empty($sub_rows))
834				$rows = $rows + $sub_rows;
835		}
836	}
837
838	return $rows;
839}
840
841function groups_get_groups_with_agent($id_user = false, $privilege = "AR", $returnAllGroup = true, $returnAllColumns = false, $id_groups = null, $keys_field = 'id_grupo') {
842	$groups = users_get_groups($id_user, $privilege, $returnAllGroup, $returnAllColumns, $id_groups, $keys_field);
843
844	$return = array();
845	foreach ($groups as $group) {
846		$data = reporting_get_group_stats($group['id_grupo']);
847
848		if ($data["total_agents"] != 0) {
849			$return[] = $group;
850		}
851	}
852
853	return $return;
854}
855
856/**
857 * Print a row in the groups view (Recursive function)
858 *
859 * @param int $id_group The group id of the row
860 * @param array $group_all An array of all groups
861 * @param array $group arrayy The group name and childs
862 * @param array $printed_groups The printed groups list (by reference)
863 *
864 */
865function groups_get_group_row($id_group, $group_all, $group, &$printed_groups) {
866	global $config;
867
868	if ($id_group < 0)
869		return;
870
871	if (isset($printed_groups[$id_group])) {
872		return;
873	}
874
875	// Store printed group to not print it again
876	$printed_groups[$id_group] = 1;
877
878	// Get stats for this group
879	$data = reporting_get_group_stats($id_group);
880
881
882	if ($data["total_agents"] == 0) {
883		if (!empty($group['childs'])) {
884			$group_childrens = groups_get_childrens($id_group, null, true);
885			$group_childrens_agents = groups_total_agents(array_keys($group_childrens));
886
887			if (empty($group_childrens_agents)) {
888				return; // Skip empty groups
889			}
890		}
891		else {
892			return; // Skip empty groups
893		}
894	}
895
896	// Calculate entire row color
897	if ($data["monitor_alerts_fired"] > 0) {
898		$group_class = 'group_view_alrm';
899		$status_image = ui_print_status_image ('agent_alertsfired_ball.png', "", true);
900	}
901	elseif ($data["monitor_critical"] > 0) {
902		$group_class = 'group_view_crit';
903		$status_image = ui_print_status_image ('agent_critical_ball.png', "", true);
904	}
905	elseif ($data["monitor_warning"] > 0) {
906		$group_class = 'group_view_warn';
907		$status_image = ui_print_status_image ('agent_warning_ball.png', "", true);
908	}
909	elseif (($data["monitor_unknown"] > 0) ||  ($data["agents_unknown"] > 0)) {
910		$group_class = 'group_view_unk';
911		$status_image = ui_print_status_image ('agent_no_monitors_ball.png', "", true);
912	}
913	elseif ($data["monitor_ok"] > 0)  {
914		$group_class = 'group_view_ok';
915		$status_image = ui_print_status_image ('agent_ok_ball.png', "", true);
916	}
917	elseif ($data["agent_not_init"] > 0)  {
918		$group_class = 'group_view_not_init';
919		$status_image = ui_print_status_image ('agent_no_data_ball.png', "", true);
920	}
921	else {
922		$group_class = 'group_view_normal';
923		$status_image = ui_print_status_image ('agent_no_data_ball.png', "", true);
924	}
925
926	ob_start();
927
928	echo "<tr style='height: 35px;'>";
929
930	// Force
931	echo "<td class='group_view_data' style='text-align: center; vertica-align: middle;'>";
932	if (check_acl ($config['id_user'], $id_group, "AW")) {
933		echo '<a href="index.php?sec=estado&sec2=operation/agentes/group_view&update_netgroup='.$id_group.'">' .
934			html_print_image("images/target.png", true, array("border" => '0', "title" => __('Force'))) . '</a>';
935	}
936	echo "</td>";
937
938	// Status
939	// echo "<td style='text-align:center;'>" . $status_image . "</td>";
940
941	// Group name
942	echo "<td class='' style='font-weight: bold; font-size: 12px;'>&nbsp;&nbsp;";
943	//echo $group['prefix'] . ui_print_group_icon ($id_group, true, "groups_small", 'font-size: 7.5pt');
944	echo "&nbsp;<a class='' href='index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id=$id_group'>";
945	echo $group['prefix'] . ui_print_truncate_text($group['name']);
946	echo "</a>";
947	echo "</td>";
948
949	// Total agents
950	echo "<td class='group_view_data $group_class' class='group_view_data' style='font-weight: bold; font-size: 18px; text-align: center;'>";
951	if ($data["total_agents"] > 0)
952		echo "<a class='group_view_data $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
953			href='index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id=$id_group'>";
954
955	//Total agent field given by function reporting_get_group_stats return the number of agents
956	//of this groups and its children. It was done to print empty fathers of children groups.
957	//We need to recalculate the total agents for this group here to get only the total agents
958	//for this group. Of course the group All (0) is a special case.
959
960	if ($id_group != 0) {
961		$data["total_agents"] = db_get_sql ("SELECT COUNT(id_agente)
962			FROM tagente
963			WHERE id_grupo = $id_group AND disabled = 0");
964	}
965
966	echo $data["total_agents"];
967	echo "</a>";
968
969	// Agents unknown
970	if ($data["agents_unknown"] > 0) {
971		echo "<td class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
972		echo "<a class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
973			href='index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id=$id_group&status=" . AGENT_STATUS_UNKNOWN ."'>";
974		echo $data["agents_unknown"];
975		echo "</a>";
976		echo "</td>";
977	}
978	else {
979		echo "<td class='$group_class'></td>";
980	}
981
982	// Agents not init
983	if ($data["agent_not_init"] > 0) {
984		echo "<td class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
985		echo "<a class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
986			href='index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id=$id_group&status=" . AGENT_STATUS_NOT_INIT ."'>";
987		echo $data["agent_not_init"];
988		echo "</a>";
989		echo "</td>";
990	}
991	else {
992		echo "<td class='$group_class'></td>";
993	}
994
995	// Monitors Unknown
996	if ($data["monitor_unknown"] > 0) {
997		echo "<td class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
998		echo "<a class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
999			href='index.php?" .
1000			"sec=estado&sec2=operation/agentes/status_monitor&ag_group=$id_group&status=" . AGENT_MODULE_STATUS_UNKNOWN . "'>";
1001		echo $data["monitor_unknown"];
1002		echo "</a>";
1003		echo "</td>";
1004	}
1005	else {
1006		echo "<td class='$group_class'></td>";
1007	}
1008
1009
1010	// Monitors Not Init
1011	if ($data["monitor_not_init"] > 0) {
1012		echo "<td class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
1013		echo "<a class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
1014			href='index.php?" .
1015			"sec=estado&sec2=operation/agentes/status_monitor&ag_group=$id_group&status=" . AGENT_MODULE_STATUS_NOT_INIT . "'>";
1016		echo $data["monitor_not_init"];
1017		echo "</a>";
1018		echo "</td>";
1019	}
1020	else {
1021		echo "<td class='$group_class'></td>";
1022	}
1023
1024
1025	// Monitors OK
1026	echo "<td class='group_view_data group_view_data_ok $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
1027	if ($data["monitor_ok"] > 0) {
1028		echo "<a class='group_view_data group_view_data_unk $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
1029			href='index.php?" .
1030			"sec=estado&sec2=operation/agentes/status_monitor&ag_group=$id_group&status=" . AGENT_MODULE_STATUS_NORMAL . "'>";
1031		echo $data["monitor_ok"];
1032		echo "</a>";
1033	}
1034	else {
1035		echo "&nbsp;";
1036	}
1037	echo "</td>";
1038
1039	// Monitors Warning
1040	if ($data["monitor_warning"] > 0) {
1041		echo "<td class='group_view_data group_view_data_warn $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
1042		echo "<a class='group_view_data group_view_data_warn $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
1043			href='index.php?" .
1044			"sec=estado&sec2=operation/agentes/status_monitor&ag_group=$id_group&status=" . AGENT_MODULE_STATUS_WARNING . "'>";
1045		echo $data["monitor_warning"];
1046		echo "</a>";
1047		echo "</td>";
1048	}
1049	else {
1050		echo "<td class='$group_class'></td>";
1051	}
1052
1053	// Monitors Critical
1054	if ($data["monitor_critical"] > 0) {
1055		echo "<td class='group_view_data group_view_data_crit $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'>";
1056		echo "<a class='group_view_data group_view_data_crit $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
1057			href='index.php?" .
1058			"sec=estado&sec2=operation/agentes/status_monitor&ag_group=$id_group&status=" . AGENT_MODULE_STATUS_CRITICAL_BAD . "'>";
1059		echo $data["monitor_critical"];
1060		echo "</a>";
1061		echo "</td>";
1062	}
1063	else {
1064		echo "<td class='$group_class'></td>";
1065	}
1066	// Alerts fired
1067	if ($data["monitor_alerts_fired"] > 0) {
1068		echo "<td class='group_view_data group_view_data_alrm $group_class' style='font-weight: bold; font-size: 18px;  text-align: center;'>";
1069		echo "<a class='group_view_data group_view_data_alrm $group_class' style='font-weight: bold; font-size: 18px; text-align: center;'
1070			href='index.php?" .
1071			"sec=estado&sec2=operation/agentes/alerts_status&ag_group=$id_group&filter=fired'>";
1072		echo $data["monitor_alerts_fired"];
1073		echo "</a>";
1074		echo "</td>";
1075	}
1076	else {
1077		echo "<td class='$group_class'></td>";
1078	}
1079
1080	echo "</tr>";
1081
1082	$row[$id_group] = ob_get_clean();
1083
1084
1085	foreach ($group['childs'] as $child) {
1086		if (array_key_exists($child, $group_all)) {
1087			$row_child = groups_get_group_row($child, $group_all, $group_all[$child], $printed_groups);
1088
1089			if (!is_array_empty($row_child)) {
1090				$row = $row + $row_child;
1091			}
1092		}
1093	}
1094
1095	return $row;
1096}
1097
1098/**
1099 * Gets a group by id_group
1100 *
1101 * @param int $id_group The group id of the row
1102 *
1103 * @return mixed Return the group row or false
1104 *
1105 */
1106function groups_get_group_by_id($id_group) {
1107	$result_group = db_get_row('tgrupo', 'id_grupo', $id_group);
1108
1109	return $result_group;
1110}
1111
1112/**
1113 * Create new group
1114 *
1115 * @param string Group name
1116 * @param array Rest of the fields of the group
1117 *
1118 * @return mixed Return group_id or false if something goes wrong
1119 *
1120 */
1121function groups_create_group($group_name, $rest_values) {
1122
1123	if ($group_name == "") {
1124		return false;
1125	}
1126
1127	$array_tmp = array('nombre' => $group_name);
1128
1129	$values = array_merge($rest_values, $array_tmp);
1130
1131	if (!isset($values['propagate'])) {
1132		$values['propagate'] = 0;
1133	}
1134	if (!isset($values['disabled'])) {
1135		$values['disabled'] = 0;
1136	}
1137
1138	$check = db_get_value('nombre', 'tgrupo', 'nombre', $group_name);
1139
1140	if (!$check) {
1141		$result = db_process_sql_insert('tgrupo', $values);
1142	}
1143	else {
1144		$result = false;
1145	}
1146
1147	return $result;
1148}
1149
1150/**
1151 * Get the number of the agents that pass the filters.
1152 *
1153 * @param mixed $group Id in integer or a set of ids into an array.
1154 * @param array $agent_filter Filter of the agents.
1155 * This filter support the following fields:
1156 * -'status': (mixed) Agent status. Single or grouped into an array. e.g.: AGENT_STATUS_CRITICAL.
1157 * -'name': (string) Agent name. e.g.: "agent_1".
1158 * @param array $module_filter Filter of the modules.
1159 * This filter support the following fields:
1160 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1161 * -'name': (string) Module name. e.g.: "module_1".
1162 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1163 * @param array $groups_and_tags Array with strict ACL rules.
1164 * @param bool $realtime Search realtime values or the values processed by the server.
1165 *
1166 * @return int Number of agents.
1167 *
1168 */
1169function groups_get_agents_counter ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1170
1171	if (empty($group)) {
1172		return 0;
1173	}
1174	else if (is_array($group)) {
1175		$groups = $group;
1176	}
1177	else {
1178		$groups = array($group);
1179	}
1180
1181	$group_str = implode (",", $groups);
1182	$groups_clause = "AND ta.id_grupo IN ($group_str)";
1183
1184	$tags_clause = "";
1185	if ($strict_user && !empty($groups_and_tags)) {
1186		foreach ($groups as $group_id) {
1187			if (isset($groups_and_tags[$group_id]) && !empty($groups_and_tags[$group_id])) {
1188				$tags_str = $groups_and_tags[$group_id];
1189				$tags_clause .= " AND (ta.grupo <> $group_id
1190									OR (ta.grupo = $group_id
1191										AND tam.id_agente_modulo NOT IN (SELECT id_agente_modulo
1192																		FROM ttag_module
1193																		WHERE id_tag NOT IN ($tags_str) )))";
1194			}
1195		}
1196	}
1197
1198	$agent_name_filter = "";
1199	$agent_status = AGENT_STATUS_ALL;
1200	if (!empty($agent_filter)) {
1201		// Name
1202		if (isset($agent_filter["name"]) && !empty($agent_filter["name"])) {
1203			$agent_name_filter = "AND ta.nombre LIKE '%" . $agent_filter["name"] . "%'";
1204		}
1205		// Status
1206		if (isset($agent_filter["status"])) {
1207			if (is_array($agent_filter["status"]))
1208				$agent_status = array_unique($agent_filter["status"]);
1209			else
1210				$agent_status = $agent_filter["status"];
1211		}
1212	}
1213
1214	$module_name_filter = "";
1215	$module_status_filter = "";
1216	$module_status_array = array();
1217	if (!empty($module_filter)) {
1218		// IMPORTANT: The module filters will force the realtime search
1219		$realtime = true;
1220
1221		// Name
1222		if (isset($module_filter["name"]) && !empty($module_filter["name"])) {
1223			$module_name_filter = "AND tam.nombre LIKE '%" . $module_filter["name"] . "%'";
1224		}
1225		// Status
1226		if (isset($module_filter["status"])) {
1227			$module_status = $module_filter["status"];
1228			if (is_array($module_status))
1229				$module_status = array_unique($module_status);
1230			else
1231				$module_status = array($module_status);
1232
1233			foreach ($module_status as $status) {
1234				switch ($status) {
1235					case AGENT_MODULE_STATUS_ALL:
1236						$module_status_array[] = AGENT_MODULE_STATUS_CRITICAL_ALERT;
1237						$module_status_array[] = AGENT_MODULE_STATUS_CRITICAL_BAD;
1238						$module_status_array[] = AGENT_MODULE_STATUS_WARNING_ALERT;
1239						$module_status_array[] = AGENT_MODULE_STATUS_WARNING;
1240						$module_status_array[] = AGENT_MODULE_STATUS_UNKNOWN;
1241						$module_status_array[] = AGENT_MODULE_STATUS_NO_DATA;
1242						$module_status_array[] = AGENT_MODULE_STATUS_NOT_INIT;
1243						$module_status_array[] = AGENT_MODULE_STATUS_NORMAL_ALERT;
1244						$module_status_array[] = AGENT_MODULE_STATUS_NORMAL;
1245						break;
1246					case AGENT_MODULE_STATUS_CRITICAL_ALERT:
1247					case AGENT_MODULE_STATUS_CRITICAL_BAD:
1248						$module_status_array[] = AGENT_MODULE_STATUS_CRITICAL_ALERT;
1249						$module_status_array[] = AGENT_MODULE_STATUS_CRITICAL_BAD;
1250						break;
1251					case AGENT_MODULE_STATUS_WARNING_ALERT:
1252					case AGENT_MODULE_STATUS_WARNING:
1253						$module_status_array[] = AGENT_MODULE_STATUS_WARNING_ALERT;
1254						$module_status_array[] = AGENT_MODULE_STATUS_WARNING;
1255						break;
1256					case AGENT_MODULE_STATUS_UNKNOWN:
1257						$module_status_array[] = AGENT_MODULE_STATUS_UNKNOWN;
1258						break;
1259					case AGENT_MODULE_STATUS_NO_DATA:
1260					case AGENT_MODULE_STATUS_NOT_INIT:
1261						$module_status_array[] = AGENT_MODULE_STATUS_NO_DATA;
1262						$module_status_array[] = AGENT_MODULE_STATUS_NOT_INIT;
1263						break;
1264					case AGENT_MODULE_STATUS_NORMAL_ALERT:
1265					case AGENT_MODULE_STATUS_NORMAL:
1266						$module_status_array[] = AGENT_MODULE_STATUS_NORMAL_ALERT;
1267						$module_status_array[] = AGENT_MODULE_STATUS_NORMAL;
1268						break;
1269				}
1270			}
1271			if (!empty($module_status_array)) {
1272				$module_status_array = array_unique($module_status_array);
1273				$status_str = implode(",", $module_status_array);
1274
1275				$module_status_filter = "INNER JOIN tagente_estado tae
1276											ON tam.id_agente_modulo = tae.id_agente_modulo
1277												AND tae.estado IN ($status_str)";
1278			}
1279		}
1280	}
1281
1282	$count = 0;
1283	// Realtime
1284	if ($realtime) {
1285		$sql = "SELECT DISTINCT ta.id_agente
1286				FROM tagente ta
1287				INNER JOIN tagente_modulo tam
1288					ON ta.id_agente = tam.id_agente
1289						AND tam.disabled = 0
1290						$module_name_filter
1291				$module_status_filter
1292				WHERE ta.disabled = 0
1293					$agent_name_filter
1294					$groups_clause
1295					$tags_clause";
1296		$agents = db_get_all_rows_sql($sql);
1297
1298		if ($agents === false)
1299			return $count;
1300
1301		if ($agent_status == AGENT_STATUS_ALL)
1302			return count($agents);
1303
1304		foreach ($agents as $agent) {
1305			$agent_filter["id"] = $agent["id_agente"];
1306
1307			$total = 0;
1308			$critical = 0;
1309			$warning = 0;
1310			$unknown = 0;
1311			$not_init = 0;
1312			$normal = 0;
1313			if (empty($module_status_array)) {
1314				$total = (int) groups_get_total_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1315				$critical = (int) groups_get_critical_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1316				$warning = (int) groups_get_warning_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1317				$unknown = (int) groups_get_unknown_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1318				$not_init = (int) groups_get_not_init_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1319				$normal = (int) groups_get_normal_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1320			}
1321			else {
1322				foreach ($module_status_array as $status) {
1323					switch ($status) {
1324						case AGENT_MODULE_STATUS_CRITICAL_ALERT:
1325						case AGENT_MODULE_STATUS_CRITICAL_BAD:
1326							$critical = (int) groups_get_critical_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1327							break;
1328						case AGENT_MODULE_STATUS_WARNING_ALERT:
1329						case AGENT_MODULE_STATUS_WARNING:
1330							$warning = (int) groups_get_warning_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1331							break;
1332						case AGENT_MODULE_STATUS_UNKNOWN:
1333							$unknown = (int) groups_get_unknown_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1334							break;
1335						case AGENT_MODULE_STATUS_NO_DATA:
1336						case AGENT_MODULE_STATUS_NOT_INIT:
1337							$not_init = (int) groups_get_not_init_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1338							break;
1339						case AGENT_MODULE_STATUS_NORMAL_ALERT:
1340						case AGENT_MODULE_STATUS_NORMAL:
1341							$normal = (int) groups_get_normal_monitors ($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1342							break;
1343					}
1344				}
1345
1346				$total = $critical + $warning + $unknown + $not_init + $normal;
1347			}
1348
1349			if (!is_array($agent_status)) {
1350				switch ($agent_status) {
1351					case AGENT_STATUS_CRITICAL:
1352						if ($critical > 0)
1353							$count ++;
1354						break;
1355					case AGENT_STATUS_WARNING:
1356						if ($total > 0 && $critical = 0 && $warning > 0)
1357							$count ++;
1358						break;
1359					case AGENT_STATUS_UNKNOWN:
1360						if ($critical == 0 && $warning == 0 && $unknown > 0)
1361							$count ++;
1362						break;
1363					case AGENT_STATUS_NOT_INIT:
1364						if ($total == 0 || $total == $not_init)
1365							$count ++;
1366						break;
1367					case AGENT_STATUS_NORMAL:
1368						if ($critical == 0 && $warning == 0 && $unknown == 0 && $normal > 0)
1369							$count ++;
1370						break;
1371					default:
1372						// The status doesn't exist
1373						return 0;
1374				}
1375			}
1376			else {
1377				if (array_search(AGENT_STATUS_CRITICAL, $agent_status) !== false) {
1378					if ($critical > 0)
1379						$count ++;
1380				}
1381				else if (array_search(AGENT_STATUS_WARNING, $agent_status) !== false) {
1382					if ($total > 0 && $critical = 0 && $warning > 0)
1383						$count ++;
1384				}
1385				else if (array_search(AGENT_STATUS_UNKNOWN, $agent_status) !== false) {
1386					if ($critical == 0 && $warning == 0 && $unknown > 0)
1387						$count ++;
1388				}
1389				else if (array_search(AGENT_STATUS_NOT_INIT, $agent_status) !== false) {
1390					if ($total == 0 || $total == $not_init)
1391						$count ++;
1392				}
1393				else if (array_search(AGENT_STATUS_NORMAL, $agent_status) !== false) {
1394					if ($critical == 0 && $warning == 0 && $unknown == 0 && $normal > 0)
1395						$count ++;
1396				}
1397				// Invalid status
1398				else {
1399					return 0;
1400				}
1401			}
1402		}
1403	}
1404	// Server processed
1405	else {
1406		$status_filter = "";
1407		// Transform the element into a one element array
1408		if (!is_array($agent_status))
1409			$agent_status = array($agent_status);
1410
1411		// Support for multiple status. It counts the agents for each status and sum the result
1412		foreach ($agent_status as $status) {
1413			switch ($agent_status) {
1414				case AGENT_STATUS_ALL:
1415					$status_filter = "";
1416					break;
1417				case AGENT_STATUS_CRITICAL:
1418					$status_filter = "AND ta.critical_count > 0";
1419					break;
1420				case AGENT_STATUS_WARNING:
1421					$status_filter = "AND ta.total_count > 0
1422									AND ta.critical_count = 0
1423									AND ta.warning_count > 0";
1424					break;
1425				case AGENT_STATUS_UNKNOWN:
1426					$status_filter = "AND ta.critical_count = 0
1427									AND ta.warning_count = 0
1428									AND ta.unknown_count > 0";
1429					break;
1430				case AGENT_STATUS_NOT_INIT:
1431					$status_filter = "AND (ta.total_count = 0
1432										OR ta.total_count = ta.notinit_count)";
1433					break;
1434				case AGENT_STATUS_NORMAL:
1435					$status_filter = "AND ta.critical_count = 0
1436									AND ta.warning_count = 0
1437									AND ta.unknown_count = 0
1438									AND ta.normal_count > 0";
1439					break;
1440				default:
1441					// The type doesn't exist
1442					return 0;
1443			}
1444
1445			$sql = "SELECT COUNT(DISTINCT ta.id_agente)
1446					FROM tagente ta
1447					WHERE ta.disabled = 0
1448						$agent_name_filter
1449						$status_filter
1450						$groups_clause";
1451
1452			$res = db_get_sql($sql);
1453			if ($res !== false)
1454				$count += $res;
1455		}
1456	}
1457
1458	return $count;
1459}
1460
1461/**
1462 * Get the number of the agents that pass the filters.
1463 *
1464 * @param mixed $group Id in integer or a set of ids into an array.
1465 * @param array $agent_filter Filter of the agents.
1466 * This filter support the following fields:
1467 * -'name': (string) Agent name. e.g.: "agent_1".
1468 * @param array $module_filter Filter of the modules.
1469 * This filter support the following fields:
1470 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1471 * -'name': (string) Module name. e.g.: "module_1".
1472 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1473 * @param array $groups_and_tags Array with strict ACL rules.
1474 * @param bool $realtime Search realtime values or the values processed by the server.
1475 *
1476 * @return int Number of agents.
1477 *
1478 */
1479function groups_get_total_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1480	// Always modify the agent status filter
1481	$agent_filter["status"] = AGENT_STATUS_ALL;
1482	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1483}
1484
1485/**
1486 * Get the number of the normal agents that pass the filters.
1487 *
1488 * @param mixed $group Id in integer or a set of ids into an array.
1489 * @param array $agent_filter Filter of the agents.
1490 * This filter support the following fields:
1491 * -'name': (string) Agent name. e.g.: "agent_1".
1492 * @param array $module_filter Filter of the modules.
1493 * This filter support the following fields:
1494 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1495 * -'name': (string) Module name. e.g.: "module_1".
1496 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1497 * @param array $groups_and_tags Array with strict ACL rules.
1498 * @param bool $realtime Search realtime values or the values processed by the server.
1499 *
1500 * @return int Number of agents.
1501 *
1502 */
1503function groups_get_normal_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1504	// Always modify the agent status filter
1505	$agent_filter["status"] = AGENT_STATUS_NORMAL;
1506	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1507}
1508
1509/**
1510 * Get the number of the critical agents that pass the filters.
1511 *
1512 * @param mixed $group Id in integer or a set of ids into an array.
1513 * @param array $agent_filter Filter of the agents.
1514 * This filter support the following fields:
1515 * -'name': (string) Agent name. e.g.: "agent_1".
1516 * @param array $module_filter Filter of the modules.
1517 * This filter support the following fields:
1518 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1519 * -'name': (string) Module name. e.g.: "module_1".
1520 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1521 * @param array $groups_and_tags Array with strict ACL rules.
1522 * @param bool $realtime Search realtime values or the values processed by the server.
1523 *
1524 * @return int Number of agents.
1525 *
1526 */
1527function groups_get_critical_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1528	// Always modify the agent status filter
1529	$agent_filter["status"] = AGENT_STATUS_CRITICAL;
1530	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1531}
1532
1533/**
1534 * Get the number of the warning agents that pass the filters.
1535 *
1536 * @param mixed $group Id in integer or a set of ids into an array.
1537 * @param array $agent_filter Filter of the agents.
1538 * This filter support the following fields:
1539 * -'name': (string) Agent name. e.g.: "agent_1".
1540 * @param array $module_filter Filter of the modules.
1541 * This filter support the following fields:
1542 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1543 * -'name': (string) Module name. e.g.: "module_1".
1544 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1545 * @param array $groups_and_tags Array with strict ACL rules.
1546 * @param bool $realtime Search realtime values or the values processed by the server.
1547 *
1548 * @return int Number of agents.
1549 *
1550 */
1551function groups_get_warning_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1552	// Always modify the agent status filter
1553	$agent_filter["status"] = AGENT_STATUS_WARNING;
1554	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1555}
1556
1557/**
1558 * Get the number of the unknown agents that pass the filters.
1559 *
1560 * @param mixed $group Id in integer or a set of ids into an array.
1561 * @param array $agent_filter Filter of the agents.
1562 * This filter support the following fields:
1563 * -'name': (string) Agent name. e.g.: "agent_1".
1564 * @param array $module_filter Filter of the modules.
1565 * This filter support the following fields:
1566 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1567 * -'name': (string) Module name. e.g.: "module_1".
1568 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1569 * @param array $groups_and_tags Array with strict ACL rules.
1570 * @param bool $realtime Search realtime values or the values processed by the server.
1571 *
1572 * @return int Number of agents.
1573 *
1574 */
1575function groups_get_unknown_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1576	// Always modify the agent status filter
1577	$agent_filter["status"] = AGENT_STATUS_UNKNOWN;
1578	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1579}
1580
1581/**
1582 * Get the number of the not init agents that pass the filters.
1583 *
1584 * @param mixed $group Id in integer or a set of ids into an array.
1585 * @param array $agent_filter Filter of the agents.
1586 * This filter support the following fields:
1587 * -'name': (string) Agent name. e.g.: "agent_1".
1588 * @param array $module_filter Filter of the modules.
1589 * This filter support the following fields:
1590 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1591 * -'name': (string) Module name. e.g.: "module_1".
1592 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1593 * @param array $groups_and_tags Array with strict ACL rules.
1594 * @param bool $realtime Search realtime values or the values processed by the server.
1595 *
1596 * @return int Number of agents.
1597 *
1598 */
1599function groups_get_not_init_agents ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1600	// Always modify the agent status filter
1601	$agent_filter["status"] = AGENT_STATUS_NOT_INIT;
1602	return groups_get_agents_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1603}
1604
1605/**
1606 * Get the number of the monitors that pass the filters.
1607 *
1608 * @param mixed $group Id in integer or a set of ids into an array.
1609 * @param array $agent_filter Filter of the agents.
1610 * This filter support the following fields:
1611 * -'name': (string) Agent name. e.g.: "agent_1".
1612 * -'id': (mixed) Agent id. e.g.: "1".
1613 * @param array $module_filter Filter of the modules.
1614 * This filter support the following fields:
1615 * -'status': (mixed) Module status. Single or grouped into an array. e.g.: AGENT_MODULE_STATUS_CRITICAL.
1616 * -'name': (string) Module name. e.g.: "module_1".
1617 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1618 * @param array $groups_and_tags Array with strict ACL rules.
1619 * @param bool $realtime Search realtime values or the values processed by the server.
1620 *
1621 * @return int Number of monitors.
1622 *
1623 */
1624function groups_get_monitors_counter ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1625
1626	if (empty($group)) {
1627		return 0;
1628	}
1629	else if (is_array($group)) {
1630		$groups = $group;
1631	}
1632	else {
1633		$groups = array($group);
1634	}
1635
1636	if ($strict_user) {
1637		$realtime = true;
1638	}
1639
1640	$group_str = implode (",", $groups);
1641	$groups_clause = "AND ta.id_grupo IN ($group_str)";
1642
1643	$tags_clause = "";
1644	if ($strict_user && !empty($groups_and_tags)) {
1645		foreach ($groups as $group_id) {
1646			if (isset($groups_and_tags[$group_id]) && !empty($groups_and_tags[$group_id])) {
1647				$tags_str = $groups_and_tags[$group_id];
1648				$tags_clause .= " AND (ta.grupo <> $group_id
1649									OR (ta.grupo = $group_id
1650										AND tam.id_agente_modulo NOT IN (SELECT id_agente_modulo
1651																		FROM ttag_module
1652																		WHERE id_tag NOT IN ($tags_str) )))";
1653			}
1654		}
1655	}
1656
1657	$agent_name_filter = "";
1658	$agents_clause = "";
1659	if (!empty($agent_filter)) {
1660		// Name
1661		if (isset($agent_filter["name"]) && !empty($agent_filter["name"])) {
1662			$agent_name_filter = "AND ta.nombre LIKE '%" . $agent_filter["name"] . "%'";
1663		}
1664		// ID
1665		if (isset($agent_filter["id"])) {
1666			if (is_array($agent_filter["id"]))
1667				$agents = array_unique($agent_filter["id"]);
1668			else
1669				$agents = array($agent_filter["id"]);
1670			$agents_str = implode (",", $agents);
1671			$agents_clause = "AND ta.id_agente IN ($agents_str)";
1672		}
1673	}
1674
1675
1676	$module_name_filter = "";
1677	$module_status_array = "";
1678	$modules_clause = "";
1679	if (!empty($module_filter)) {
1680
1681		// Name
1682		if (isset($module_filter["name"]) && !empty($module_filter["name"])) {
1683			// IMPORTANT: The module filters will force the realtime search
1684			$realtime = true;
1685
1686			$module_name_filter = "AND tam.nombre LIKE '%" . $module_filter["name"] . "%'";
1687		}
1688		// Status
1689		if (isset($module_filter["status"])) {
1690			if (is_array($module_filter["status"]))
1691				$module_status = array_unique($module_filter["status"]);
1692			else
1693				$module_status = array($module_filter["status"]);
1694
1695			$status_array = "";
1696			foreach ($module_status as $status) {
1697				switch ($status) {
1698					case AGENT_MODULE_STATUS_ALL:
1699						$status_array[] = AGENT_MODULE_STATUS_CRITICAL_ALERT;
1700						$status_array[] = AGENT_MODULE_STATUS_CRITICAL_BAD;
1701						$status_array[] = AGENT_MODULE_STATUS_WARNING_ALERT;
1702						$status_array[] = AGENT_MODULE_STATUS_WARNING;
1703						$status_array[] = AGENT_MODULE_STATUS_UNKNOWN;
1704						$status_array[] = AGENT_MODULE_STATUS_NO_DATA;
1705						$status_array[] = AGENT_MODULE_STATUS_NOT_INIT;
1706						$status_array[] = AGENT_MODULE_STATUS_NORMAL_ALERT;
1707						$status_array[] = AGENT_MODULE_STATUS_NORMAL;
1708						break;
1709					case AGENT_MODULE_STATUS_CRITICAL_ALERT:
1710					case AGENT_MODULE_STATUS_CRITICAL_BAD:
1711						$status_array[] = AGENT_MODULE_STATUS_CRITICAL_ALERT;
1712						$status_array[] = AGENT_MODULE_STATUS_CRITICAL_BAD;
1713						break;
1714					case AGENT_MODULE_STATUS_WARNING_ALERT:
1715					case AGENT_MODULE_STATUS_WARNING:
1716						$status_array[] = AGENT_MODULE_STATUS_WARNING_ALERT;
1717						$status_array[] = AGENT_MODULE_STATUS_WARNING;
1718						break;
1719					case AGENT_MODULE_STATUS_UNKNOWN:
1720						$status_array[] = AGENT_MODULE_STATUS_UNKNOWN;
1721						break;
1722					case AGENT_MODULE_STATUS_NO_DATA:
1723					case AGENT_MODULE_STATUS_NOT_INIT:
1724						$status_array[] = AGENT_MODULE_STATUS_NO_DATA;
1725						$status_array[] = AGENT_MODULE_STATUS_NOT_INIT;
1726						break;
1727					case AGENT_MODULE_STATUS_NORMAL_ALERT:
1728					case AGENT_MODULE_STATUS_NORMAL:
1729						$status_array[] = AGENT_MODULE_STATUS_NORMAL_ALERT;
1730						$status_array[] = AGENT_MODULE_STATUS_NORMAL;
1731						break;
1732					default:
1733						// The status doesn't exist
1734						return 0;
1735				}
1736			}
1737			if (!empty($status_array)) {
1738				$status_array = array_unique($status_array);
1739				$status_str = implode(",", $status_array);
1740
1741				$modules_clause = "AND tae.estado IN ($status_str)";
1742			}
1743		}
1744	}
1745
1746	if ($realtime) {
1747		$sql = "SELECT COUNT(DISTINCT tam.id_agente_modulo)
1748				FROM tagente_modulo tam
1749				INNER JOIN tagente_estado tae
1750					ON tam.id_agente_modulo = tae.id_agente_modulo
1751						$modules_clause
1752				INNER JOIN tagente ta
1753					ON tam.id_agente = ta.id_agente
1754						AND ta.disabled = 0
1755						$agent_name_filter
1756						$agents_clause
1757						$groups_clause
1758				WHERE tam.disabled = 0
1759					$module_name_filter
1760					$tags_clause";
1761	}
1762	else {
1763		$status_columns_array = array();
1764		foreach ($module_status_array as $status) {
1765			switch ($status) {
1766				case AGENT_MODULE_STATUS_CRITICAL_ALERT:
1767				case AGENT_MODULE_STATUS_CRITICAL_BAD:
1768					$status_columns_array[] = 'ta.critical_count';
1769					break;
1770				case AGENT_MODULE_STATUS_WARNING_ALERT:
1771				case AGENT_MODULE_STATUS_WARNING:
1772					$status_columns_array[] = 'ta.warning_count';
1773					break;
1774				case AGENT_MODULE_STATUS_UNKNOWN:
1775					$status_columns_array[] = 'ta.unknown_count';
1776					break;
1777				case AGENT_MODULE_STATUS_NO_DATA:
1778				case AGENT_MODULE_STATUS_NOT_INIT:
1779					$status_columns_array[] = 'ta.notinit_count';
1780					break;
1781				case AGENT_MODULE_STATUS_NORMAL_ALERT:
1782				case AGENT_MODULE_STATUS_NORMAL:
1783					$status_columns_array[] = 'ta.normal_count';
1784					break;
1785				default:
1786					// The type doesn't exist
1787					return 0;
1788			}
1789		}
1790		if (empty($status_columns_array))
1791			return 0;
1792
1793		$status_columns_str = implode(",", $status_columns_array);
1794
1795		$sql = "SELECT SUM($status_columns_str)
1796				FROM tagente ta
1797				WHERE ta.disabled = 0
1798					$agent_name_filter
1799					$agents_clause
1800					$groups_clause
1801					$tags_clause";
1802	}
1803
1804	$count = (int) db_get_sql ($sql);
1805
1806	return $count;
1807}
1808
1809/**
1810 * Get the number of the monitors that pass the filters.
1811 *
1812 * @param mixed $group Id in integer or a set of ids into an array.
1813 * @param array $agent_filter Filter of the agents.
1814 * This filter support the following fields:
1815 * -'name': (string) Agent name. e.g.: "agent_1".
1816 * -'id': (int/array) Agent id. e.g.: "1".
1817 * @param array $module_filter Filter of the modules.
1818 * This filter support the following fields:
1819 * -'name': (string) Module name. e.g.: "module_1".
1820 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1821 * @param array $groups_and_tags Array with strict ACL rules.
1822 * @param bool $realtime Search realtime values or the values processed by the server.
1823 *
1824 * @return int Number of monitors.
1825 *
1826 */
1827function groups_get_total_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1828	// Always modify the module status filter
1829	$module_filter["status"] = AGENT_MODULE_STATUS_ALL;
1830	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1831}
1832
1833/**
1834 * Get the number of the normal monitors that pass the filters.
1835 *
1836 * @param mixed $group Id in integer or a set of ids into an array.
1837 * @param array $agent_filter Filter of the agents.
1838 * This filter support the following fields:
1839 * -'name': (string) Agent name. e.g.: "agent_1".
1840 * -'id': (int/array) Agent id. e.g.: "1".
1841 * @param array $module_filter Filter of the modules.
1842 * This filter support the following fields:
1843 * -'name': (string) Module name. e.g.: "module_1".
1844 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1845 * @param array $groups_and_tags Array with strict ACL rules.
1846 * @param bool $realtime Search realtime values or the values processed by the server.
1847 *
1848 * @return int Number of monitors.
1849 *
1850 */
1851function groups_get_normal_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1852	// Always modify the module status filter
1853	$module_filter["status"] = AGENT_MODULE_STATUS_NORMAL;
1854	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1855}
1856
1857/**
1858 * Get the number of the critical monitors that pass the filters.
1859 *
1860 * @param mixed $group Id in integer or a set of ids into an array.
1861 * @param array $agent_filter Filter of the agents.
1862 * This filter support the following fields:
1863 * -'name': (string) Agent name. e.g.: "agent_1".
1864 * -'id': (int/array) Agent id. e.g.: "1".
1865 * @param array $module_filter Filter of the modules.
1866 * This filter support the following fields:
1867 * -'name': (string) Module name. e.g.: "module_1".
1868 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1869 * @param array $groups_and_tags Array with strict ACL rules.
1870 * @param bool $realtime Search realtime values or the values processed by the server.
1871 *
1872 * @return int Number of monitors.
1873 *
1874 */
1875function groups_get_critical_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1876	// Always modify the module status filter
1877	$module_filter["status"] = AGENT_MODULE_STATUS_CRITICAL_BAD;
1878	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1879}
1880
1881/**
1882 * Get the number of the warning monitors that pass the filters.
1883 *
1884 * @param mixed $group Id in integer or a set of ids into an array.
1885 * @param array $agent_filter Filter of the agents.
1886 * This filter support the following fields:
1887 * -'name': (string) Agent name. e.g.: "agent_1".
1888 * -'id': (int/array) Agent id. e.g.: "1".
1889 * @param array $module_filter Filter of the modules.
1890 * This filter support the following fields:
1891 * -'name': (string) Module name. e.g.: "module_1".
1892 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1893 * @param array $groups_and_tags Array with strict ACL rules.
1894 * @param bool $realtime Search realtime values or the values processed by the server.
1895 *
1896 * @return int Number of monitors.
1897 *
1898 */
1899function groups_get_warning_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1900	// Always modify the module status filter
1901	$module_filter["status"] = AGENT_MODULE_STATUS_WARNING;
1902	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1903}
1904
1905/**
1906 * Get the number of the unknown monitors that pass the filters.
1907 *
1908 * @param mixed $group Id in integer or a set of ids into an array.
1909 * @param array $agent_filter Filter of the agents.
1910 * This filter support the following fields:
1911 * -'name': (string) Agent name. e.g.: "agent_1".
1912 * -'id': (int/array) Agent id. e.g.: "1".
1913 * @param array $module_filter Filter of the modules.
1914 * This filter support the following fields:
1915 * -'name': (string) Module name. e.g.: "module_1".
1916 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1917 * @param array $groups_and_tags Array with strict ACL rules.
1918 * @param bool $realtime Search realtime values or the values processed by the server.
1919 *
1920 * @return int Number of monitors.
1921 *
1922 */
1923function groups_get_unknown_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1924	// Always modify the module status filter
1925	$module_filter["status"] = AGENT_MODULE_STATUS_UNKNOWN;
1926	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1927}
1928
1929/**
1930 * Get the number of the not init monitors that pass the filters.
1931 *
1932 * @param mixed $group Id in integer or a set of ids into an array.
1933 * @param array $agent_filter Filter of the agents.
1934 * This filter support the following fields:
1935 * -'name': (string) Agent name. e.g.: "agent_1".
1936 * -'id': (int/array) Agent id. e.g.: "1".
1937 * @param array $module_filter Filter of the modules.
1938 * This filter support the following fields:
1939 * -'name': (string) Module name. e.g.: "module_1".
1940 * @param bool $strict_user If the user has enabled the strict ACL mode or not.
1941 * @param array $groups_and_tags Array with strict ACL rules.
1942 * @param bool $realtime Search realtime values or the values processed by the server.
1943 *
1944 * @return int Number of monitors.
1945 *
1946 */
1947function groups_get_not_init_monitors ($group, $agent_filter = array(), $module_filter = array(), $strict_user = false, $groups_and_tags = false, $realtime = false) {
1948	// Always modify the module status filter
1949	$module_filter["status"] = AGENT_MODULE_STATUS_NOT_INIT;
1950	return groups_get_monitors_counter($group, $agent_filter, $module_filter, $strict_user, $groups_and_tags, $realtime);
1951}
1952
1953// Get alerts defined for a given group, except disabled
1954
1955function groups_monitor_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
1956
1957	// If there are not groups to query, we jump to nextone
1958
1959	if (empty ($group_array)) {
1960		return 0;
1961
1962	}
1963	else if (!is_array ($group_array)) {
1964		$group_array = array($group_array);
1965	}
1966
1967	$group_clause = implode (",", $group_array);
1968	$group_clause = "(" . $group_clause . ")";
1969
1970	if ($strict_user) {
1971		$sql = "SELECT COUNT(talert_template_modules.id)
1972			FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
1973			WHERE tagente.id_grupo = $id_group_strict AND tagente_modulo.id_agente = tagente.id_agente
1974				AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
1975				AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
1976				AND	talert_template_modules.disabled = 0
1977				AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo";
1978		$count = db_get_sql ($sql);
1979		return $count;
1980	} else {
1981		//TODO REVIEW ORACLE AND POSTGRES
1982		return db_get_sql ("SELECT COUNT(talert_template_modules.id)
1983			FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
1984			WHERE tagente.id_grupo IN $group_clause AND tagente_modulo.id_agente = tagente.id_agente
1985				AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
1986				AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
1987				AND	talert_template_modules.disabled = 0
1988				AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo");
1989	}
1990}
1991
1992// Get alert configured currently FIRED, except disabled
1993
1994function groups_monitor_fired_alerts ($group_array, $strict_user = false, $id_group_strict = false) {
1995
1996	// If there are not groups to query, we jump to nextone
1997
1998	if (empty ($group_array)) {
1999		return 0;
2000
2001	}
2002	else if (!is_array ($group_array)) {
2003		$group_array = array($group_array);
2004	}
2005
2006	$group_clause = implode (",", $group_array);
2007	$group_clause = "(" . $group_clause . ")";
2008
2009	if ($strict_user) {
2010		$sql = "SELECT COUNT(talert_template_modules.id)
2011		FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
2012		WHERE tagente.id_grupo = $id_group_strict AND tagente_modulo.id_agente = tagente.id_agente
2013			AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
2014			AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
2015			AND talert_template_modules.disabled = 0
2016			AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo
2017			AND times_fired > 0 ";
2018
2019		$count = db_get_sql ($sql);
2020		return $count;
2021	} else {
2022		//TODO REVIEW ORACLE AND POSTGRES
2023		return db_get_sql ("SELECT COUNT(talert_template_modules.id)
2024			FROM talert_template_modules, tagente_modulo, tagente_estado, tagente
2025			WHERE tagente.id_grupo IN $group_clause AND tagente_modulo.id_agente = tagente.id_agente
2026				AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
2027				AND tagente_modulo.disabled = 0 AND tagente.disabled = 0
2028				AND talert_template_modules.disabled = 0
2029				AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo
2030				AND times_fired > 0");
2031	}
2032
2033}
2034
2035/**
2036 *  Total agents in a group, (by default except disabled ones)
2037 *
2038 * @param mixed Array or (comma separated) string with groups
2039 * @param bool Whether to count disabled agents
2040 *
2041 * @return mixed Return group count or false if something goes wrong
2042 *
2043 */
2044function groups_total_agents ($group_array, $disabled = false) {
2045
2046	if (empty ($group_array)) {
2047		return 0;
2048
2049	}
2050	else if (!is_array ($group_array)) {
2051		$group_array = array($group_array);
2052	}
2053
2054	$group_clause = implode (",", $group_array);
2055	$group_clause = "(" . $group_clause . ")";
2056
2057	$sql = "SELECT COUNT(*) FROM tagente WHERE id_grupo IN $group_clause";
2058
2059	if (!$disabled)
2060		$sql .= " AND disabled = 0";
2061
2062	return db_get_sql ($sql);
2063}
2064
2065/**
2066 *  Number of disabled agents in a group
2067 *
2068 * @param mixed Array or (comma separated) string with groups
2069 *
2070 * @return mixed Return group count or false if something goes wrong
2071 *
2072 */
2073function groups_agent_disabled ($group_array) {
2074
2075	if (empty ($group_array)) {
2076		return 0;
2077
2078	}
2079	else if (!is_array ($group_array)) {
2080		$group_array = array($group_array);
2081	}
2082
2083	$group_clause = implode (",", $group_array);
2084	$group_clause = "(" . $group_clause . ")";
2085
2086	$sql = "SELECT COUNT(*) FROM tagente WHERE id_grupo IN $group_clause AND disabled = 1";
2087
2088	return db_get_sql ($sql);
2089}
2090
2091/**
2092 *  Return a group row for Groups managment list
2093 *
2094 * @param mixed Group info
2095 * @param int total number of groups
2096 * @param string (ref) Concatenation of branches class with the parent classes
2097 *
2098 * @return mixed Row with html_print_table format
2099 *
2100 */
2101function groups_get_group_to_list($group, $groups_count, &$symbolBranchs) {
2102	$tabulation = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $group['deep']);
2103
2104	if ($group['id_grupo'] == 0) {
2105		$symbol = '-';
2106	}
2107	else {
2108		$symbol = '+';
2109	}
2110
2111	$group_hash_branch = false;
2112	if (isset($group['hash_branch'])) {
2113		$group_hash_branch = $group['hash_branch'];
2114	}
2115
2116	if ($group_hash_branch) {
2117		$data[0] = '<strong>'.$tabulation . ' ' .
2118			'<a href="javascript: showBranch(' . $group['id_grupo'] .
2119			', ' . $group['parent'] . ');" title="' . __('Show branch children') .
2120			'"><span class="symbol_' . $group['id_grupo'] . ' ' . $symbolBranchs . '">' .
2121			$symbol . '</span> '. ui_print_truncate_text($group['nombre']) . '</a></strong>';
2122	}
2123	else {
2124		$data[0] = '<strong>' . $tabulation . ' ' . ui_print_truncate_text($group['nombre']) . '</strong>';
2125	}
2126	$data[1] = $group['id_grupo'];
2127	$data[2] = ui_print_group_icon($group['id_grupo'], true);
2128	$data[3] = $group['disabled'] ? __('Disabled') : __('Enabled');
2129	$data[4] = $group['description'];
2130	if ($group['id_grupo'] == 0) {
2131		$data[5] = '';
2132	}
2133	else {
2134		$data[5] = '<a href="index.php?sec=gagente&' .
2135			'sec2=godmode/groups/configure_group&' .
2136			'id_group=' . $group['id_grupo'] . '">' . html_print_image("images/config.png", true, array("alt" => __('Edit'), "title" => __('Edit'), "border" => '0'));
2137		//Check if there is only a group to unable delete it
2138		if ($groups_count > 2) {
2139			$data[5] .= '&nbsp;&nbsp;' .
2140				'<a href="index.php?sec=gagente&' .
2141					'sec2=godmode/groups/group_list&' .
2142					'id_group=' . $group['id_grupo'] . '&' .
2143					'delete_group=1" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">' . html_print_image("images/cross.png", true, array("alt" => __('Delete'), "border" => '0'));
2144		}
2145		else {
2146			$data[5] .= '&nbsp;&nbsp;' .
2147				ui_print_help_tip(
2148					__('You can not delete the last group in Pandora. A common installation must has almost one group.'), true);
2149		}
2150	}
2151
2152	return $data;
2153}
2154
2155/**
2156 * Store to be printed the subgroups rows (Recursive)
2157 *
2158 * @param mixed Group info
2159 * @param mixed Hash list with all the groups of 2nd or higher level
2160 * @param string (ref) Concatenation of branches classes to control the symbols from Javascript
2161 * @param int total number of groups
2162 * @param obj (ref) table object in html_print_table format with the stored groups
2163 * @param int (ref) counter of the row stored
2164 * @param string (ref) Concatenation of branches class with the parent classes
2165 *
2166 */
2167function groups_print_group_sons($group, $sons, &$branch_classes, $groups_count, &$table, &$iterator, &$symbolBranchs) {
2168	if (isset($sons[$group['id_grupo']])) {
2169		foreach($sons[$group['id_grupo']] as $key => $g) {
2170			$symbolBranchs .= ' symbol_branch_' . $g['parent'];
2171
2172			$data = groups_get_group_to_list($g, $groups_count, $symbolBranchs);
2173			array_push ($table->data, $data);
2174
2175			$branch_classes[$g['id_grupo']] = $branch_classes[$g['parent']] . ' branch_' . $g['parent'];
2176			$table->rowclass[$iterator] = 'parent_' . $g['parent'] . $branch_classes[$g['id_grupo']];
2177
2178			if ($g['deep'] == 0) {
2179				$table->rowstyle[$iterator] = '';
2180			}
2181			else {
2182				if ($g['parent'] != 0) {
2183					$table->rowstyle[$iterator] = 'display: none;';
2184				}
2185			}
2186
2187			$iterator++;
2188
2189			groups_print_group_sons($g, $sons, $branch_classes, $groups_count, $table, $iterator, $symbolBranchs);
2190		}
2191	}
2192}
2193
2194/**
2195 * Return an array with the groups hierarchy (Recursive)
2196 *
2197 * @param array Groups array passed by reference
2198 * @param mixed The id of the parent to search or false to begin the search from the first hierarchy level
2199 *
2200 * @return array The groups reordered by its hierarchy
2201 */
2202function groups_get_tree(&$groups, $parent = false) {
2203	$return = array();
2204
2205	foreach ($groups as $id => $group) {
2206		if ($parent === false && (!isset($group['parent']) || $group['parent'] == 0 || !in_array($group['parent'], $groups))) {
2207			$return[$id] = $group;
2208			unset($groups[$id]);
2209			$children = groups_get_tree($groups, $id);
2210
2211			if (!empty($children)) {
2212				$return[$id]['children'] = $children;
2213			}
2214		}
2215		else if ($parent && isset($group['parent']) && $group['parent'] == $parent) {
2216			$return[$id] = $group;
2217			unset($groups[$id]);
2218			$children = groups_get_tree($groups, $id);
2219
2220			if (!empty($children)) {
2221				$return[$id]['children'] = $children;
2222			}
2223		}
2224		else {
2225			continue;
2226		}
2227	}
2228
2229	return $return;
2230}
2231function groups_get_all_hierarchy_group ($id_group, $hierarchy = array()) {
2232	global $config;
2233
2234	if ($id_group == 0) {
2235		$hierarchy = groups_get_childrens($id_group);
2236	}
2237	else {
2238		$hierarchy[] = $id_group;
2239		$parent = db_get_value('parent','tgrupo','id_grupo',$id_group);
2240
2241		if ($parent !== 0) {
2242			$propagate = db_get_value('propagate','tgrupo','id_grupo',$parent);
2243
2244			if ($propagate == 1) {
2245				//$childrens_ids_parent = array($parent);
2246				$hierarchy[] = $parent;
2247				$childrens = groups_get_childrens($parent);
2248				if (!empty($childrens)) {
2249					foreach ($childrens as $child) {
2250						//$childrens_ids_parent[] = (int)$child['id_grupo'];
2251						$hierarchy[] = (int)$child['id_grupo'];
2252					}
2253				}
2254
2255				$hierarchy = groups_get_all_hierarchy_group ($parent, $hierarchy);
2256			}
2257		}
2258	}
2259	return $hierarchy;
2260}
2261
2262function group_get_data ($id_user = false, $user_strict = false, $acltags, $returnAllGroup = false, $mode = 'group', $agent_filter = array(), $module_filter = array()) {
2263	global $config;
2264	if ($id_user == false) {
2265		$id_user = $config['id_user'];
2266	}
2267
2268	$user_groups = array();
2269	$user_tags = array();
2270	$groups_without_tags = array();
2271	foreach ($acltags as $group => $tags) {
2272		if ($user_strict) { //Remove groups with tags
2273			if ($tags == '') {
2274				$groups_without_tags[$group] = $group;
2275			}
2276		}
2277		$user_groups[$group] = groups_get_name($group);
2278		if ($tags != '') {
2279			$tags_group = explode(',', $tags);
2280
2281			foreach ($tags_group as $tag) {
2282				$user_tags[$tag] = tags_get_name($tag);
2283			}
2284		}
2285	}
2286
2287	if ($user_strict) {
2288		$user_groups_ids = implode(',', array_keys($groups_without_tags));
2289	}
2290	else {
2291		$user_groups_ids = implode(',', array_keys($acltags));
2292	}
2293
2294	if (!empty($user_groups_ids)) {
2295		switch ($config["dbtype"]) {
2296			case "mysql":
2297				$list_groups = db_get_all_rows_sql("
2298					SELECT *
2299					FROM tgrupo
2300					WHERE id_grupo IN (" . $user_groups_ids . ")
2301					ORDER BY nombre COLLATE utf8_general_ci ASC");
2302				break;
2303			case "postgresql":
2304				$list_groups = db_get_all_rows_sql("
2305					SELECT *
2306					FROM tgrupo
2307					WHERE id_grupo IN (" . $user_groups_ids . ")
2308					ORDER BY nombre ASC");
2309				break;
2310			case "oracle":
2311				$list_groups = db_get_all_rows_sql("
2312					SELECT *
2313					FROM tgrupo
2314					WHERE id_grupo IN (" . $user_groups_ids . ")
2315					ORDER BY nombre ASC");
2316				break;
2317		}
2318	}
2319
2320	$list = array();
2321
2322	if ($list_groups == false) {
2323		$list_groups = array();
2324	}
2325
2326	if ($returnAllGroup) {
2327		$i = 1;
2328		$list[0]['_id_'] = 0;
2329		$list[0]['_name_'] = __('All');
2330
2331		$list[0]['_agents_unknown_'] = 0;
2332		$list[0]['_monitors_alerts_fired_'] = 0;
2333		$list[0]['_total_agents_'] = 0;
2334		$list[0]['_monitors_ok_'] = 0;
2335		$list[0]['_monitors_critical_'] = 0;
2336		$list[0]['_monitors_warning_'] = 0;
2337		$list[0]['_monitors_unknown_'] = 0;
2338		$list[0]['_monitors_not_init_'] = 0;
2339		$list[0]['_agents_not_init_'] = 0;
2340
2341		if ($mode == 'tactical') {
2342			$list[0]['_agents_ok_'] = 0;
2343			$list[0]['_agents_warning_'] = 0;
2344			$list[0]['_agents_critical_'] = 0;
2345			$list[0]['_monitors_alerts_'] = 0;
2346		}
2347	}
2348	else {
2349		$i = 0;
2350	}
2351
2352	/*
2353	 * Agent cache for metaconsole.
2354	 * Retrieve the statistic data from the cache table.
2355	 */
2356	if (!$user_strict && is_metaconsole() && !empty($list_groups)) {
2357		$cache_table = 'tmetaconsole_agent';
2358
2359		$sql_stats = "SELECT id_grupo, COUNT(id_agente) AS agents_total,
2360						SUM(total_count) AS monitors_total,
2361						SUM(normal_count) AS monitors_ok,
2362						SUM(warning_count) AS monitors_warning,
2363						SUM(critical_count) AS monitors_critical,
2364						SUM(unknown_count) AS monitors_unknown,
2365						SUM(notinit_count) AS monitors_not_init,
2366						SUM(fired_count) AS alerts_fired
2367					  FROM $cache_table
2368					  WHERE disabled = 0
2369					  	AND id_grupo IN ($user_groups_ids)
2370					  GROUP BY id_grupo";
2371		$data_stats = db_get_all_rows_sql($sql_stats);
2372
2373		$sql_stats_unknown = "SELECT id_grupo, COUNT(id_agente) AS agents_unknown
2374							  FROM $cache_table
2375							  WHERE disabled = 0
2376							  	AND id_grupo IN ($user_groups_ids)
2377							  	AND critical_count = 0
2378							  	AND warning_count = 0
2379							  	AND unknown_count > 0
2380							  GROUP BY id_grupo";
2381		$data_stats_unknown = db_get_all_rows_sql($sql_stats_unknown);
2382
2383		$sql_stats_not_init = "SELECT id_grupo, COUNT(id_agente) AS agents_not_init
2384							  FROM $cache_table
2385							  WHERE disabled = 0
2386							  	AND id_grupo IN ($user_groups_ids)
2387							  	AND (total_count = 0 OR total_count = notinit_count)
2388							  GROUP BY id_grupo";
2389		$data_stats_not_init = db_get_all_rows_sql($sql_stats_not_init);
2390
2391		if ($mode == 'tactical' || $mode == 'tree') {
2392			$sql_stats_ok = "SELECT id_grupo, COUNT(id_agente) AS agents_ok
2393							 FROM $cache_table
2394							 WHERE disabled = 0
2395							 	AND id_grupo IN ($user_groups_ids)
2396							 	AND critical_count = 0
2397							 	AND warning_count = 0
2398							 	AND unknown_count = 0
2399							 	AND normal_count > 0
2400							 GROUP BY id_grupo";
2401			$data_stats_ok = db_get_all_rows_sql($sql_stats_ok);
2402
2403			$sql_stats_warning = "SELECT id_grupo, COUNT(id_agente) AS agents_warning
2404								  FROM $cache_table
2405								  WHERE disabled = 0
2406								  	AND id_grupo IN ($user_groups_ids)
2407								  	AND critical_count = 0
2408								  	AND warning_count > 0
2409								  GROUP BY id_grupo";
2410			$data_stats_warning = db_get_all_rows_sql($sql_stats_warning);
2411
2412			$sql_stats_critical = "SELECT id_grupo, COUNT(id_agente) AS agents_critical
2413									FROM $cache_table
2414									WHERE disabled = 0
2415										AND id_grupo IN ($user_groups_ids)
2416										AND critical_count > 0
2417									GROUP BY id_grupo";
2418			$data_stats_critical = db_get_all_rows_sql($sql_stats_critical);
2419		}
2420
2421		$stats_by_group = array();
2422		if (!empty($data_stats)) {
2423			foreach ($data_stats as $value) {
2424				$group_id = (int) $value['id_grupo'];
2425
2426				$stats = array();
2427				$stats['agents_total'] = (int) $value['agents_total'];
2428				$stats['monitors_total'] = (int) $value['monitors_total'];
2429				$stats['monitors_ok'] = (int) $value['monitors_ok'];
2430				$stats['monitors_warning'] = (int) $value['monitors_warning'];
2431				$stats['monitors_critical'] = (int) $value['monitors_critical'];
2432				$stats['monitors_unknown'] = (int) $value['monitors_unknown'];
2433				$stats['monitors_not_init'] = (int) $value['monitors_not_init'];
2434				$stats['alerts_fired'] = (int) $value['alerts_fired'];
2435				$stats_by_group[$group_id] = $stats;
2436			}
2437
2438			if (!empty($stats_by_group)) {
2439				if (!empty($data_stats_unknown)) {
2440					foreach ($data_stats_unknown as $value) {
2441						$group_id = (int) $value['id_grupo'];
2442						if (isset($stats_by_group[$group_id])) {
2443							$stats_by_group[$group_id]['agents_unknown'] = (int) $value['agents_unknown'];
2444						}
2445					}
2446				}
2447				if (!empty($data_stats_not_init)) {
2448					foreach ($data_stats_not_init as $value) {
2449						$group_id = (int) $value['id_grupo'];
2450						if (isset($stats_by_group[$group_id])) {
2451							$stats_by_group[$group_id]['agents_not_init'] = (int) $value['agents_not_init'];
2452						}
2453					}
2454				}
2455				if (!empty($data_stats_ok)) {
2456					foreach ($data_stats_ok as $value) {
2457						$group_id = (int) $value['id_grupo'];
2458						if (isset($stats_by_group[$group_id])) {
2459							$stats_by_group[$group_id]['agents_ok'] = (int) $value['agents_ok'];
2460						}
2461					}
2462				}
2463				if (!empty($data_stats_warning)) {
2464					foreach ($data_stats_warning as $value) {
2465						$group_id = (int) $value['id_grupo'];
2466						if (isset($stats_by_group[$group_id])) {
2467							$stats_by_group[$group_id]['agents_warning'] = (int) $value['agents_warning'];
2468						}
2469					}
2470				}
2471				if (!empty($data_stats_critical)) {
2472					foreach ($data_stats_critical as $value) {
2473						$group_id = (int) $value['id_grupo'];
2474						if (isset($stats_by_group[$group_id])) {
2475							$stats_by_group[$group_id]['agents_critical'] = (int) $value['agents_critical'];
2476						}
2477					}
2478				}
2479			}
2480		}
2481	}
2482
2483	foreach ($list_groups as $key => $item) {
2484		$id = $item['id_grupo'];
2485
2486		if (!$user_strict && is_metaconsole()) { // Agent cache
2487			$group_stat = array();
2488			if (isset($stats_by_group[$id]))
2489				$group_stat = $stats_by_group[$id];
2490
2491			$list[$i]['_id_'] = $id;
2492			$list[$i]['_name_'] = $item['nombre'];
2493			$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
2494
2495			if ($mode == 'tree' && !empty($item['parent']))
2496				$list[$i]['_parent_id_'] = $item['parent'];
2497
2498			$list[$i]['_agents_unknown_'] = isset($group_stat['agents_unknown']) ? $group_stat['agents_unknown'] : 0;
2499			$list[$i]['_monitors_alerts_fired_'] = isset($group_stat['alerts_fired']) ? $group_stat['alerts_fired'] : 0;
2500			$list[$i]['_total_agents_'] = isset($group_stat['agents_total']) ? $group_stat['agents_total'] : 0;
2501
2502			// This fields are not in database
2503			$list[$i]['_monitors_ok_'] = isset($group_stat['monitors_ok']) ? $group_stat['monitors_ok'] : 0;
2504			$list[$i]['_monitors_critical_'] = isset($group_stat['monitors_critical']) ? $group_stat['monitors_critical'] : 0;
2505			$list[$i]['_monitors_warning_'] = isset($group_stat['monitors_warning']) ? $group_stat['monitors_warning'] : 0;
2506			$list[$i]['_monitors_unknown_'] = isset($group_stat['monitors_unknown']) ? $group_stat['monitors_unknown'] : 0;
2507			$list[$i]['_monitors_not_init_'] = isset($group_stat['monitors_not_init']) ? $group_stat['monitors_not_init'] : 0;
2508			$list[$i]['_agents_not_init_'] = isset($group_stat['agents_not_init']) ? $group_stat['agents_not_init'] : 0;
2509
2510			if ($mode == 'tactical' || $mode == 'tree') {
2511				$list[$i]['_agents_ok_'] = isset($group_stat['agents_ok']) ? $group_stat['agents_ok'] : 0;
2512				$list[$i]['_agents_warning_'] = isset($group_stat['agents_warning']) ? $group_stat['agents_warning'] : 0;
2513				$list[$i]['_agents_critical_'] = isset($group_stat['agents_critical']) ? $group_stat['agents_critical'] : 0;
2514				$list[$i]['_monitors_alerts_'] =  isset($group_stat['alerts']) ? $group_stat['alerts'] : 0;;
2515
2516				$list[$i]["_monitor_alerts_fire_count_"] = $group_stat[0]["alerts_fired"];
2517				$list[$i]["_total_checks_"] = $group_stat[0]["modules"];
2518				$list[$i]["_total_alerts_"] = $group_stat[0]["alerts"];
2519			}
2520			if ($mode == 'tactical') {
2521				// Get total count of monitors for this group, except disabled.
2522				$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_"];
2523
2524				// Calculate not_normal monitors
2525				$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
2526
2527				if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2528					$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2529				}
2530				else {
2531					$list[$i]["_monitor_health_"] = 100;
2532				}
2533
2534				if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2535					$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2536				}
2537				else {
2538					$list[$i]["_module_sanity_"] = 100;
2539				}
2540
2541				if (isset($list[$i]["_alerts_"])) {
2542					if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
2543						$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
2544					}
2545					else {
2546						$list[$i]["_alert_level_"] = 100;
2547					}
2548				}
2549				else {
2550					$list[$i]["_alert_level_"] = 100;
2551					$list[$i]["_alerts_"] = 0;
2552				}
2553
2554				$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
2555
2556				if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2557					$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2558				}
2559				else {
2560					$list[$i]["_global_health_"] = 100;
2561				}
2562
2563				$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
2564			}
2565
2566			if ($returnAllGroup) {
2567				$list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
2568				$list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
2569				$list[0]['_total_agents_'] += $list[$i]['_total_agents_'];
2570				$list[0]['_monitors_ok_'] += $list[$i]['_monitors_ok_'];
2571				$list[0]['_monitors_critical_'] += $list[$i]['_monitors_critical_'];
2572				$list[0]['_monitors_warning_'] += $list[$i]['_monitors_warning_'];
2573				$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
2574				$list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
2575				$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
2576
2577				if ($mode == 'tactical' || $mode == 'tree') {
2578					$list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
2579					$list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
2580					$list[0]['_agents_critical_'] += $list[$i]['_agents_critical_'];
2581					$list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
2582				}
2583			}
2584
2585			if ($mode == 'group') {
2586				if (($list[$i]['_agents_unknown_'] == 0) && ($list[$i]['_monitors_alerts_fired_'] == 0)
2587						&& ($list[$i]['_total_agents_'] == 0) && ($list[$i]['_monitors_ok_'] == 0)
2588						&& ($list[$i]['_monitors_critical_'] == 0) && ($list[$i]['_monitors_warning_'] == 0)) {
2589					unset($list[$i]);
2590				}
2591			}
2592
2593		}
2594		else if (($config["realtimestats"] == 0) && !$user_strict) {
2595			$group_stat = db_get_all_rows_sql ("SELECT *
2596				FROM tgroup_stat, tgrupo
2597				WHERE tgrupo.id_grupo = tgroup_stat.id_group
2598					AND tgroup_stat.id_group = $id
2599				ORDER BY nombre");
2600
2601			$list[$i]['_id_'] = $id;
2602			$list[$i]['_name_'] = $item['nombre'];
2603			$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
2604
2605			if ($mode == 'tree' && !empty($item['parent']))
2606				$list[$i]['_parent_id_'] = $item['parent'];
2607
2608			$list[$i]['_agents_unknown_'] = $group_stat[0]["unknown"];
2609			$list[$i]['_monitors_alerts_fired_'] = $group_stat[0]["alerts_fired"];
2610			$list[$i]['_total_agents_'] = $group_stat[0]["agents"];
2611
2612			// This fields are not in database
2613			$list[$i]['_monitors_ok_'] = (int) groups_get_normal_monitors($id);
2614			$list[$i]['_monitors_critical_'] = (int) groups_get_critical_monitors($id);
2615			$list[$i]['_monitors_warning_'] = (int) groups_get_warning_monitors($id);
2616			$list[$i]['_monitors_unknown_'] = (int) groups_get_unknown_monitors($id);
2617			$list[$i]['_monitors_not_init_'] = (int) groups_get_not_init_monitors($id);
2618			$list[$i]['_agents_not_init_'] = (int) groups_get_not_init_agents($id);
2619
2620			if ($mode == 'tactical' || $mode == 'tree') {
2621				$list[$i]['_agents_ok_'] = $group_stat[0]["normal"];
2622				$list[$i]['_agents_warning_'] = $group_stat[0]["warning"];
2623				$list[$i]['_agents_critical_'] = $group_stat[0]["critical"];
2624				$list[$i]['_monitors_alerts_'] = $group_stat[0]["alerts"];
2625
2626				$list[$i]["_monitor_alerts_fire_count_"] = $group_stat[0]["alerts_fired"];
2627				$list[$i]["_total_checks_"] = $group_stat[0]["modules"];
2628				$list[$i]["_total_alerts_"] = $group_stat[0]["alerts"];
2629			}
2630			if ($mode == 'tactical') {
2631				// Get total count of monitors for this group, except disabled.
2632				$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_"];
2633
2634				// Calculate not_normal monitors
2635				$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
2636
2637				if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2638					$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2639				}
2640				else {
2641					$list[$i]["_monitor_health_"] = 100;
2642				}
2643
2644				if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2645					$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2646				}
2647				else {
2648					$list[$i]["_module_sanity_"] = 100;
2649				}
2650
2651				if (isset($list[$i]["_alerts_"])) {
2652					if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
2653						$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
2654					}
2655					else {
2656						$list[$i]["_alert_level_"] = 100;
2657					}
2658				}
2659				else {
2660					$list[$i]["_alert_level_"] = 100;
2661					$list[$i]["_alerts_"] = 0;
2662				}
2663
2664				$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
2665
2666				if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2667					$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2668				}
2669				else {
2670					$list[$i]["_global_health_"] = 100;
2671				}
2672
2673				$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
2674			}
2675
2676			if ($returnAllGroup) {
2677				$list[0]['_agents_unknown_'] += $group_stat[0]["unknown"];
2678				$list[0]['_monitors_alerts_fired_'] += $group_stat[0]["alerts_fired"];
2679				$list[0]['_total_agents_'] += $group_stat[0]["agents"];
2680				$list[0]['_monitors_ok_'] += $list[$i]['_monitors_ok_'];
2681				$list[0]['_monitors_critical_'] += $list[$i]['_monitors_critical_'];
2682				$list[0]['_monitors_warning_'] += $list[$i]['_monitors_warning_'];
2683				$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
2684				$list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
2685				$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
2686
2687				if ($mode == 'tactical' || $mode == 'tree') {
2688					$list[0]['_agents_ok_'] += $group_stat[0]["normal"];
2689					$list[0]['_agents_warning_'] += $group_stat[0]["warning"];
2690					$list[0]['_agents_critical_'] += $group_stat[0]["critical"];
2691					$list[0]['_monitors_alerts_'] += $group_stat[0]["alerts"];
2692				}
2693			}
2694
2695			if ($mode == 'group')  {
2696				if (! defined ('METACONSOLE')) {
2697					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)) {
2698						unset($list[$i]);
2699					}
2700				}
2701				else {
2702					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)) {
2703						unset($list[$i]);
2704					}
2705				}
2706			}
2707
2708		}
2709		else {
2710			$list[$i]['_id_'] = $id;
2711			$list[$i]['_name_'] = $item['nombre'];
2712			$list[$i]['_iconImg_'] = html_print_image ("images/groups_small/" . groups_get_icon($item['id_grupo']).".png", true, array ("style" => 'vertical-align: middle;'));
2713
2714			if ($mode == 'tree' && !empty($item['parent']))
2715				$list[$i]['_parent_id_'] = $item['parent'];
2716
2717			$list[$i]['_monitors_ok_'] = (int) groups_get_normal_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2718			$list[$i]['_monitors_critical_'] = (int) groups_get_critical_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2719			$list[$i]['_monitors_warning_'] = (int) groups_get_warning_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2720			$list[$i]['_monitors_unknown_'] = (int) groups_get_unknown_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2721			$list[$i]['_monitors_not_init_'] = (int) groups_get_not_init_monitors ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2722			$list[$i]['_monitors_alerts_fired_'] = groups_monitor_fired_alerts ($id, $user_strict, $id);
2723			$list[$i]['_total_agents_'] = (int) groups_get_total_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2724			$list[$i]['_agents_unknown_'] = (int) groups_get_unknown_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2725			$list[$i]['_agents_not_init_'] = (int) groups_get_not_init_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2726
2727			if ($mode == 'tactical' || $mode == 'tree') {
2728				$list[$i]['_agents_ok_'] = (int) groups_get_normal_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2729				$list[$i]['_agents_warning_'] = (int) groups_get_warning_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2730				$list[$i]['_agents_critical_'] = (int) groups_get_critical_agents ($id, $agent_filter, $module_filter, $user_strict, $acltags, $config["realtimestats"]);
2731				$list[$i]['_monitors_alerts_'] = groups_monitor_alerts ($id, $user_strict, $id);
2732
2733				// TODO
2734				//~ $list[$i]["_total_checks_"]
2735				//~ $list[$i]["_total_alerts_"]
2736
2737				// Get total count of monitors for this group, except disabled.
2738				$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_"];
2739
2740				// Calculate not_normal monitors
2741				$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
2742
2743				if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2744					$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2745				}
2746				else {
2747					$list[$i]["_monitor_health_"] = 100;
2748				}
2749
2750				if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2751					$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2752				}
2753				else {
2754					$list[$i]["_module_sanity_"] = 100;
2755				}
2756
2757				if (isset($list[$i]["_alerts_"])) {
2758					if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_alerts_"] > 0) {
2759						$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_alerts_"] / 100)), 1);
2760					}
2761					else {
2762						$list[$i]["_alert_level_"] = 100;
2763					}
2764				}
2765				else {
2766					$list[$i]["_alert_level_"] = 100;
2767					$list[$i]["_alerts_"] = 0;
2768				}
2769
2770				$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
2771
2772				if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2773					$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2774				}
2775				else {
2776					$list[$i]["_global_health_"] = 100;
2777				}
2778
2779				$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
2780			}
2781
2782			if ($returnAllGroup) {
2783				$list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
2784				$list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
2785				$list[0]['_total_agents_'] += $list[$i]['_total_agents_'];
2786				$list[0]['_monitors_ok_'] += $list[$i]['_monitors_ok_'];
2787				$list[0]['_monitors_critical_'] += $list[$i]['_monitors_critical_'];
2788				$list[0]['_monitors_warning_'] += $list[$i]['_monitors_warning_'];
2789				$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
2790				$list[0]['_monitors_not_init_'] = $list[$i]['_monitors_not_init_'];
2791				$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
2792
2793				if ($mode == 'tactical' || $mode == 'tree') {
2794					$list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
2795					$list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
2796					$list[0]['_agents_critical_'] += $list[$i]['_agents_critical_'];
2797					$list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
2798				}
2799			}
2800
2801			if ($mode == 'group') {
2802				if (! defined ('METACONSOLE')) {
2803					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)) {
2804						unset($list[$i]);
2805					}
2806				} else {
2807					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)) {
2808						unset($list[$i]);
2809					}
2810				}
2811			}
2812		}
2813		$i++;
2814	}
2815
2816	if ($user_strict) {
2817		foreach ($user_tags as $group_id => $tag_name) {
2818			$id = db_get_value('id_tag', 'ttag', 'name', $tag_name);
2819
2820			$list[$i]['_id_'] = $id;
2821			$list[$i]['_name_'] = $tag_name;
2822			$list[$i]['_iconImg_'] = html_print_image ("images/tag_red.png", true, array ("style" => 'vertical-align: middle;'));
2823			$list[$i]['_is_tag_'] = 1;
2824
2825			$list[$i]['_total_agents_'] = (int) tags_get_total_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2826			$list[$i]['_agents_unknown_'] = (int) tags_get_unknown_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2827			$list[$i]['_agents_not_init_'] = (int) tags_get_not_init_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2828			$list[$i]['_monitors_ok_'] = (int) tags_get_normal_monitors ($id, $acltags, $agent_filter, $module_filter);
2829			$list[$i]['_monitors_critical_'] = (int) tags_get_critical_monitors ($id, $acltags, $agent_filter, $module_filter);
2830			$list[$i]['_monitors_warning_'] = (int) tags_get_warning_monitors ($id, $acltags, $agent_filter, $module_filter);
2831			$list[$i]['_monitors_not_init_'] = (int) tags_get_not_init_monitors ($id, $acltags, $agent_filter, $module_filter);
2832			$list[$i]['_monitors_unknown_'] = (int) tags_get_unknown_monitors ($id, $acltags, $agent_filter, $module_filter);
2833			$list[$i]['_monitors_alerts_fired_'] = tags_monitors_fired_alerts($id, $acltags);
2834
2835			if ($mode == 'tactical' || $mode == 'tree') {
2836				$list[$i]['_agents_ok_'] = (int) tags_get_normal_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2837				$list[$i]['_agents_warning_'] = (int) tags_get_warning_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2838				$list[$i]['_agents_critical_'] = (int) tags_get_critical_agents ($id, $acltags, $agent_filter, $module_filter, $config["realtimestats"]);
2839				$list[$i]['_monitors_alerts_'] = tags_get_monitors_alerts ($id, $acltags);
2840			}
2841			if ($mode == 'tactical') {
2842				// Get total count of monitors for this group, except disabled.
2843				$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_"];
2844
2845				// Calculate not_normal monitors
2846				$list[$i]["_monitor_not_normal_"] = $list[$i]["_monitor_checks_"] - $list[$i]["_monitors_ok_"];
2847
2848				if ($list[$i]["_monitor_not_normal_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2849					$list[$i]["_monitor_health_"] = format_numeric (100 - ($list[$i]["_monitor_not_normal_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2850				}
2851				else {
2852					$list[$i]["_monitor_health_"] = 100;
2853				}
2854
2855				if ($list[$i]["_monitors_not_init_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2856					$list[$i]["_module_sanity_"] = format_numeric (100 - ($list[$i]["_monitors_not_init_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2857				}
2858				else {
2859					$list[$i]["_module_sanity_"] = 100;
2860				}
2861
2862				if (isset($list[$i]["_monitors_alerts_"])) {
2863					if ($list[$i]["_monitors_alerts_fired_"] > 0 && $list[$i]["_monitors_alerts_"] > 0) {
2864						$list[$i]["_alert_level_"] = format_numeric (100 - ($list[$i]["_monitors_alerts_fired_"] / ($list[$i]["_monitors_alerts_"] / 100)), 1);
2865					}
2866					else {
2867						$list[$i]["_alert_level_"] = 100;
2868					}
2869				}
2870				else {
2871					$list[$i]["_alert_level_"] = 100;
2872					$list[$i]["_monitors_alerts_"] = 0;
2873				}
2874
2875				$list[$i]["_monitor_bad_"] = $list[$i]["_monitors_critical_"] + $list[$i]["_monitors_warning_"];
2876
2877				if ($list[$i]["_monitor_bad_"] > 0 && $list[$i]["_monitor_checks_"] > 0) {
2878					$list[$i]["_global_health_"] = format_numeric (100 - ($list[$i]["_monitor_bad_"] / ($list[$i]["_monitor_checks_"] / 100)), 1);
2879				}
2880				else {
2881					$list[$i]["_global_health_"] = 100;
2882				}
2883
2884				$list[$i]["_server_sanity_"] = format_numeric (100 - $list[$i]["_module_sanity_"], 1);
2885			}
2886
2887			if ($returnAllGroup) {
2888				$list[0]['_agents_unknown_'] += $list[$i]['_agents_unknown_'];
2889				$list[0]['_monitors_alerts_fired_'] += $list[$i]['_monitors_alerts_fired_'];
2890				$list[0]['_total_agents_'] += $list[$i]['_total_agents_'];
2891				$list[0]['_monitors_ok_'] += $list[$i]['_monitors_ok_'];
2892				$list[0]['_monitors_critical_'] += $list[$i]['_monitors_critical_'];
2893				$list[0]['_monitors_warning_'] += $list[$i]['_monitors_warning_'];
2894				$list[0]['_monitors_unknown_'] += $list[$i]['_monitors_unknown_'];
2895				$list[0]['_agents_not_init_'] += $list[$i]['_agents_not_init_'];
2896				$list[0]['_monitors_not_init_'] += $list[$i]['_monitors_not_init_'];
2897
2898				if ($mode == 'tactical' || $mode == 'tree') {
2899					$list[0]['_agents_ok_'] += $list[$i]['_agents_ok_'];
2900					$list[0]['_agents_warning_'] += $list[$i]['_agents_warning_'];
2901					$list[0]['_agents_critical_'] += $list[$i]['_agents_critical_'];
2902					$list[0]['_monitors_alerts_'] += $list[$i]['_monitors_alerts_'];
2903				}
2904			}
2905
2906			if ($mode == 'group') {
2907				if (! defined ('METACONSOLE')) {
2908					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)) {
2909						unset($list[$i]);
2910					}
2911				}
2912				else {
2913					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)) {
2914						unset($list[$i]);
2915					}
2916				}
2917			}
2918			$i++;
2919		}
2920	}
2921
2922	return $list;
2923}
2924
2925function group_get_groups_list($id_user = false, $user_strict = false, $access = 'AR', $force_group_and_tag = true, $returnAllGroup = false, $mode = 'group') {
2926	global $config;
2927
2928	if ($id_user == false) {
2929		$id_user = $config['id_user'];
2930	}
2931
2932	$acltags = tags_get_user_module_and_tags ($id_user, $access, $user_strict);
2933
2934	// If using metaconsole, the strict users will use the agent table of every node
2935	if (is_metaconsole() && $user_strict) {
2936		$servers = metaconsole_get_servers();
2937
2938		$result_list = array ();
2939		foreach ($servers as $server) {
2940
2941			if (metaconsole_connect($server) != NOERR) {
2942				continue;
2943			}
2944			$server_list = group_get_data ($id_user, $user_strict,
2945				$acltags, $returnAllGroup, $mode);
2946
2947			foreach ($server_list as $server_item) {
2948				if (! isset ($result_list[$server_item['_name_']])) {
2949
2950					$result_list[$server_item['_name_']] = $server_item;
2951				}
2952				else {
2953					$result_list[$server_item['_name_']]['_monitors_ok_'] += $server_item['_monitors_ok_'];
2954					$result_list[$server_item['_name_']]['_monitors_critical_'] += $server_item['_monitors_critical_'];
2955					$result_list[$server_item['_name_']]['_monitors_warning_'] += $server_item['_monitors_warning_'];
2956					$result_list[$server_item['_name_']]['_agents_unknown_'] += $server_item['_agents_unknown_'];
2957					$result_list[$server_item['_name_']]['_total_agents_'] += $server_item['_total_agents_'];
2958					$result_list[$server_item['_name_']]['_monitors_alerts_fired_'] += $server_item['_monitors_alerts_fired_'];
2959
2960					if ($mode == 'tactical') {
2961						$result_list[$server_item['_name_']]['_agents_ok_'] += $server_item['_agents_ok_'];
2962						$result_list[$server_item['_name_']]['_agents_critical_'] += $server_item['_agents_critical_'];
2963						$result_list[$server_item['_name_']]['_agents_warning_'] += $server_item['_agents_warning_'];
2964						$result_list[$server_item['_name_']]['_monitors_alerts_'] += $server_item['_monitors_alerts_'];
2965
2966						$result_list[$server_item['_name_']]["_monitor_checks_"] += $server_item["_monitor_checks_"];
2967						$result_list[$server_item['_name_']]["_monitor_not_normal_"] += $server_item["_monitor_not_normal_"];
2968						$result_list[$server_item['_name_']]["_monitor_health_"] += $server_item["_monitor_health_"];
2969						$result_list[$server_item['_name_']]["_module_sanity_"] += $server_item["_module_sanity_"];
2970						$result_list[$server_item['_name_']]["_alerts_"] += $server_item["_alerts_"];
2971						$result_list[$server_item['_name_']]["_alert_level_"] += $server_item["_alert_level_"];
2972						$result_list[$server_item['_name_']]["_monitor_bad_"] += $server_item["_monitor_bad_"];
2973						$result_list[$server_item['_name_']]["_global_health_"] += $server_item["_global_health_"];
2974						$result_list[$server_item['_name_']]["_server_sanity_"] += $server_item["_server_sanity_"];
2975						$result_list[$server_item['_name_']]["_monitor_alerts_fire_count_"] += $server_item["_monitor_alerts_fire_count_"];
2976						$result_list[$server_item['_name_']]["_total_checks_"] += $server_item["_total_checks_"];
2977						$result_list[$server_item['_name_']]["_total_alerts_"] += $server_item["_total_alerts_"];
2978					}
2979				}
2980			}
2981			metaconsole_restore_db();
2982
2983		}
2984
2985		return $result_list;
2986	}
2987	// If using metaconsole, the not strict users will use the metaconsole's agent cache table
2988	else {
2989		$result_list = group_get_data ($id_user, $user_strict, $acltags,
2990			$returnAllGroup, $mode);
2991
2992		return $result_list;
2993	}
2994}
2995
2996function groups_get_group_deep ($id_group) {
2997	global $config;
2998	$parents = groups_get_parents($id_group, false);
2999
3000	if (empty($parents)) {
3001		$deep = "";
3002	}
3003	else {
3004		$deep = str_repeat("&nbsp;&nbsp;", count($parents));
3005	}
3006
3007	return $deep;
3008}
3009?>
3010