1<?php
2
3// Pandora FMS - http://pandorafms.com
4// ==================================================
5// Copyright (c) 2005-2011 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
17/**
18 * @package Include
19 * @subpackage Reporting
20 */
21
22/**
23 * Include the usual functions
24 */
25require_once($config["homedir"] . "/include/functions.php");
26require_once($config["homedir"] . "/include/functions_db.php");
27require_once($config["homedir"] . "/include/functions_agents.php");
28include_once($config["homedir"] . "/include/functions_groups.php");
29require_once($config["homedir"] . '/include/functions_graph.php');
30include_once($config['homedir'] . "/include/functions_modules.php");
31include_once($config['homedir'] . "/include/functions_events.php");
32include_once($config['homedir'] . "/include/functions_alerts.php");
33include_once($config['homedir'] . '/include/functions_users.php');
34enterprise_include_once('include/functions_reporting.php');
35enterprise_include_once('include/functions_metaconsole.php');
36enterprise_include_once('include/functions_inventory.php');
37include_once($config['homedir'] . "/include/functions_forecast.php");
38include_once($config['homedir'] . "/include/functions_ui.php");
39include_once($config['homedir'] . "/include/functions_netflow.php");
40include_once($config['homedir'] . "/include/functions_os.php");
41
42function reporting_user_can_see_report($id_report, $id_user = null) {
43	global $config;
44
45	if (empty($id_user)) {
46		$id_user = $config['id_user'];
47	}
48
49	// Get Report record (to get id_group)
50	$report = db_get_row ('treport', 'id_report', $id_report);
51
52	// Check ACL on the report to see if user has access to the report.
53	if (empty($report) || !check_acl ($config['id_user'], $report['id_group'], "RR")) {
54		return false;
55	}
56
57	return true;
58}
59
60function reporting_get_type($content) {
61	switch ($content["type"]) {
62		case REPORT_OLD_TYPE_SIMPLE_GRAPH:
63			$content["type"] = 'simple_graph';
64			break;
65		case REPORT_OLD_TYPE_CUSTOM_GRAPH:
66			$content["type"] = 'custom_graph';
67			break;
68		case REPORT_OLD_TYPE_MONITOR_REPORT:
69			$content["type"] = 'monitor_report';
70			break;
71		case REPORT_OLD_TYPE_SLA:
72			$content["type"] = 'SLA';
73			break;
74		case REPORT_OLD_TYPE_AVG_VALUE:
75			$content["type"] = 'avg_value';
76			break;
77		case REPORT_OLD_TYPE_MAX_VALUE:
78			$content["type"] = 'max_value';
79			break;
80		case REPORT_OLD_TYPE_MIN_VALUE:
81			$content["type"] = 'min_value';
82			break;
83		case REPORT_OLD_TYPE_SUMATORY:
84			$content["type"] = 'sumatory';
85			break;
86	}
87
88	return $content["type"];
89}
90
91function reporting_get_description($id_report) {
92	return db_get_value('description', 'treport', 'id_report', $id_report);
93}
94
95function reporting_get_name($id_report) {
96	return db_get_value('name', 'treport', 'id_report', $id_report);
97}
98
99function reporting_make_reporting_data($report = null, $id_report,
100	$date, $time, $period = null, $type = 'dinamic',
101	$force_width_chart = null, $force_height_chart = null) {
102
103	global $config;
104
105	$return = array();
106
107	if (!empty($report)) {
108		$contents = $report['contents'];
109	}
110	else {
111		$report = db_get_row ('treport', 'id_report', $id_report);
112		$contents = db_get_all_rows_field_filter ('treport_content',
113			'id_report', $id_report, db_escape_key_identifier('order'));
114	}
115
116	$datetime = strtotime($date . ' ' . $time);
117	$report["datetime"] = $datetime;
118	$report["group"] = $report['id_group'];
119	$report["group_name"] = groups_get_name ($report['id_group']);
120	$report['contents'] = array();
121
122	if (empty($contents)) {
123		return reporting_check_structure_report($report);
124	}
125
126
127	foreach ($contents as $content) {
128		if (!empty($period)) {
129			$content['period'] = $period;
130		}
131
132		$content['style'] = json_decode(
133			io_safe_output($content['style']), true);
134
135		switch (reporting_get_type($content)) {
136			case 'simple_graph':
137				$report['contents'][] =
138					reporting_simple_graph(
139						$report,
140						$content,
141						$type,
142						$force_width_chart,
143						$force_height_chart);
144				break;
145			case 'general':
146				$report['contents'][] =
147					reporting_general(
148						$report,
149						$content);
150				break;
151			case 'availability':
152				$report['contents'][] =
153					reporting_availability(
154						$report,
155						$content);
156				break;
157			case 'sql':
158				$report['contents'][] = reporting_sql(
159					$report,
160					$content);
161				break;
162			case 'custom_graph':
163			case 'automatic_custom_graph':
164				$report['contents'][] =
165					reporting_custom_graph(
166						$report,
167						$content,
168						$type,
169						$force_width_chart,
170						$force_height_chart);
171				break;
172			case 'text':
173				$report['contents'][] = reporting_text(
174					$report,
175					$content);
176				break;
177			case 'url':
178				$report['contents'][] = reporting_url(
179					$report,
180					$content,
181					$type);
182				break;
183			case 'max_value':
184				$report['contents'][] = reporting_value(
185					$report,
186					$content,
187					'max');
188				break;
189			case 'avg_value':
190				$report['contents'][] = reporting_value(
191					$report,
192					$content,
193					'avg');
194				break;
195			case 'min_value':
196				$report['contents'][] = reporting_value(
197					$report,
198					$content,
199					'min');
200				break;
201			case 'sumatory':
202				$report['contents'][] = reporting_value(
203					$report,
204					$content,
205					'sum');
206				break;
207			case 'historical_data':
208				$report['contents'][] = reporting_historical_data(
209					$report,
210					$content);
211				break;
212			case 'MTTR':
213				$report['contents'][] = reporting_value(
214					$report,
215					$content,
216					'MTTR');
217				break;
218			case 'MTBF':
219				$report['contents'][] = reporting_value(
220					$report,
221					$content,
222					'MTBF');
223				break;
224			case 'TTO':
225				$report['contents'][] = reporting_value(
226					$report,
227					$content,
228					'TTO');
229				break;
230			case 'TTRT':
231				$report['contents'][] = reporting_value(
232					$report,
233					$content,
234					'TTRT');
235				break;
236			case 'agent_configuration':
237				$report['contents'][] = reporting_agent_configuration(
238					$report,
239					$content);
240				break;
241			case 'projection_graph':
242				$report['contents'][] = reporting_projection_graph(
243					$report,
244					$content,
245					$type,
246					$force_width_chart,
247					$force_height_chart);
248				break;
249			case 'prediction_date':
250				$report['contents'][] = reporting_prediction_date(
251					$report,
252					$content);
253				break;
254			case 'simple_baseline_graph':
255				$report['contents'][] = reporting_simple_baseline_graph(
256					$report,
257					$content,
258					$type,
259					$force_width_chart,
260					$force_height_chart);
261				break;
262			case 'netflow_area':
263				$report['contents'][] = reporting_simple_baseline_graph(
264					$report,
265					$content,
266					$type,
267					$force_width_chart,
268					$force_height_chart);
269				break;
270			case 'netflow_pie':
271				$report['contents'][] = reporting_netflow_pie(
272					$report,
273					$content,
274					$type,
275					$force_width_chart,
276					$force_height_chart);
277				break;
278			case 'netflow_data':
279				$report['contents'][] = reporting_netflow_data(
280					$report,
281					$content,
282					$type,
283					$force_width_chart,
284					$force_height_chart);
285				break;
286			case 'netflow_statistics':
287				$report['contents'][] = reporting_netflow_statistics(
288					$report,
289					$content,
290					$type,
291					$force_width_chart,
292					$force_height_chart);
293				break;
294			case 'netflow_summary':
295				$report['contents'][] = reporting_netflow_summary(
296					$report,
297					$content,
298					$type,
299					$force_width_chart,
300					$force_height_chart);
301				break;
302			case 'monitor_report':
303				$report['contents'][] = reporting_monitor_report(
304					$report,
305					$content);
306				break;
307			case 'sql_graph_vbar':
308				$report['contents'][] = reporting_sql_graph(
309					$report,
310					$content,
311					$type,
312					$force_width_chart,
313					$force_height_chart,
314					'sql_graph_vbar');
315				break;
316			case 'sql_graph_hbar':
317				$report['contents'][] = reporting_sql_graph(
318					$report,
319					$content,
320					$type,
321					$force_width_chart,
322					$force_height_chart,
323					'sql_graph_hbar');
324				break;
325			case 'sql_graph_pie':
326				$report['contents'][] = reporting_sql_graph(
327					$report,
328					$content,
329					$type,
330					$force_width_chart,
331					$force_height_chart,
332					'sql_graph_pie');
333				break;
334			case 'alert_report_module':
335				$report['contents'][] = reporting_alert_report_module(
336					$report,
337					$content);
338				break;
339			case 'alert_report_agent':
340				$report['contents'][] = reporting_alert_report_agent(
341					$report,
342					$content);
343				break;
344			case 'alert_report_group':
345				$report['contents'][] = reporting_alert_report_group(
346					$report,
347					$content);
348				break;
349			case 'network_interfaces_report':
350				$report['contents'][] = reporting_network_interfaces_report(
351					$report,
352					$content);
353				break;
354			case 'group_configuration':
355				$report['contents'][] = reporting_group_configuration(
356					$report,
357					$content);
358				break;
359			case 'database_serialized':
360				$report['contents'][] = reporting_database_serialized(
361					$report,
362					$content);
363				break;
364			case 'agent_detailed_event':
365			case 'event_report_agent':
366				$report['contents'][] = reporting_event_report_agent(
367					$report,
368					$content,
369					$type,
370					$force_width_chart,
371					$force_height_chart);
372				break;
373			case 'group_report':
374				$report['contents'][] = reporting_group_report(
375					$report,
376					$content);
377				break;
378			case 'exception':
379				$report['contents'][] = reporting_exception(
380					$report,
381					$content,
382					$type,
383					$force_width_chart,
384					$force_height_chart);
385				break;
386			case 'agent_module':
387				$report['contents'][] = reporting_agent_module(
388					$report,
389					$content);
390				break;
391			case 'inventory':
392				$report['contents'][] = reporting_inventory(
393					$report,
394					$content,
395					$type);
396				break;
397			case 'inventory_changes':
398				$report['contents'][] = reporting_inventory_changes(
399					$report,
400					$content,
401					$type);
402				break;
403			case 'event_report_module':
404				$report['contents'][] = reporting_event_report_module(
405					$report,
406					$content);
407				break;
408			case 'event_report_group':
409				$report['contents'][] = reporting_event_report_group(
410					$report,
411					$content,
412					$type,
413					$force_width_chart,
414					$force_height_chart);
415				break;
416			case 'top_n':
417				$report['contents'][] = reporting_event_top_n(
418					$report,
419					$content,
420					$type,
421					$force_width_chart,
422					$force_height_chart);
423				break;
424			case 'SLA':
425				$report['contents'][] = reporting_SLA(
426					$report,
427					$content,
428					$type,
429					$force_width_chart,
430					$force_height_chart);
431				break;
432			case 'SLA_monthly':
433				$report['contents'][] = reporting_enterprise_sla_monthly_refactoriced(
434					$report,
435					$content);
436				break;
437			case 'SLA_services':
438				$report['contents'][] = reporting_enterprise_sla_services_refactoriced(
439					$report,
440					$content,
441					$type,
442					$force_width_chart,
443					$force_height_chart);
444				break;
445		}
446	}
447
448	return reporting_check_structure_report($report);
449}
450
451function reporting_SLA($report, $content, $type = 'dinamic',
452	$force_width_chart = null, $force_height_chart = null) {
453
454	global $config;
455
456	$return['type'] = 'SLA';
457
458	if (empty($content['name'])) {
459		$content['name'] = __('S.L.A.');
460	}
461
462	$return['title'] = $content['name'];
463	$return["description"] = $content["description"];
464	$return["date"] = reporting_get_date_text($report, $content);
465
466
467	// Get chart
468	reporting_set_conf_charts($width, $height, $only_image, $type,
469		$content, $ttl);
470
471	if (!empty($force_width_chart)) {
472		$width = $force_width_chart;
473	}
474
475	if (!empty($force_height_chart)) {
476		$height = $force_height_chart;
477	}
478
479
480	$edge_interval = 10;
481
482	if (empty($content['subitems'])) {
483		$slas = db_get_all_rows_field_filter (
484			'treport_content_sla_combined',
485			'id_report_content', $content['id_rc']);
486	}
487	else {
488		$slas = $content['subitems'];
489	}
490
491	if (empty($slas)) {
492		$return['failed'] = __('There are no SLAs defined');
493	}
494	else {
495
496		// What show?
497		$show_table = $content['show_graph'] == 0 || $content['show_graph'] == 1;
498		$show_graphs = $content['show_graph'] == 1 || $content['show_graph'] == 2;
499
500
501		// Table Planned Downtimes
502		require_once ($config['homedir'] . '/include/functions_planned_downtimes.php');
503		$metaconsole_on = is_metaconsole();
504		$downtime_malformed = false;
505
506		$planned_downtimes_empty = true;
507		$malformed_planned_downtimes_empty = true;
508
509		$return['planned_downtimes'] = array();
510
511		if ($metaconsole_on) {
512			$id_agent_modules_by_server = array();
513
514			foreach ($slas as $sla) {
515				$server = $sla['server_name'];
516				if (empty($server))
517					continue;
518
519				if (!isset($id_agent_modules_by_server[$server]))
520					$id_agent_modules_by_server[$server] = array();
521
522				$id_agent_modules_by_server[$server][] = $sla['id_agent_module'];
523			}
524
525			$planned_downtimes_by_server = array();
526			$malformed_planned_downtimes_by_server = array();
527			foreach ($id_agent_modules_by_server as $server => $id_agent_modules) {
528				//Metaconsole connection
529				if (!empty($server)) {
530					$connection = metaconsole_get_connection($server);
531					if (!metaconsole_load_external_db($connection)) {
532						continue;
533					}
534
535					$planned_downtimes_by_server[$server] = reporting_get_planned_downtimes(($report['datetime']-$content['period']), $report['datetime'], $id_agent_modules);
536					$malformed_planned_downtimes_by_server[$server] = planned_downtimes_get_malformed();
537
538					if (!empty($planned_downtimes_by_server[$server]))
539						$planned_downtimes_empty = false;
540					if (!empty($malformed_planned_downtimes_by_server[$server]))
541						$malformed_planned_downtimes_empty = false;
542
543					//Restore db connection
544					metaconsole_restore_db();
545				}
546			}
547
548			if (!$planned_downtimes_empty) {
549				foreach ($planned_downtimes_by_server as $server => $planned_downtimes) {
550					foreach ($planned_downtimes as $planned_downtime) {
551						$data = array();
552						$data['server'] = $server;
553						$data['name'] = $planned_downtime['name'];
554						$data['description'] = $planned_downtime['description'];
555						$data['execution'] = ucfirst($planned_downtime['type_execution']);
556						$data['dates'] = reporting_format_planned_downtime_dates($planned_downtime);
557
558						$data['malformed'] = 0;
559						if (!$malformed_planned_downtimes_empty
560								&& isset($malformed_planned_downtimes_by_server[$server])
561								&& isset($malformed_planned_downtimes_by_server[$server][$planned_downtime['id']])) {
562
563							$data['malformed'] = 1;
564
565							if (!$downtime_malformed)
566								$downtime_malformed = true;
567						}
568
569						$return['planned_downtimes'][] = $data;
570					}
571				}
572			}
573		}
574		else {
575			$id_agent_modules = array();
576			foreach ($slas as $sla) {
577				if (!empty($sla['id_agent_module']))
578					$id_agent_modules[] = $sla['id_agent_module'];
579			}
580
581			$planned_downtimes =
582				reporting_get_planned_downtimes(
583					($report['datetime'] - $content['period']),
584					$report['datetime'],
585					$id_agent_modules);
586			$malformed_planned_downtimes = planned_downtimes_get_malformed();
587
588			if (!empty($planned_downtimes))
589				$planned_downtimes_empty = false;
590			if (!empty($malformed_planned_downtimes))
591				$malformed_planned_downtimes_empty = false;
592
593			if (!$planned_downtimes_empty) {
594				foreach ($planned_downtimes as $planned_downtime) {
595
596					$data = array();
597					$data['name'] = $planned_downtime['name'];
598					$data['description'] = $planned_downtime['description'];
599					$data['execution'] = ucfirst($planned_downtime['type_execution']);
600					$data['dates'] =
601						reporting_format_planned_downtime_dates($planned_downtime);
602
603					$data['malformed'] = 0;
604					if (!$malformed_planned_downtimes_empty && isset($malformed_planned_downtimes[$planned_downtime['id']])) {
605						$data['malformed'] = 1;
606						if (!$downtime_malformed)
607							$downtime_malformed = true;
608					}
609
610					$return['planned_downtimes'][] = $data;
611				}
612			}
613		}
614
615		if ($downtime_malformed) {
616			$return['failed'] =
617				__('This item is affected by a malformed planned downtime. Go to the planned downtimes section to solve this.');
618		}
619		else {
620
621
622			$urlImage = ui_get_full_url(false, true, false, false);
623
624			$sla_failed = false;
625			$total_SLA = 0;
626			$total_result_SLA = 'ok';
627			$sla_showed = array();
628			$sla_showed_values = array();
629
630			foreach ($slas as $sla) {
631				$server_name = $sla ['server_name'];
632				//Metaconsole connection
633				if ($metaconsole_on && $server_name != '') {
634					$connection = metaconsole_get_connection($server_name);
635					if (!metaconsole_load_external_db($connection)) {
636						//ui_print_error_message ("Error connecting to ".$server_name);
637						continue;
638					}
639				}
640
641				if (modules_is_disable_agent($sla['id_agent_module'])
642					|| modules_is_not_init($sla['id_agent_module'])) {
643					if ($metaconsole_on) {
644						//Restore db connection
645						metaconsole_restore_db();
646					}
647
648					continue;
649				}
650
651
652
653				//Get the sla_value in % and store it on $sla_value
654				$sla_value = reporting_get_agentmodule_sla(
655					$sla['id_agent_module'],
656					$content['period'],
657					$sla['sla_min'],
658					$sla['sla_max'],
659					$report["datetime"],
660					$content,
661					$content['time_from'],
662					$content['time_to']);
663
664				if ($metaconsole_on) {
665					//Restore db connection
666					metaconsole_restore_db();
667				}
668
669				//Do not show right modules if 'only_display_wrong' is active
670				if ($content['only_display_wrong'] == 1 &&
671					$sla_value >= $sla['sla_limit']) {
672
673					continue;
674				}
675
676				$sla_showed[] = $sla;
677				$sla_showed_values[] = $sla_value;
678
679			}
680
681			// SLA items sorted descending ()
682			if ($content['top_n'] == 2) {
683				arsort($sla_showed_values);
684			}
685			// SLA items sorted ascending
686			else if ($content['top_n'] == 1) {
687				asort($sla_showed_values);
688			}
689		}
690
691		$return['data'] = array();
692		$return['charts'] = null;
693
694		foreach ($sla_showed_values as $k => $sla_value) {
695			$sla = $sla_showed[$k];
696
697			$server_name = $sla ['server_name'];
698			//Metaconsole connection
699			if ($metaconsole_on && $server_name != '') {
700				$connection = metaconsole_get_connection($server_name);
701				if (metaconsole_connect($connection) != NOERR) {
702					continue;
703				}
704			}
705
706			$total_SLA += $sla_value;
707
708			if ($show_table) {
709				$data = array ();
710				$data['agent'] = modules_get_agentmodule_agent_name(
711					$sla['id_agent_module']);
712				$data['module'] = modules_get_agentmodule_name(
713					$sla['id_agent_module']);
714
715
716				switch ($config["dbtype"]) {
717					case "mysql":
718					case "postgresql":
719						$data['max'] = $sla['sla_max'];
720						$data['min'] = $sla['sla_min'];
721						$data['sla_limit'] = $sla['sla_limit'];
722						break;
723					case "oracle":
724						$data['max'] = oracle_format_float_to_php($sla['sla_max']);
725						$data['min'] = oracle_format_float_to_php($sla['sla_min']);
726						$data['sla_limit'] = oracle_format_float_to_php($sla['sla_limit']);
727						break;
728				}
729
730				$data['sla_value_unknown'] = 0;
731				$data['sla_status'] = 0;
732				$data['sla_value'] = 0;
733				if ($sla_value === false) {
734					$data['sla_value_unknown'] = 1;
735				}
736				else {
737
738					if ($sla_value >= $sla['sla_limit']) {
739						$data['sla_status'] = 1;
740					}
741					else {
742						$sla_failed = true;
743						$data['sla_status'] = 0;
744					}
745
746					// Print icon with status including edge
747					# Fix : 100% accurance is 'inside limits' although 10% was not overrun
748					// if (($sla_value == 100 && $sla_value >= $sla['sla_limit']) || ($sla_value > ($sla['sla_limit'] + $edge_interval))) {
749					// 	$data[6] = html_print_image('images/status_sets/default/severity_normal.png',true,array('title'=>__('Inside limits')));
750					// }
751					// elseif (($sla_value <= $sla['sla_limit'] + $edge_interval)
752					// 	&& ($sla_value >= $sla['sla_limit'] - $edge_interval)) {
753					// 	$data[6] = html_print_image('images/status_sets/default/severity_warning.png',true,array('title'=>__('On the edge')));
754					// }
755					// else {
756					// 	$data[6] = html_print_image('images/status_sets/default/severity_critical.png',true,array('title'=>__('Out of limits')));
757					// }
758
759					$data['sla_value'] = $sla_value;
760					$data['sla_formated_value'] = format_numeric($sla_value, 2). "%";
761				}
762
763				$return['data'][] = $data;
764			}
765
766
767			// Slice graphs calculation
768			if ($show_graphs) {
769				$dataslice = array();
770				$dataslice['agent'] = modules_get_agentmodule_agent_name ($sla['id_agent_module']);
771				$dataslice['module'] = modules_get_agentmodule_name ($sla['id_agent_module']);
772
773				$dataslice['chart'] = graph_sla_slicebar(
774					$sla['id_agent_module'],
775					$content['period'],
776					$sla['sla_min'],
777					$sla['sla_max'],
778					$report['datetime'],
779					$content,
780					$content['time_from'],
781					$content['time_to'],
782					650,
783					25,
784					$urlImage,
785					$ttl,
786					false,
787					false);
788
789				$return['charts'][] = $dataslice;
790			}
791
792			if ($metaconsole_on) {
793				//Restore db connection
794				metaconsole_restore_db();
795			}
796		}
797	}
798
799	return reporting_check_structure_content($return);
800}
801
802function reporting_event_top_n($report, $content, $type = 'dinamic',
803	$force_width_chart = null, $force_height_chart = null) {
804
805	global $config;
806
807	$return['type'] = 'top_n';
808
809	if (empty($content['name'])) {
810		$content['name'] = __('Top N');
811	}
812
813	$return['title'] = $content['name'];
814	$top_n = $content['top_n'];
815
816	switch ($top_n) {
817		case REPORT_TOP_N_MAX:
818			$type_top_n = __('Max');
819			break;
820		case REPORT_TOP_N_MIN:
821			$type_top_n = __('Min');
822			break;
823		case REPORT_TOP_N_AVG:
824		default:
825			//If nothing is selected then it will be shown the average data
826			$type_top_n = __('Avg');
827			break;
828	}
829	$return['subtitle'] = __('Top %d' ,$content['top_n_value']) . ' - ' . $type_top_n;
830	$return["description"] = $content["description"];
831	$return["date"] = reporting_get_date_text($report, $content);
832
833
834	$order_uptodown = $content['order_uptodown'];
835
836	$top_n_value = $content['top_n_value'];
837	$show_graph = $content['show_graph'];
838
839	$return['top_n'] = $content['top_n_value'];
840
841	if (empty($content['subitems'])) {
842		//Get all the related data
843		$sql = sprintf("SELECT id_agent_module, server_name
844			FROM treport_content_item
845			WHERE id_report_content = %d", $content['id_rc']);
846
847		$tops = db_process_sql ($sql);
848	}
849	else {
850		$tops = $content['subitems'];
851	}
852
853	// Get chart
854	reporting_set_conf_charts($width, $height, $only_image, $type,
855		$content, $ttl);
856
857	if (!empty($force_width_chart)) {
858		$width = $force_width_chart;
859	}
860
861	if (!empty($force_height_chart)) {
862		$height = $force_height_chart;
863	}
864
865
866	if (empty($tops)) {
867		$return['failed'] = __('There are no Agent/Modules defined');
868	}
869	else {
870		$data_top = array();
871
872		foreach ($tops as $key => $row) {
873
874			//Metaconsole connection
875			$server_name = $row['server_name'];
876			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
877				$connection = metaconsole_get_connection($server_name);
878				if (metaconsole_load_external_db($connection) != NOERR) {
879					//ui_print_error_message ("Error connecting to ".$server_name);
880					continue;
881				}
882			}
883
884			$ag_name = modules_get_agentmodule_agent_name($row ['id_agent_module']);
885			$mod_name = modules_get_agentmodule_name ($row ['id_agent_module']);
886			$unit = db_get_value('unit', 'tagente_modulo',
887				'id_agente_modulo', $row ['id_agent_module']);
888
889
890			switch ($top_n) {
891				case REPORT_TOP_N_MAX:
892					$value = reporting_get_agentmodule_data_max ($row['id_agent_module'], $content['period']);
893					break;
894				case REPORT_TOP_N_MIN:
895					$value = reporting_get_agentmodule_data_min ($row['id_agent_module'], $content['period']);
896					break;
897				case REPORT_TOP_N_AVG:
898				default:
899					//If nothing is selected then it will be shown the average data
900					$value = reporting_get_agentmodule_data_average ($row['id_agent_module'], $content['period']);
901					break;
902			}
903
904			//If the returned value from modules_get_agentmodule_data_max/min/avg is false it won't be stored.
905			if ($value !== false) {
906				$data_top[$key] = $value;
907				$id_agent_module[$key] = $row['id_agent_module'];
908				$agent_name[$key] = $ag_name;
909				$module_name[$key] = $mod_name;
910				$units[$key] = $unit;
911			}
912
913			//Restore dbconnection
914			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
915				metaconsole_restore_db();
916			}
917		}
918
919		if (empty($data_top)) {
920			$return['failed'] = __('Insuficient data');
921		}
922		else {
923			$data_return = array();
924
925			//Order to show.
926			switch ($order_uptodown) {
927				//Descending
928				case 1:
929					array_multisort($data_top, SORT_DESC, $agent_name, SORT_ASC, $module_name, SORT_ASC, $id_agent_module, SORT_ASC, $units, SORT_ASC);
930					break;
931				//Ascending
932				case 2:
933					array_multisort($data_top, SORT_ASC, $agent_name, SORT_ASC, $module_name, SORT_ASC, $id_agent_module, SORT_ASC, $units, SORT_ASC);
934					break;
935				//By agent name or without selection
936				case 0:
937				case 3:
938					array_multisort($agent_name, SORT_ASC, $data_top, SORT_ASC, $module_name, SORT_ASC, $id_agent_module, SORT_ASC, $units, SORT_ASC);
939					break;
940			}
941
942			array_splice ($data_top, $top_n_value);
943			array_splice ($agent_name, $top_n_value);
944			array_splice ($module_name, $top_n_value);
945			array_splice ($id_agent_module, $top_n_value);
946			array_splice ($units, $top_n_value);
947
948			$data_top_values = array ();
949			$data_top_values['data_top'] = $data_top;
950			$data_top_values['agent_name'] = $agent_name;
951			$data_top_values['module_name'] = $module_name;
952			$data_top_values['id_agent_module'] = $id_agent_module;
953			$data_top_values['units'] = $units;
954
955			// Define truncate size depends the graph width
956			$truncate_size = $width / (4 * ($config['font_size']))-1;
957
958			if ($order_uptodown == 1 || $order_uptodown == 2) {
959				$i = 0;
960				$data_pie_graph = array();
961				$data_hbar = array();
962				foreach ($data_top as $dt) {
963					$item_name = '';
964					$item_name =
965						ui_print_truncate_text($agent_name[$i], $truncate_size, false, true, false, "...") .
966						' - ' .
967						ui_print_truncate_text($module_name[$i], $truncate_size, false, true, false, "...");
968
969
970
971					//Dirty hack, maybe I am going to apply a job in Apple
972					//https://www.imperialviolet.org/2014/02/22/applebug.html
973					$item_name_key_pie = $item_name;
974					$exist_key = true;
975					while ($exist_key) {
976						if (isset($data_pie_graph[$item_name_key_pie])) {
977							$item_name_key_pie .= ' ';
978						}
979						else {
980							$exist_key = false;
981						}
982					}
983					$item_name_key_hbar = $item_name;
984					$exist_key = true;
985					while ($exist_key) {
986						if (isset($data_hbar[$item_name_key_hbar])) {
987							$item_name_key_hbar = ' ' . $item_name_key_hbar;
988						}
989						else {
990							$exist_key = false;
991						}
992					}
993
994
995
996					$data_hbar[$item_name]['g'] = $dt;
997					$data_pie_graph[$item_name] = $dt;
998
999					if ($show_graph == 0 || $show_graph == 1) {
1000						$data = array();
1001						$data['agent'] = $agent_name[$i];
1002						$data['module'] = $module_name[$i];
1003
1004						$data['value'] = $dt;
1005						$data['formated_value'] = format_for_graph($dt,2) . " " . $units[$i];
1006						$data_return[] = $data;
1007					}
1008					$i++;
1009					if ($i >= $top_n_value) break;
1010				}
1011			}
1012			else if ($order_uptodown == 0 || $order_uptodown == 3) {
1013				$i = 0;
1014				$data_pie_graph = array();
1015				$data_hbar = array();
1016				foreach ($agent_name as $an) {
1017					$item_name = '';
1018					$item_name =
1019						ui_print_truncate_text($agent_name[$i],
1020							$truncate_size, false, true, false, "...") .
1021						' - ' .
1022						ui_print_truncate_text($module_name[$i],
1023							$truncate_size, false, true, false, "...");
1024
1025
1026
1027					//Dirty hack, maybe I am going to apply a job in Apple
1028					//https://www.imperialviolet.org/2014/02/22/applebug.html
1029					$item_name_key_pie = $item_name;
1030					$exist_key = true;
1031					while ($exist_key) {
1032						if (isset($data_pie_graph[$item_name_key_pie])) {
1033							$item_name_key_pie .= ' ';
1034						}
1035						else {
1036							$exist_key = false;
1037						}
1038					}
1039					$item_name_key_hbar = $item_name;
1040					$exist_key = true;
1041					while ($exist_key) {
1042						if (isset($data_hbar[$item_name_key_hbar])) {
1043							$item_name_key_hbar = ' ' . $item_name_key_hbar;
1044						}
1045						else {
1046							$exist_key = false;
1047						}
1048					}
1049
1050
1051
1052					$data_pie_graph[$item_name] = $data_top[$i];
1053					$data_hbar[$item_name]['g'] = $data_top[$i];
1054					if  ($show_graph == 0 || $show_graph == 1) {
1055						$data = array();
1056						$data['agent'] = $an;
1057						$data['module'] = $module_name[$i];
1058						$data['value'] = $data_top[$i];
1059						$data['formated_value'] = format_for_graph($data_top[$i],2) . " " . $units[$i];
1060						$data_return[] = $data;
1061					}
1062					$i++;
1063					if ($i >= $top_n_value) break;
1064				}
1065			}
1066
1067
1068			$return['charts']['bars'] = null;
1069			$return['charts']['pie'] = null;
1070
1071
1072			if ($show_graph != REPORT_TOP_N_ONLY_TABLE) {
1073
1074				$return['charts']['pie'] = pie3d_graph(false,
1075					$data_pie_graph,
1076					$width, $height,
1077					__("other"),
1078					ui_get_full_url(false, true, false, false) . '/',
1079					ui_get_full_url(false, false, false, false) .  "/images/logo_vertical_water.png",
1080					$config['fontpath'],
1081					$config['font_size'],
1082					$ttl);
1083
1084
1085				//Display bars graph
1086				$return['charts']['bars'] = hbar_graph(
1087					false,
1088					$data_hbar,
1089					$width,
1090					count($data_hbar) * 50,
1091					array(),
1092					array(),
1093					"",
1094					"",
1095					true,
1096					ui_get_full_url(false, true, false, false) . '/',
1097					$config['homedir'] . "/images/logo_vertical_water.png",
1098					$config['fontpath'],
1099					$config['font_size'],
1100					true,
1101					$ttl,
1102					true);
1103			}
1104
1105			$return['resume'] = null;
1106
1107			if ($content['show_resume'] && count($data_top_values) > 0) {
1108				//Get the very first not null value
1109				$i=0;
1110				do {
1111					$min = $data_top_values['data_top'][$i];
1112					$i++;
1113				}
1114				while ($min === false && $i < count($data_top_values));
1115				$max = $min;
1116				$avg = 0;
1117
1118				$i=0;
1119				foreach ($data_top_values['data_top'] as $key => $dtv) {
1120					if ($dtv < $min) $min = $dtv;
1121					if ($dtv > $max) $max = $dtv;
1122					$avg += $dtv;
1123					$i++;
1124				}
1125				$avg = $avg / $i;
1126
1127
1128				$return['resume']['min']['value'] = $min;
1129				$return['resume']['min']['formated_value'] = format_for_graph($min, 2);
1130				$return['resume']['avg']['value'] = $avg;
1131				$return['resume']['avg']['formated_value'] = format_for_graph($avg, 2);
1132				$return['resume']['max']['value'] = $max;
1133				$return['resume']['max']['formated_value'] = format_for_graph($max, 2);
1134			}
1135
1136
1137			$return['data'] = $data_return;
1138		}
1139	}
1140
1141	return reporting_check_structure_content($return);
1142}
1143
1144function reporting_event_report_group($report, $content,
1145	$type = 'dinamic', $force_width_chart = null,
1146	$force_height_chart = null) {
1147
1148	global $config;
1149
1150	$return['type'] = 'event_report_group';
1151
1152	if (empty($content['name'])) {
1153		$content['name'] = __('Event Report Group');
1154	}
1155
1156	if ($config['metaconsole']) {
1157		$id_meta = metaconsole_get_id_server($content["server_name"]);
1158
1159
1160		$server = metaconsole_get_connection_by_id ($id_meta);
1161		metaconsole_connect($server);
1162	}
1163
1164	$return['title'] = $content['name'];
1165	$return['subtitle'] = groups_get_name($content['id_group'], true);
1166	if (!empty($content['style']['event_filter_search'])) {
1167		$return['subtitle'] .= " (" . $content['style']['event_filter_search'] . ")";
1168	}
1169	$return["description"] = $content["description"];
1170	$return["date"] = reporting_get_date_text($report, $content);
1171
1172
1173	$filter_event_no_validated = $content['style']['filter_event_no_validated'];
1174	$filter_event_validated = $content['style']['filter_event_validated'];
1175	$filter_event_critical = $content['style']['filter_event_critical'];
1176	$filter_event_warning = $content['style']['filter_event_warning'];
1177	$filter_event_filter_search = $content['style']['event_filter_search'];
1178
1179	$event_graph_by_agent = $content['style']['event_graph_by_agent'];
1180	$event_graph_by_user_validator = $content['style']['event_graph_by_user_validator'];
1181	$event_graph_by_criticity = $content['style']['event_graph_by_criticity'];
1182	$event_graph_validated_vs_unvalidated = $content['style']['event_graph_validated_vs_unvalidated'];
1183
1184
1185	$data = reporting_get_group_detailed_event(
1186		$content['id_group'], $content['period'], $report["datetime"],
1187		true, true, $filter_event_validated, $filter_event_critical,
1188		$filter_event_warning, $filter_event_no_validated,
1189		$filter_event_filter_search, 'hash');
1190
1191	if (empty($data)) {
1192		$return['failed'] = __('No events');
1193	}
1194	else {
1195		$return['data'] = $data;
1196	}
1197
1198
1199
1200	reporting_set_conf_charts($width, $height, $only_image, $type,
1201		$content, $ttl);
1202
1203	if (!empty($force_width_chart)) {
1204		$width = $force_width_chart;
1205	}
1206
1207	if (!empty($force_height_chart)) {
1208		$height = $force_height_chart;
1209	}
1210
1211
1212
1213	$return['chart']['by_agent'] = null;
1214	$return['chart']['by_user_validator'] = null;
1215	$return['chart']['by_criticity'] = null;
1216	$return['chart']['validated_vs_unvalidated'] = null;
1217
1218	if ($event_graph_by_agent) {
1219		$data_graph = reporting_get_count_events_by_agent(
1220			$content['id_group'], $content['period'],
1221			$report["datetime"],
1222			$filter_event_validated,
1223			$filter_event_critical,
1224			$filter_event_warning,
1225			$filter_event_no_validated,
1226			$filter_event_filter_search);
1227
1228		$return['chart']['by_agent']= pie3d_graph(
1229			false,
1230			$data_graph,
1231			500,
1232			150,
1233			__("other"),
1234			ui_get_full_url(false, false, false, false),
1235			ui_get_full_url(false, false, false, false) . "/images/logo_vertical_water.png",
1236			$config['fontpath'],
1237			$config['font_size'],
1238			$ttl);
1239	}
1240
1241	if ($event_graph_by_user_validator) {
1242		$data_graph =
1243			reporting_get_count_events_validated_by_user(
1244				array('id_group' => $content['id_group']), $content['period'],
1245				$report["datetime"],
1246				$filter_event_validated,
1247				$filter_event_critical,
1248				$filter_event_warning,
1249				$filter_event_no_validated,
1250				$filter_event_filter_search);
1251
1252		$return['chart']['by_user_validator'] = pie3d_graph(
1253			false,
1254			$data_graph,
1255			500,
1256			150,
1257			__("other"),
1258			ui_get_full_url(false, false, false, false),
1259			ui_get_full_url(false, false, false, false) . "/images/logo_vertical_water.png",
1260			$config['fontpath'],
1261			$config['font_size'],
1262			$ttl);
1263	}
1264
1265	if ($event_graph_by_criticity) {
1266		$data_graph = reporting_get_count_events_by_criticity(
1267			array('id_group' => $content['id_group']), $content['period'],
1268			$report["datetime"],
1269			$filter_event_validated,
1270			$filter_event_critical,
1271			$filter_event_warning,
1272			$filter_event_no_validated,
1273			$filter_event_filter_search);
1274
1275		$colors = get_criticity_pie_colors($data_graph);
1276
1277		$return['chart']['by_criticity'] = pie3d_graph(
1278			false,
1279			$data_graph,
1280			500,
1281			150,
1282			__("other"),
1283			ui_get_full_url(false, false, false, false),
1284			ui_get_full_url(false, false, false, false) .  "/images/logo_vertical_water.png",
1285			$config['fontpath'],
1286			$config['font_size'],
1287			$ttl,
1288			false,
1289			$colors);
1290	}
1291
1292	if ($event_graph_validated_vs_unvalidated) {
1293		$data_graph =
1294			reporting_get_count_events_validated(
1295				array('id_group' => $content['id_group']), $content['period'],
1296				$report["datetime"],
1297				$filter_event_validated,
1298				$filter_event_critical,
1299				$filter_event_warning,
1300				$filter_event_no_validated,
1301				$filter_event_filter_search);
1302
1303		$return['chart']['validated_vs_unvalidated'] = pie3d_graph(
1304			false,
1305			$data_graph,
1306			500,
1307			150,
1308			__("other"),
1309			ui_get_full_url(false, false, false, false),
1310			ui_get_full_url(false, false, false, false) .  "/images/logo_vertical_water.png",
1311			$config['fontpath'],
1312			$config['font_size'],
1313			$ttl);
1314	}
1315
1316	if ($config['metaconsole']) {
1317		metaconsole_restore_db();
1318	}
1319
1320	return reporting_check_structure_content($return);
1321}
1322
1323function reporting_event_report_module($report, $content) {
1324	global $config;
1325
1326	$return['type'] = 'event_report_module';
1327
1328	if (empty($content['name'])) {
1329		$content['name'] = __('Event Report Module');
1330	}
1331
1332	if ($config['metaconsole']) {
1333		$id_meta = metaconsole_get_id_server($content["server_name"]);
1334
1335
1336		$server = metaconsole_get_connection_by_id ($id_meta);
1337		metaconsole_connect($server);
1338	}
1339
1340	$return['title'] = $content['name'];
1341	$return['subtitle'] = agents_get_name($content['id_agent']) .
1342		" - " .
1343		io_safe_output(
1344			modules_get_agentmodule_name($content['id_agent_module']));
1345	$return["description"] = $content["description"];
1346	$return["date"] = reporting_get_date_text($report, $content);
1347
1348	$data = reporting_get_module_detailed_event(
1349		$content['id_agent_module'], $content['period'],
1350		$report["datetime"], true, false, true);
1351
1352	if (empty($data)) {
1353		$return['failed'] = __('No events');
1354	}
1355	else {
1356		$return['data'] = $data;
1357	}
1358
1359	if ($config['metaconsole']) {
1360		metaconsole_restore_db();
1361	}
1362
1363	return reporting_check_structure_content($return);
1364}
1365
1366function reporting_inventory_changes($report, $content, $type) {
1367	global $config;
1368
1369	$return['type'] = 'inventory_changes';
1370
1371	if (empty($content['name'])) {
1372		$content['name'] = __('Inventory Changes');
1373	}
1374
1375	if ($config['metaconsole']) {
1376		$id_meta = metaconsole_get_id_server($content["server_name"]);
1377
1378
1379		$server = metaconsole_get_connection_by_id ($id_meta);
1380		metaconsole_connect($server);
1381	}
1382
1383	$return['title'] = $content['name'];
1384	$return['subtitle'] = agents_get_name($content['id_agent']);
1385	$return["description"] = $content["description"];
1386	$return["date"] = reporting_get_date_text($report, $content);
1387
1388	$es = json_decode($content['external_source'], true);
1389
1390	$id_agent = $es['id_agents'];
1391	$module_name = $es['inventory_modules'];
1392
1393
1394	switch ($type) {
1395		case 'data':
1396			$inventory_changes = inventory_get_changes(
1397				$id_agent, $module_name,
1398				$report["datetime"] - $content['period'],
1399				$report["datetime"], "csv");
1400			break;
1401		default:
1402			$inventory_changes = inventory_get_changes(
1403				$id_agent, $module_name,
1404				$report["datetime"] - $content['period'],
1405				$report["datetime"], "array");
1406			break;
1407	}
1408
1409
1410
1411	$return['data'] = array();
1412
1413	if ($inventory_changes == ERR_NODATA) {
1414		$return['failed'] = __('No changes found.');
1415	}
1416	else {
1417		$return['data'] = $inventory_changes;
1418	}
1419
1420	if ($config['metaconsole']) {
1421		metaconsole_restore_db();
1422	}
1423
1424	return reporting_check_structure_content($return);
1425}
1426
1427function reporting_inventory($report, $content, $type) {
1428	global $config;
1429
1430	$es = json_decode($content['external_source'], true);
1431
1432	$return['type'] = 'inventory';
1433
1434	if (empty($content['name'])) {
1435		$content['name'] = __('Inventory');
1436	}
1437
1438	if ($config['metaconsole']) {
1439		$id_meta = metaconsole_get_id_server($content["server_name"]);
1440
1441
1442		$server = metaconsole_get_connection_by_id ($id_meta);
1443		metaconsole_connect($server);
1444	}
1445
1446	$return['title'] = $content['name'];
1447	$return["description"] = $content["description"];
1448	$return["date"] = reporting_get_date_text($report, $content);
1449
1450	$es = json_decode($content['external_source'], true);
1451
1452	$id_agent = $es['id_agents'];
1453	$module_name = $es['inventory_modules'];
1454	if (empty($module_name)) {
1455		$module_name = array(0 => 0);
1456	}
1457	$date = $es['date'];
1458	$description = $content['description'];
1459
1460	switch ($type) {
1461		case 'data':
1462			$inventory_data = inventory_get_data(
1463				(array)$id_agent, (array)$module_name, $date, '', false,
1464				'csv');
1465			break;
1466		default:
1467			$inventory_data = inventory_get_data(
1468				(array)$id_agent, (array)$module_name, $date, '', false,
1469				'hash');
1470			break;
1471	}
1472
1473
1474
1475	if ($inventory_data == ERR_NODATA) {
1476		$return['failed'] = __('No data found.');
1477	}
1478	else {
1479		$return['data'] = $inventory_data;
1480	}
1481
1482	if ($config['metaconsole']) {
1483		metaconsole_restore_db();
1484	}
1485
1486	return reporting_check_structure_content($return);
1487}
1488
1489function reporting_agent_module($report, $content) {
1490	global $config;
1491
1492	$id_group = $content['id_group'];
1493	$id_module_group = $content['id_module_group'];
1494
1495	$return['type'] = 'agent_module';
1496
1497
1498	if (empty($content['name'])) {
1499		$content['name'] = __('Agent/Modules');
1500	}
1501
1502	$return['title'] = $content['name'];
1503	$group_name = groups_get_name($content['id_group'], true);
1504	if ($content['id_module_group'] == 0) {
1505		$module_group_name = __('All');
1506	}
1507	else {
1508		$module_group_name = db_get_value('name', 'tmodule_group',
1509			'id_mg',  $content['id_module_group']);
1510	}
1511	$return['subtitle'] = $group_name . " - " . $module_group_name;
1512	$return["description"] = $content["description"];
1513	$return["date"] = reporting_get_date_text($report, $content);
1514
1515	$return["data"] = array();
1516
1517	$agents = array();
1518	if ($id_group > 0) {
1519		$agents = agents_get_group_agents($id_group);
1520		$agents = array_keys($agents);
1521	}
1522
1523	$filter_module_groups = false;
1524	if ($id_module_group > 0) {
1525		$filter_module_groups['id_module_group'] = $id_module_group;
1526	}
1527
1528	$all_modules = agents_get_modules($agents, false,
1529		$filter_module_groups, true, false);
1530
1531	$modules_by_name = array();
1532	$name = '';
1533	$cont = 0;
1534
1535	foreach ($all_modules as $key => $module) {
1536		if ($module == $name) {
1537			$modules_by_name[$cont - 1]['id'][] = $key;
1538		}
1539		else {
1540			$name = $module;
1541			$modules_by_name[$cont]['name'] = $name;
1542			$modules_by_name[$cont]['id'][] = $key;
1543			$cont ++;
1544		}
1545	}
1546
1547	$filter_groups = array();
1548	if ($id_group > 0) {
1549		$filter_groups['id_grupo'] = $id_group;
1550	}
1551	$agents = agents_get_agents ($filter_groups);
1552	$nagents = count($agents);
1553
1554	if ($all_modules == false || $agents == false) {
1555		$return['failed'] = __('There are no agents with modules');
1556	}
1557	else {
1558		foreach ($agents as $agent) {
1559			$row = array();
1560			$row['agent_status'][$agent['id_agente']] =
1561				agents_get_status($agent['id_agente']);
1562			$row['agent_name'] = $agent['nombre'];
1563
1564			$agent_modules = agents_get_modules($agent['id_agente']);
1565
1566			$row['modules'] = array();
1567			foreach ($modules_by_name as $module) {
1568				$row['modules'][$module['name']] = null;
1569				foreach ($module['id'] as $module_id) {
1570					if (array_key_exists($module_id, $agent_modules)) {
1571						$row['modules'][$module['name']] =
1572							modules_get_agentmodule_status($module_id);
1573						break;
1574					}
1575				}
1576			}
1577
1578			$return['data'][] = $row;
1579		}
1580	}
1581
1582	if ($config['metaconsole']) {
1583		metaconsole_restore_db();
1584	}
1585
1586	return reporting_check_structure_content($return);
1587}
1588
1589function reporting_exception($report, $content, $type = 'dinamic',
1590	$force_width_chart = null, $force_height_chart = null) {
1591
1592	global $config;
1593
1594	$return['type'] = 'exception';
1595
1596
1597	if (empty($content['name'])) {
1598		$content['name'] = __('Exception');
1599	}
1600
1601	$order_uptodown = $content['order_uptodown'];
1602	$exception_condition_value = $content['exception_condition_value'];
1603	$show_graph = $content['show_graph'];
1604
1605	$formated_exception_value = $exception_condition_value;
1606	if (is_numeric($exception_condition_value)) {
1607		$formated_exception_value = format_for_graph(
1608			$exception_condition_value, 2);
1609	}
1610
1611
1612	$return['title'] = $content['name'];
1613	$exception_condition = $content['exception_condition'];
1614	switch ($exception_condition) {
1615		case REPORT_EXCEPTION_CONDITION_EVERYTHING:
1616			$return['subtitle'] = __('Exception - Everything');
1617			$return['subtype'] = __('Everything');
1618			break;
1619		case REPORT_EXCEPTION_CONDITION_GE:
1620			$return['subtitle'] =
1621				sprintf(__('Exception - Modules over or equal to %s'),
1622				$formated_exception_value);
1623			$return['subtype'] = __('Modules over or equal to %s');
1624			break;
1625		case REPORT_EXCEPTION_CONDITION_LE:
1626			$return['subtitle'] =
1627				sprintf(__('Exception - Modules under or equal to %s'),
1628				$formated_exception_value);
1629			$return['subtype'] = __('Modules under or equal to %s');
1630			break;
1631		case REPORT_EXCEPTION_CONDITION_L:
1632			$return['subtitle'] =
1633				sprintf(__('Exception - Modules under %s'),
1634				$formated_exception_value);
1635			$return['subtype'] = __('Modules under %s');
1636			break;
1637		case REPORT_EXCEPTION_CONDITION_G:
1638			$return['subtitle'] =
1639				sprintf(__('Exception - Modules over %s'),
1640				$formated_exception_value);
1641			$return['subtype'] = __('Modules over %s');
1642			break;
1643		case REPORT_EXCEPTION_CONDITION_E:
1644			$return['subtitle'] =
1645				sprintf(__('Exception - Equal to %s'),
1646				$formated_exception_value);
1647			$return['subtype'] = __('Equal to %s');
1648			break;
1649		case REPORT_EXCEPTION_CONDITION_NE:
1650			$return['subtitle'] =
1651				sprintf(__('Exception - Not equal to %s'),
1652				$formated_exception_value);
1653			$return['subtype'] = __('Not equal to %s');
1654			break;
1655		case REPORT_EXCEPTION_CONDITION_OK:
1656			$return['subtitle'] =
1657				__('Exception - Modules at normal status');
1658			$return['subtype'] = __('Modules at normal status');
1659			break;
1660		case REPORT_EXCEPTION_CONDITION_NOT_OK:
1661			$return['subtitle'] =
1662				__('Exception - Modules at critical or warning status');
1663			$return['subtype'] = __('Modules at critical or warning status');
1664			break;
1665	}
1666	$return["description"] = $content["description"];
1667	$return["date"] = reporting_get_date_text($report, $content);
1668
1669	$return["data"] = array();
1670	$return["chart"] = array();
1671	$return["resume"] = array();
1672
1673
1674
1675
1676
1677	if (empty($content['subitems'])) {
1678		//Get all the related data
1679		$sql = sprintf("
1680			SELECT id_agent_module, server_name, operation
1681			FROM treport_content_item
1682			WHERE id_report_content = %d", $content['id_rc']);
1683
1684		$exceptions = db_process_sql ($sql);
1685	}
1686	else {
1687		$exceptions = $content['subitems'];
1688	}
1689
1690
1691	if ($exceptions === false) {
1692		$return['failed'] = __('There are no Agent/Modules defined');
1693	}
1694	else {
1695		//Get the very first not null value
1696		$i = 0;
1697		do {
1698			//Metaconsole connection
1699			$server_name = $exceptions[$i]['server_name'];
1700			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
1701				$connection = metaconsole_get_connection($server_name);
1702				if (metaconsole_load_external_db($connection) != NOERR) {
1703					//ui_print_error_message ("Error connecting to ".$server_name);
1704					continue;
1705				}
1706			}
1707
1708			if ($content['period'] == 0) {
1709				$min =
1710					modules_get_last_value($exceptions[$i]['id_agent_module']);
1711			}
1712			else {
1713				switch ($exceptions[$i]['operation']) {
1714					case 'avg':
1715						$min = reporting_get_agentmodule_data_average(
1716							$exceptions[$i]['id_agent_module'], $content['period']);
1717						break;
1718					case 'max':
1719						$min = reporting_get_agentmodule_data_max(
1720							$exceptions[$i]['id_agent_module'], $content['period']);
1721						break;
1722					case 'min':
1723						$min = reporting_get_agentmodule_data_min(
1724							$exceptions[$i]['id_agent_module'], $content['period']);
1725						break;
1726				}
1727			}
1728			$i++;
1729
1730			//Restore dbconnection
1731			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
1732				metaconsole_restore_db();
1733			}
1734		}
1735		while ($min === false && $i < count($exceptions));
1736		$max = $min;
1737		$avg = 0;
1738
1739
1740		$i = 0;
1741		foreach ($exceptions as $exc) {
1742			//Metaconsole connection
1743			$server_name = $exc['server_name'];
1744			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
1745				$connection = metaconsole_get_connection($server_name);
1746				if (metaconsole_load_external_db($connection) != NOERR) {
1747					//ui_print_error_message ("Error connecting to ".$server_name);
1748					continue;
1749				}
1750			}
1751
1752			$ag_name = modules_get_agentmodule_agent_name ($exc ['id_agent_module']);
1753			$mod_name = modules_get_agentmodule_name ($exc ['id_agent_module']);
1754			$unit = db_get_value('unit', 'tagente_modulo',
1755				'id_agente_modulo', $exc['id_agent_module']);
1756
1757			if ($content['period'] == 0) {
1758				$value =
1759					modules_get_last_value($exceptions[$i]['id_agent_module']);
1760			}
1761			else {
1762				switch ($exc['operation']) {
1763					case 'avg':
1764						$value = reporting_get_agentmodule_data_average ($exc['id_agent_module'], $content['period']);
1765						break;
1766					case 'max':
1767						$value = reporting_get_agentmodule_data_max ($exc['id_agent_module'], $content['period']);
1768						break;
1769					case 'min':
1770						$value = reporting_get_agentmodule_data_min ($exc['id_agent_module'], $content['period']);
1771						break;
1772				}
1773			}
1774
1775			if ($value !== false) {
1776				if ($value > $max) $max = $value;
1777				if ($value < $min) $min = $value;
1778				$avg += $value;
1779
1780				//Skips
1781				switch ($exception_condition) {
1782					case REPORT_EXCEPTION_CONDITION_EVERYTHING:
1783						break;
1784					case REPORT_EXCEPTION_CONDITION_GE:
1785						if ($value < $exception_condition_value) {
1786							continue 2;
1787						}
1788						break;
1789					case REPORT_EXCEPTION_CONDITION_LE:
1790						if ($value > $exception_condition_value) {
1791							continue 2;
1792						}
1793						break;
1794					case REPORT_EXCEPTION_CONDITION_L:
1795						if ($value > $exception_condition_value) {
1796							continue 2;
1797						}
1798						break;
1799					case REPORT_EXCEPTION_CONDITION_G:
1800						if ($value < $exception_condition_value) {
1801							continue 2;
1802						}
1803						break;
1804					case REPORT_EXCEPTION_CONDITION_E:
1805						if ($value != $exception_condition_value) {
1806							continue 2;
1807						}
1808						break;
1809					case REPORT_EXCEPTION_CONDITION_NE:
1810						if ($value == $exception_condition_value) {
1811							continue 2;
1812						}
1813						break;
1814					case REPORT_EXCEPTION_CONDITION_OK:
1815						if (modules_get_agentmodule_status($exc['id_agent_module']) != 0) {
1816							continue 2;
1817						}
1818						break;
1819					case REPORT_EXCEPTION_CONDITION_NOT_OK:
1820						if (modules_get_agentmodule_status($exc['id_agent_module']) == 0) {
1821							continue 2;
1822						}
1823						break;
1824				}
1825
1826				$i++;
1827				$data_exceptions[] = $value;
1828				$id_agent_module[] = $exc['id_agent_module'];
1829				$agent_name[] = $ag_name;
1830				$module_name[] = $mod_name;
1831				$units[] = $unit;
1832				if ($exc['operation'] == 'avg') {
1833					$operation[] = "rate";
1834				}
1835				else {
1836					$operation[] = $exc['operation'];
1837				}
1838			}
1839			//Restore dbconnection
1840			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
1841				metaconsole_restore_db();
1842			}
1843		}
1844
1845		if ($i == 0) {
1846			switch ($exception_condition) {
1847				case REPORT_EXCEPTION_CONDITION_EVERYTHING:
1848					$return['failed'] = __('There are no Modules under those conditions.');
1849					break;
1850				case REPORT_EXCEPTION_CONDITION_GE:
1851					$return['failed'] = __('There are no Modules over or equal to %s.', $exception_condition_value);
1852					break;
1853				case REPORT_EXCEPTION_CONDITION_LE:
1854					$return['failed'] = __('There are no Modules less or equal to %s.', $exception_condition_value);
1855					break;
1856				case REPORT_EXCEPTION_CONDITION_L:
1857					$return['failed'] = __('There are no Modules less %s.', $exception_condition_value);
1858					break;
1859				case REPORT_EXCEPTION_CONDITION_G:
1860					$return['failed'] = __('There are no Modules over %s.', $exception_condition_value);
1861					break;
1862				case REPORT_EXCEPTION_CONDITION_E:
1863					$return['failed'] = __('There are no Modules equal to %s', $exception_condition_value);
1864					break;
1865				case REPORT_EXCEPTION_CONDITION_NE:
1866					$return['failed'] = __('There are no Modules not equal to %s', $exception_condition_value);
1867					break;
1868				case REPORT_EXCEPTION_CONDITION_OK:
1869					$return['failed'] = __('There are no Modules normal status');
1870					break;
1871				case REPORT_EXCEPTION_CONDITION_NOT_OK:
1872					$return['failed'] = __('There are no Modules at critial or warning status');
1873					break;
1874			}
1875
1876		}
1877		else {
1878			$avg = $avg / $i;
1879
1880			switch ($order_uptodown) {
1881				//Order descending
1882				case 1:
1883					array_multisort($data_exceptions, SORT_DESC,
1884						$agent_name, SORT_ASC, $module_name, SORT_ASC,
1885						$id_agent_module, SORT_ASC);
1886					break;
1887				//Order ascending
1888				case 2:
1889					array_multisort($data_exceptions, SORT_ASC,
1890						$agent_name, SORT_ASC, $module_name, SORT_ASC,
1891						$id_agent_module, SORT_ASC);
1892					break;
1893				//Order by agent name or without selection
1894				case 0:
1895				case 3:
1896					array_multisort($agent_name, SORT_ASC,
1897						$data_exceptions, SORT_ASC, $module_name,
1898						SORT_ASC, $id_agent_module, SORT_ASC);
1899					break;
1900			}
1901
1902			if ($order_uptodown == 1 || $order_uptodown == 2) {
1903				$j = 0;
1904				$data_pie_graph = array();
1905				$data_hbar = array();
1906				foreach ($data_exceptions as $dex) {
1907					$data_hbar[$agent_name[$j]]['g'] = $dex;
1908					$data_pie_graph[$agent_name[$j]] = $dex;
1909					if ($show_graph == 0 || $show_graph == 1) {
1910						$data = array();
1911						$data['agent'] = $agent_name[$j];
1912						$data['module'] = $module_name[$j];
1913						$data['operation'] = __($operation[$j]);
1914						$data['value'] = $dex;
1915						$data['formated_value'] = format_for_graph($dex, 2) . " " . $units[$j];
1916						$return['data'][] = $data;
1917					}
1918					$j++;
1919				}
1920			}
1921			else if ($order_uptodown == 0 || $order_uptodown == 3) {
1922				$j = 0;
1923				$data_pie_graph = array();
1924				$data_hbar = array();
1925				foreach ($agent_name as $an) {
1926					$data_hbar[$an]['g'] = $data_exceptions[$j];
1927					$data_pie_graph[$an] = $data_exceptions[$j];
1928					if ($show_graph == 0 || $show_graph == 1) {
1929						$data = array();
1930						$data['agent'] = $an;
1931						$data['module'] = $module_name[$j];
1932						$data['operation'] = __($operation[$j]);
1933						$data['value'] = $data_exceptions[$j];
1934						$data['formated_value'] = format_for_graph($data_exceptions[$j], 2) . " " . $units[$j];
1935						$return['data'][] = $data;
1936					}
1937					$j++;
1938				}
1939			}
1940
1941			if ($show_graph == 1 || $show_graph == 2) {
1942
1943
1944				reporting_set_conf_charts($width, $height, $only_image,
1945					$type, $content, $ttl);
1946
1947				if (!empty($force_width_chart)) {
1948					$width = $force_width_chart;
1949				}
1950
1951				if (!empty($force_height_chart)) {
1952					$height = $force_height_chart;
1953				}
1954
1955
1956				$return["chart"]["pie"] = pie3d_graph(
1957					false,
1958					$data_pie_graph,
1959					600,
1960					150,
1961					__("other"),
1962					ui_get_full_url(false, false, false, false),
1963					ui_get_full_url(false, false, false, false) .  "/images/logo_vertical_water.png",
1964					$config['fontpath'],
1965					$config['font_size'],
1966					$ttl);
1967
1968
1969				$params = array(
1970					'flash_chart' => false,
1971					'chart_data' => $data_hbar,
1972					'width' => 600,
1973					'height' => 25 * count($data_hbar),
1974					'color' => array(),
1975					'legend' => array(),
1976					'long_index' => array(),
1977					'no_data_image' => ui_get_full_url("images/image_problem.opaque.png", false, false, false),
1978					'xaxisname' => "",
1979					'yaxisname' => "",
1980					'water_mark' => ui_get_full_url(false, false, false, false) .  "/images/logo_vertical_water.png",
1981					'font' => "",
1982					'font_size' => "",
1983					'unit' => "",
1984					'ttl' => $ttl,
1985					'homeurl' => ui_get_full_url(false, false, false, false),
1986					'backgroundColor' => 'white'
1987					);
1988				$return["chart"]["hbar"] = call_user_func_array(
1989					'hbar_graph',
1990					$params);
1991			}
1992
1993
1994
1995			if ($content['show_resume'] && $i > 0) {
1996				$return["resume"]['min']['value'] = $min;
1997				$return["resume"]['min']['formated_value'] = format_for_graph($min,2);
1998				$return["resume"]['max']['value'] = $max;
1999				$return["resume"]['max']['formated_value'] = format_for_graph($max,2);
2000				$return["resume"]['avg']['value'] = $avg;
2001				$return["resume"]['avg']['formated_value'] = format_for_graph($avg,2);
2002			}
2003
2004
2005		}
2006
2007	}
2008
2009
2010	return reporting_check_structure_content($return);
2011}
2012
2013function reporting_group_report($report, $content) {
2014	global $config;
2015
2016	$metaconsole_on = ($config['metaconsole'] == 1) && defined('METACONSOLE');
2017
2018	$return['type'] = 'group_report';
2019
2020
2021	if (empty($content['name'])) {
2022		$content['name'] = __('Group Report');
2023	}
2024
2025	if ($config['metaconsole']) {
2026		$id_meta = metaconsole_get_id_server($content["server_name"]);
2027
2028
2029		$server = metaconsole_get_connection_by_id ($id_meta);
2030		metaconsole_connect($server);
2031	}
2032
2033	$return['title'] = $content['name'];
2034	$return['subtitle'] = groups_get_name($content['id_group'], true);
2035	$return["description"] = $content["description"];
2036	$return["date"] = reporting_get_date_text($report, $content);
2037
2038	$return["data"] = array();
2039
2040	$events = events_get_group_events(
2041		$content['id_group'],
2042		$content['period'],
2043		$report['datetime'],
2044		false,
2045		false,
2046		false,
2047		false,
2048		false,
2049		$metaconsole_on);
2050
2051	if (empty($events)) {
2052		$events = array();
2053	}
2054	$return["data"]["count_events"] = count($events);
2055
2056	$return["data"]["group_stats"] = reporting_get_group_stats($content['id_group']);
2057
2058	if ($config['metaconsole']) {
2059		metaconsole_restore_db();
2060	}
2061
2062	return reporting_check_structure_content($return);
2063}
2064
2065function reporting_event_report_agent($report, $content,
2066	$type = 'dinamic', $force_width_chart = null,
2067	$force_height_chart = null) {
2068
2069	global $config;
2070
2071	$return['type'] = 'event_report_agent';
2072
2073	if (empty($content['name'])) {
2074		$content['name'] = __('Event Report Agent');
2075	}
2076
2077
2078	$return['title'] = $content['name'];
2079	$return['subtitle'] = agents_get_name($content['id_agent']);
2080	$return["description"] = $content["description"];
2081	$return["date"] = reporting_get_date_text($report, $content);
2082
2083	$style = $content['style'];
2084
2085	$filter_event_no_validated = $style['filter_event_no_validated'];
2086	$filter_event_validated = $style['filter_event_validated'];
2087	$filter_event_critical = $style['filter_event_critical'];
2088	$filter_event_warning = $style['filter_event_warning'];
2089
2090	$event_graph_by_user_validator = $style['event_graph_by_user_validator'];
2091	$event_graph_by_criticity = $style['event_graph_by_criticity'];
2092	$event_graph_validated_vs_unvalidated = $style['event_graph_validated_vs_unvalidated'];
2093
2094	$return['data'] = reporting_get_agents_detailed_event(
2095		$content['id_agent'],
2096		$content['period'],
2097		$report["datetime"],
2098		true,
2099		$filter_event_validated,
2100		$filter_event_critical,
2101		$filter_event_warning,
2102		$filter_event_no_validated,
2103		true);
2104
2105
2106
2107	reporting_set_conf_charts($width, $height, $only_image, $type,
2108		$content, $ttl);
2109
2110	if (!empty($force_width_chart)) {
2111		$width = $force_width_chart;
2112	}
2113
2114	if (!empty($force_height_chart)) {
2115		$height = $force_height_chart;
2116	}
2117
2118
2119
2120	$return["chart"]["by_user_validator"] = null;
2121	$return["chart"]["by_criticity"] = null;
2122	$return["chart"]["validated_vs_unvalidated"] = null;
2123
2124	if ($event_graph_by_user_validator) {
2125		$data_chart =
2126			reporting_get_count_events_validated_by_user(
2127				array('id_agent' => $content['id_agent']),
2128				$content['period'],
2129				$report["datetime"],
2130				$filter_event_validated,
2131				$filter_event_critical,
2132				$filter_event_warning,
2133				$filter_event_no_validated);
2134
2135		$return["chart"]["by_user_validator"] = pie3d_graph(
2136			false,
2137			$data_chart,
2138			500,
2139			150,
2140			__("other"),
2141			ui_get_full_url(false, false, false, false),
2142			ui_get_full_url(false, false, false, false) . "/images/logo_vertical_water.png",
2143			$config['fontpath'],
2144			$config['font_size'],
2145			$ttl);
2146	}
2147
2148	if ($event_graph_by_criticity) {
2149		$data_graph = reporting_get_count_events_by_criticity(
2150			array('id_agent' => $content['id_agent']), $content['period'],
2151			$report["datetime"],
2152			$filter_event_validated,
2153			$filter_event_critical,
2154			$filter_event_warning,
2155			$filter_event_no_validated);
2156
2157		$colors = get_criticity_pie_colors($data_graph);
2158
2159		$return["chart"]["by_criticity"] = pie3d_graph(
2160			false,
2161			$data_graph,
2162			500,
2163			150,
2164			__("other"),
2165			ui_get_full_url(false, false, false, false),
2166			ui_get_full_url(false, false, false, false) . "/images/logo_vertical_water.png",
2167			$config['fontpath'],
2168			$config['font_size'],
2169			$ttl,
2170			false,
2171			$colors);
2172	}
2173
2174	if ($event_graph_validated_vs_unvalidated) {
2175		$data_graph = reporting_get_count_events_validated(
2176			array('id_agent' => $content['id_agent']), $content['period'],
2177			$report["datetime"],
2178			$filter_event_validated,
2179			$filter_event_critical,
2180			$filter_event_warning,
2181			$filter_event_no_validated);
2182
2183		$return["chart"]["validated_vs_unvalidated"] = pie3d_graph(
2184			false,
2185			$data_graph,
2186			500,
2187			150,
2188			__("other"),
2189			ui_get_full_url(false, false, false, false),
2190			ui_get_full_url(false, false, false, false) . "/images/logo_vertical_water.png",
2191			$config['fontpath'],
2192			$config['font_size'],
2193			$ttl);
2194	}
2195
2196	if ($config['metaconsole']) {
2197		metaconsole_restore_db();
2198	}
2199
2200	return reporting_check_structure_content($return);
2201}
2202
2203function reporting_historical_data($report, $content) {
2204	global $config;
2205
2206	$return['type'] = 'historical_data';
2207	$period = $content['period'];
2208	$date_limit = time() - $period;
2209	if (empty($content['name'])) {
2210		$content['name'] = __('Historical data');
2211	}
2212
2213	$return['title'] = $content['name'];
2214	$return["description"] = $content["description"];
2215	$return["date"] = reporting_get_date_text($report, $content);
2216
2217	$return['keys'] = array(__('Date'), __('Data'));
2218
2219	$result = db_get_all_rows_sql 	(
2220									'SELECT *
2221									FROM tagente_datos
2222									WHERE id_agente_modulo =' . $content['id_agent_module'] . '
2223									 AND utimestamp >' . $date_limit . '
2224									 AND utimestamp <=' . time()
2225									);
2226
2227	$data = array();
2228	foreach ($result as $row) {
2229		$data[] = array(
2230			__('Date') => date ($config["date_format"], $row['utimestamp']),
2231			__('Data') => $row['datos']);
2232	}
2233
2234	$return["data"] = $data;
2235
2236	return reporting_check_structure_content($return);
2237}
2238
2239
2240function reporting_database_serialized($report, $content) {
2241	global $config;
2242
2243	$return['type'] = 'database_serialized';
2244
2245	if (empty($content['name'])) {
2246		$content['name'] = __('Database Serialized');
2247	}
2248
2249	$return['title'] = $content['name'];
2250	$return["description"] = $content["description"];
2251	$return["date"] = reporting_get_date_text($report, $content);
2252
2253	$keys = array();
2254	if ($content['header_definition'] != '') {
2255		$keys = explode('|', $content['header_definition']);
2256	}
2257
2258	$return['keys'] = $keys;
2259
2260
2261
2262	$module_name = io_safe_output(
2263		modules_get_agentmodule_name($content['id_agent_module']));
2264	$agent_name = io_safe_output(
2265		modules_get_agentmodule_agent_name ($content['id_agent_module']));
2266
2267	$return['agent_name'] = $agent_name;
2268	$return['module_name'] = $module_name;
2269
2270
2271	$datelimit = $report["datetime"] - $content['period'];
2272	$search_in_history_db = db_search_in_history_db($datelimit);
2273
2274	// This query gets information from the default and the historic database
2275	$result = db_get_all_rows_sql('SELECT *
2276		FROM tagente_datos
2277		WHERE id_agente_modulo = ' . $content['id_agent_module'] . '
2278			AND utimestamp > ' . $datelimit . '
2279			AND utimestamp <= ' . $report["datetime"], $search_in_history_db);
2280
2281	// Adds string data if there is no numeric data
2282	if ((count($result) < 0) or (!$result)) {
2283		// This query gets information from the default and the historic database
2284		$result = db_get_all_rows_sql('SELECT *
2285			FROM tagente_datos_string
2286			WHERE id_agente_modulo = ' . $content['id_agent_module'] . '
2287				AND utimestamp > ' . $datelimit . '
2288				AND utimestamp <= ' . $report["datetime"], $search_in_history_db);
2289	}
2290	if ($result === false) {
2291		$result = array();
2292	}
2293
2294	$data = array();
2295	foreach ($result as $row) {
2296		$date = date($config["date_format"], $row['utimestamp']);
2297		$serialized_data = $row['datos'];
2298
2299		// Cut line by line
2300		if (empty($content['line_separator']) ||
2301			empty($serialized_data)) {
2302
2303			$rowsUnserialize = array($row['datos']);
2304		}
2305		else {
2306			$rowsUnserialize = explode($content['line_separator'], $serialized_data);
2307		}
2308
2309
2310		foreach ($rowsUnserialize as $rowUnser) {
2311			$row = array();
2312
2313			$row['date'] = $date;
2314			$row['data'] = array();
2315
2316			if (empty($content['column_separator'])) {
2317				if (empty($keys)) {
2318					$row['data'][][] = $rowUnser;
2319				}
2320				else {
2321					$row['data'][][$keys[0]] = $rowUnser;
2322				}
2323			}
2324			else {
2325				$columnsUnserialize = explode($content['column_separator'], $rowUnser);
2326
2327
2328				$i = 0;
2329				$temp_row = array();
2330				foreach ($columnsUnserialize as $cell) {
2331					if (isset($keys[$i])) {
2332						$temp_row[$keys[$i]] = $cell;
2333					}
2334					else {
2335						$temp_row[] = $cell;
2336					}
2337					$i++;
2338				}
2339
2340				$row['data'][] = $temp_row;
2341			}
2342
2343			$data[] = $row;
2344		}
2345	}
2346
2347	$return["data"] = $data;
2348
2349	return reporting_check_structure_content($return);
2350}
2351
2352function reporting_group_configuration($report, $content) {
2353	global $config;
2354
2355	$return['type'] = 'group_configuration';
2356
2357	if (empty($content['name'])) {
2358		$content['name'] = __('Group configuration');
2359	}
2360
2361	if ($config['metaconsole']) {
2362		$id_meta = metaconsole_get_id_server($content["server_name"]);
2363
2364
2365		$server = metaconsole_get_connection_by_id ($id_meta);
2366		metaconsole_connect($server);
2367	}
2368
2369	$group_name = groups_get_name($content['id_group'], true);
2370
2371	$return['title'] = $content['name'];
2372	$return['subtitle'] = $group_name;
2373	$return["description"] = $content["description"];
2374	$return["date"] = reporting_get_date_text($report, $content);
2375	$return['id_group'] = $content['id_group'];
2376
2377
2378	if ($content['id_group'] == 0) {
2379		switch ($config["dbtype"]) {
2380			case "mysql":
2381			case "postgresql":
2382				$sql = "SELECT * FROM tagente;";
2383				break;
2384			case "oracle":
2385				$sql = "SELECT * FROM tagente";
2386				break;
2387		}
2388	}
2389	else {
2390		$sql = "
2391			SELECT *
2392			FROM tagente
2393			WHERE id_grupo=" . $content['id_group'];
2394	}
2395
2396	$agents_list = db_get_all_rows_sql($sql);
2397	if ($agents_list === false)
2398		$agents_list = array();
2399
2400	$return['data'] = array();
2401	foreach ($agents_list as $agent) {
2402		$content_agent = $content;
2403		$content_agent['id_agent'] = $agent['id_agente'];
2404
2405		// Restore the connection to metaconsole
2406		// because into the function reporting_agent_configuration
2407		// connect to metaconsole.
2408
2409		if ($config['metaconsole']) {
2410			metaconsole_restore_db();
2411		}
2412		$agent_report = reporting_agent_configuration(
2413			$report, $content_agent);
2414
2415
2416		$return['data'][] = $agent_report['data'];
2417	}
2418
2419	if ($config['metaconsole']) {
2420		metaconsole_restore_db();
2421	}
2422
2423	return reporting_check_structure_content($return);
2424}
2425
2426function reporting_network_interfaces_report($report, $content,
2427	$type = 'dinamic', $force_width_chart = null, $force_height_chart = null) {
2428
2429	global $config;
2430
2431	$return['type'] = 'network_interfaces_report';
2432
2433	if (empty($content['name'])) {
2434		$content['name'] = __('Network interfaces report');
2435	}
2436
2437	$group_name = groups_get_name($content['id_group']);
2438
2439	$return['title'] = $content['name'];
2440	$return['subtitle'] = $group_name;
2441	$return["description"] = $content["description"];
2442	$return["date"] = reporting_get_date_text($report, $content);
2443
2444	include_once($config['homedir'] . "/include/functions_custom_graphs.php");
2445
2446	$filter = array(
2447		'id_grupo' => $content['id_group'],
2448		'disabled' => 0);
2449	$network_interfaces_by_agents = agents_get_network_interfaces(false, $filter);
2450
2451	if (empty($network_interfaces_by_agents)) {
2452		$return['failed'] =
2453			__('The group has no agents or none of the agents has any network interface');
2454		$return['data'] = array();
2455	}
2456	else {
2457		$return['failed'] = null;
2458		$return['data'] = array();
2459
2460		foreach ($network_interfaces_by_agents as $agent_id => $agent) {
2461			$row_data = array();
2462
2463			$row_data['agent'] = $agent['name'];
2464
2465			$row_data['interfaces'] = array();
2466			foreach ($agent['interfaces'] as $interface_name => $interface) {
2467				$row_interface = array();
2468
2469				$row_interface['name'] = $interface_name;
2470				$row_interface['ip'] = $interface['ip'];
2471				$row_interface['mac'] = $interface['mac'];
2472				$row_interface['status'] = $interface['status_image'];
2473				$row_interface['chart'] = null;
2474
2475				// Get chart
2476				reporting_set_conf_charts($width, $height, $only_image,
2477					$type, $content, $ttl);
2478
2479				if (!empty($force_width_chart)) {
2480					$width = $force_width_chart;
2481				}
2482
2483				if (!empty($force_height_chart)) {
2484					$height = $force_height_chart;
2485				}
2486
2487				switch ($type) {
2488					case 'dinamic':
2489					case 'static':
2490						if (!empty($interface['traffic'])) {
2491							$row_interface['chart'] = custom_graphs_print(0,
2492								$height,
2493								$width,
2494								$content['period'],
2495								null,
2496								true,
2497								$report["datetime"],
2498								$only_image,
2499								'white',
2500								array_values($interface['traffic']),
2501								$config['homeurl'],
2502								array_keys($interface['traffic']),
2503								array_fill(0, count($interface['traffic']), __("bytes/s")),
2504								false,
2505								true,
2506								true,
2507								true,
2508								$ttl);
2509							}
2510						break;
2511					case 'data':
2512						break;
2513				}
2514
2515				$row_data['interfaces'][] = $row_interface;
2516			}
2517
2518			$return['data'][] = $row_data;
2519		}
2520	}
2521
2522	return reporting_check_structure_content($return);
2523}
2524
2525function reporting_alert_report_group($report, $content) {
2526
2527	global $config;
2528
2529	$return['type'] = 'alert_report_group';
2530
2531	if (empty($content['name'])) {
2532		$content['name'] = __('Alert Report Group');
2533	}
2534
2535	if ($config['metaconsole']) {
2536		$id_meta = metaconsole_get_id_server($content["server_name"]);
2537
2538
2539		$server = metaconsole_get_connection_by_id ($id_meta);
2540		metaconsole_connect($server);
2541	}
2542
2543	$group_name = groups_get_name($content['id_group'], true);
2544
2545	$return['title'] = $content['name'];
2546	$return['subtitle'] = $group_name;
2547	$return["description"] = $content["description"];
2548	$return["date"] = reporting_get_date_text($report, $content);
2549
2550	if ($content['id_group'] == 0) {
2551		$alerts = db_get_all_rows_sql('
2552			SELECT *
2553			FROM talert_template_modules
2554			WHERE disabled = 0
2555				AND id_agent_module IN (
2556					SELECT id_agente_modulo
2557					FROM tagente_modulo)');
2558	}
2559	else {
2560		$alerts = db_get_all_rows_sql('
2561			SELECT *
2562			FROM talert_template_modules
2563			WHERE disabled = 0
2564				AND id_agent_module IN (
2565					SELECT id_agente_modulo
2566					FROM tagente_modulo
2567					WHERE id_agente IN (
2568						SELECT id_agente
2569						FROM tagente WHERE id_grupo = ' . $content['id_group'] . '))');
2570	}
2571
2572	if (empty($alerts)) {
2573		$alerts = array();
2574	}
2575
2576
2577	$data = array();
2578
2579	foreach ($alerts as $alert) {
2580		$data_row = array();
2581
2582		$data_row['disabled'] = $alert['disabled'];
2583
2584		$data_row['agent'] = io_safe_output(agents_get_name(
2585			agents_get_agent_id_by_module_id($alert['id_agent_module'])));
2586		$data_row['module'] = db_get_value_filter('nombre', 'tagente_modulo',
2587			array('id_agente_modulo' => $alert['id_agent_module']));
2588		$data_row['template'] = db_get_value_filter('name', 'talert_templates',
2589			array('id' => $alert['id_alert_template']));
2590
2591
2592		$actions = db_get_all_rows_sql('SELECT name
2593			FROM talert_actions
2594			WHERE id IN (SELECT id_alert_action
2595				FROM talert_template_module_actions
2596				WHERE id_alert_template_module = ' . $alert['id_alert_template'] . ')');
2597
2598		if (!empty($actions)) {
2599			$row = db_get_row_sql('SELECT id_alert_action
2600				FROM talert_templates
2601				WHERE id IN (SELECT id_alert_template
2602					FROM talert_template_modules
2603					WHERE id = ' . $alert['id_alert_template'] . ')');
2604
2605			$id_action = 0;
2606			if (!empty($row))
2607				$id_action = $row['id_alert_action'];
2608
2609			// Prevent from void action
2610			if (empty($id_action))
2611				$id_action = 0;
2612
2613			$actions = db_get_all_rows_sql('SELECT name
2614				FROM talert_actions
2615				WHERE id = ' . $id_action);
2616
2617			if (empty($actions)) {
2618				$actions = array();
2619			}
2620		}
2621
2622		$data_row['action'] = array();
2623		foreach ($actions as $action) {
2624			$data_row['action'][] = $action['name'];
2625		}
2626
2627		$data_row['fired'] = array();
2628		$firedTimes = get_module_alert_fired(
2629			$content['id_agent_module'],
2630			$alert['id_alert_template'],
2631			(int) $content['period'],
2632			(int) $report["datetime"]);
2633		if (empty($firedTimes)) {
2634			$firedTimes = array();
2635		}
2636		foreach ($firedTimes as $fireTime) {
2637			$data_row['fired'][] = $fireTime['timestamp'];
2638		}
2639
2640		$data[] = $data_row;
2641	}
2642
2643	$return['data'] = $data;
2644
2645	if ($config['metaconsole']) {
2646		metaconsole_restore_db();
2647	}
2648
2649	return reporting_check_structure_content($return);
2650}
2651
2652function reporting_alert_report_agent($report, $content) {
2653
2654	global $config;
2655
2656	$return['type'] = 'alert_report_agent';
2657
2658	if (empty($content['name'])) {
2659		$content['name'] = __('Alert Report Agent');
2660	}
2661
2662	if ($config['metaconsole']) {
2663		$id_meta = metaconsole_get_id_server($content["server_name"]);
2664
2665
2666
2667		$server = metaconsole_get_connection_by_id ($id_meta);
2668		metaconsole_connect($server);
2669	}
2670
2671	$agent_name = agents_get_name($content['id_agent']);
2672
2673	$return['title'] = $content['name'];
2674	$return['subtitle'] = $agent_name;
2675	$return["description"] = $content["description"];
2676	$return["date"] = reporting_get_date_text($report, $content);
2677
2678	$alerts = agents_get_alerts($content['id_agent']);
2679
2680	if (isset($alerts['simple'])) {
2681		$alerts = $alerts['simple'];
2682	}
2683	else {
2684		$alerts = array();
2685	}
2686
2687	$data = array();
2688
2689	foreach ($alerts as $alert) {
2690		$data_row = array();
2691
2692		$data_row['disabled'] = $alert['disabled'];
2693
2694		$data_row['module'] = db_get_value_filter('nombre', 'tagente_modulo',
2695			array('id_agente_modulo' => $alert['id_agent_module']));
2696		$data_row['template'] = db_get_value_filter('name', 'talert_templates',
2697			array('id' => $alert['id_alert_template']));
2698
2699
2700
2701		switch ($config["dbtype"]) {
2702			case "mysql":
2703			case "postgresql":
2704				$actions = db_get_all_rows_sql('SELECT name
2705					FROM talert_actions
2706					WHERE id IN (SELECT id_alert_action
2707						FROM talert_template_module_actions
2708						WHERE id_alert_template_module = ' . $alert['id_alert_template'] . ');');
2709				break;
2710			case "oracle":
2711				$actions = db_get_all_rows_sql('SELECT name
2712					FROM talert_actions
2713					WHERE id IN (SELECT id_alert_action
2714						FROM talert_template_module_actions
2715						WHERE id_alert_template_module = ' . $alert['id_alert_template'] . ')');
2716				break;
2717		}
2718
2719
2720
2721
2722		if (!empty($actions)) {
2723			$row = db_get_row_sql('SELECT id_alert_action
2724				FROM talert_templates
2725				WHERE id IN (SELECT id_alert_template
2726					FROM talert_template_modules
2727					WHERE id = ' . $alert['id_alert_template'] . ')');
2728
2729			$id_action = 0;
2730			if (!empty($row))
2731				$id_action = $row['id_alert_action'];
2732
2733			// Prevent from void action
2734			if (empty($id_action))
2735				$id_action = 0;
2736
2737			$actions = db_get_all_rows_sql('SELECT name
2738				FROM talert_actions
2739				WHERE id = ' . $id_action);
2740
2741			if (empty($actions)) {
2742				$actions = array();
2743			}
2744		}
2745
2746		$data_row['action'] = array();
2747		foreach ($actions as $action) {
2748			$data_row['action'][] = $action['name'];
2749		}
2750
2751		$data_row['fired'] = array();
2752		$firedTimes = get_module_alert_fired(
2753			$alert['id_agent_module'],
2754			$alert['id_alert_template'],
2755			(int) $content['period'],
2756			(int) $report["datetime"]);
2757
2758
2759
2760		if (empty($firedTimes)) {
2761			$firedTimes = array();
2762		}
2763		foreach ($firedTimes as $fireTime) {
2764			$data_row['fired'][] = $fireTime['timestamp'];
2765		}
2766
2767		$data[] = $data_row;
2768	}
2769
2770	$return['data'] = $data;
2771
2772	if ($config['metaconsole']) {
2773		metaconsole_restore_db();
2774	}
2775
2776	return reporting_check_structure_content($return);
2777}
2778
2779function reporting_alert_report_module($report, $content) {
2780
2781	global $config;
2782
2783	$return['type'] = 'alert_report_module';
2784
2785	if (empty($content['name'])) {
2786		$content['name'] = __('Alert Report Module');
2787	}
2788
2789	if ($config['metaconsole']) {
2790		$id_meta = metaconsole_get_id_server($content["server_name"]);
2791
2792
2793		$server = metaconsole_get_connection_by_id ($id_meta);
2794		metaconsole_connect($server);
2795	}
2796
2797	$module_name = io_safe_output(
2798		modules_get_agentmodule_name($content['id_agent_module']));
2799	$agent_name = io_safe_output(
2800		modules_get_agentmodule_agent_name ($content['id_agent_module']));
2801
2802	$return['title'] = $content['name'];
2803	$return['subtitle'] = $agent_name . " - " . $module_name;
2804	$return["description"] = $content["description"];
2805	$return["date"] = reporting_get_date_text($report, $content);
2806
2807	switch ($config["dbtype"]) {
2808		case "mysql":
2809		case "postgresql":
2810			$alerts = db_get_all_rows_sql('
2811				SELECT *, t1.id as id_alert_template_module
2812				FROM talert_template_modules t1
2813				INNER JOIN talert_templates t2
2814					ON t1.id_alert_template = t2.id
2815				WHERE id_agent_module = ' . $content['id_agent_module']);
2816			break;
2817		case "oracle":
2818			$alerts = db_get_all_rows_sql('
2819				SELECT t1.*, t2.*, t1.id as id_alert_template_module
2820				FROM talert_template_modules t1
2821				INNER JOIN talert_templates t2
2822					ON t1.id_alert_template = t2.id
2823				WHERE id_agent_module = ' . $content['id_agent_module']);
2824			break;
2825	}
2826
2827
2828	if ($alerts === false) {
2829		$alerts = array();
2830	}
2831
2832	$data = array();
2833	foreach ($alerts as $alert) {
2834		$data_row = array();
2835
2836		$data_row['disabled'] = $alert['disabled'];
2837
2838		$data_row['template'] = db_get_value_filter('name',
2839			'talert_templates', array('id' => $alert['id_alert_template']));
2840
2841		switch ($config["dbtype"]) {
2842			case "mysql":
2843			case "postgresql":
2844				$actions = db_get_all_rows_sql('SELECT name
2845					FROM talert_actions
2846					WHERE id IN (SELECT id_alert_action
2847						FROM talert_template_module_actions
2848						WHERE id_alert_template_module = ' . $alert['id_alert_template_module'] . ');');
2849				break;
2850			case "oracle":
2851				$actions = db_get_all_rows_sql('SELECT name
2852					FROM talert_actions
2853					WHERE id IN (SELECT id_alert_action
2854						FROM talert_template_module_actions
2855						WHERE id_alert_template_module = ' . $alert['id_alert_template_module'] . ')');
2856				break;
2857		}
2858
2859
2860
2861		if (!empty($actions)) {
2862			$row = db_get_row_sql('SELECT id_alert_action
2863				FROM talert_templates
2864				WHERE id IN (SELECT id_alert_template
2865					FROM talert_template_modules
2866					WHERE id = ' . $alert['id_alert_template_module'] . ')');
2867
2868			$id_action = 0;
2869			if (!empty($row))
2870				$id_action = $row['id_alert_action'];
2871
2872			// Prevent from void action
2873			if (empty($id_action))
2874				$id_action = 0;
2875
2876			$actions = db_get_all_rows_sql('SELECT name
2877				FROM talert_actions
2878				WHERE id = ' . $id_action);
2879
2880			if (empty($actions)) {
2881				$actions = array();
2882			}
2883		}
2884
2885		$data_row['action'] = array();
2886		foreach ($actions as $action) {
2887			$data_row['action'][] = $action['name'];
2888		}
2889
2890		$data_row['fired'] = array();
2891		$firedTimes = get_module_alert_fired(
2892			$content['id_agent_module'],
2893			$alert['id_alert_template_module'],
2894			(int) $content['period'],
2895			(int) $report["datetime"]);
2896
2897
2898
2899		if (empty($firedTimes)) {
2900			$firedTimes = array();
2901		}
2902		foreach ($firedTimes as $fireTime) {
2903			$data_row['fired'][] = $fireTime['timestamp'];
2904		}
2905
2906		$data[] = $data_row;
2907	}
2908
2909	$return['data'] = $data;
2910
2911	if ($config['metaconsole']) {
2912		metaconsole_restore_db();
2913	}
2914
2915	return reporting_check_structure_content($return);
2916}
2917
2918function reporting_sql_graph($report, $content, $type,
2919	$force_width_chart, $force_height_chart, $type_sql_graph) {
2920
2921	global $config;
2922
2923	switch ($type_sql_graph) {
2924		case 'sql_graph_hbar':
2925			$return['type'] = 'sql_graph_hbar';
2926			break;
2927		case 'sql_graph_vbar':
2928			$return['type'] = 'sql_graph_vbar';
2929			break;
2930		case 'sql_graph_pie':
2931			$return['type'] = 'sql_graph_pie';
2932			break;
2933	}
2934
2935	if (empty($content['name'])) {
2936		switch ($type_sql_graph) {
2937			case 'sql_graph_vbar':
2938				$return['name'] = __('SQL Graph Vertical Bars');
2939				break;
2940			case 'sql_graph_hbar':
2941				$return['name'] = __('SQL Graph Horizontal Bars');
2942				break;
2943			case 'sql_graph_pie':
2944				$return['name'] = __('SQL Graph Pie');
2945				break;
2946		}
2947	}
2948
2949	// Get chart
2950	reporting_set_conf_charts($width, $height, $only_image, $type,
2951		$content, $ttl);
2952
2953	if (!empty($force_width_chart)) {
2954		$width = $force_width_chart;
2955	}
2956
2957	if (!empty($force_height_chart)) {
2958		$height = $force_height_chart;
2959	}
2960
2961	$return['title'] = $content['name'];
2962	$return["description"] = $content["description"];
2963	$return["date"] = reporting_get_date_text();
2964
2965	switch ($type) {
2966		case 'dinamic':
2967		case 'static':
2968			$return['chart'] = graph_custom_sql_graph(
2969				$content["id_rc"],
2970				$width,
2971				$height,
2972				$content["type"],
2973				true,
2974				ui_get_full_url(false, false, false, false),
2975				$ttl);
2976			break;
2977		case 'data':
2978			break;
2979	}
2980
2981	return reporting_check_structure_content($return);
2982}
2983
2984function reporting_monitor_report($report, $content) {
2985	global $config;
2986
2987
2988	$return['type'] = 'monitor_report';
2989
2990	if (empty($content['name'])) {
2991		$content['name'] = __('Monitor Report');
2992	}
2993
2994	$return['title'] = $content['name'];
2995	$return["description"] = $content["description"];
2996	$return["date"] = reporting_get_date_text($report, $content);
2997
2998	if ($config['metaconsole']) {
2999		$id_meta = metaconsole_get_id_server($content["server_name"]);
3000
3001
3002		$server = metaconsole_get_connection_by_id ($id_meta);
3003		metaconsole_connect($server);
3004	}
3005
3006	$module = modules_get_agentmodule ($content['id_agent_module']);
3007
3008	$module_name = io_safe_output(
3009		modules_get_agentmodule_name($content['id_agent_module']));
3010	$agent_name = io_safe_output(
3011		modules_get_agentmodule_agent_name ($content['id_agent_module']));
3012
3013	$return['agent_name'] = $agent_name;
3014	$return['module_name'] = $module_name;
3015
3016	$value = reporting_get_agentmodule_monitor(
3017		$content['id_agent_module'],
3018		$content['period'],
3019		$module['min_critical'],
3020		$module['max_critical'],
3021		$report["datetime"]);
3022
3023	if ($value === __('Unknown')) {
3024		$return['data']['unknown'] = 1;
3025	}
3026	else {
3027		$return['data']['unknown'] = 0;
3028
3029		$return["data"]["ok"]["value"] = $value;
3030		$return["data"]["ok"]["formated_value"] = format_numeric($value, 2);
3031
3032		$return["data"]["fail"]["value"] = 100 - $return["data"]["ok"]["value"];
3033		$return["data"]["fail"]["formated_value"] = (100 - $return["data"]["ok"]["formated_value"]);
3034	}
3035
3036	if ($config['metaconsole']) {
3037		metaconsole_restore_db();
3038	}
3039
3040	return reporting_check_structure_content($return);
3041}
3042
3043function reporting_netflow($report, $content, $type,
3044	$force_width_chart, $force_height_chart, $type_netflow = null) {
3045
3046	global $config;
3047
3048	switch ($type_netflow) {
3049		case 'netflow_area':
3050			$return['type'] = 'netflow_area';
3051			break;
3052		case 'netflow_pie':
3053			$return['type'] = 'netflow_pie';
3054			break;
3055		case 'netflow_data':
3056			$return['type'] = 'netflow_data';
3057			break;
3058		case 'netflow_statistics':
3059			$return['type'] = 'netflow_statistics';
3060			break;
3061		case 'netflow_summary':
3062			$return['type'] = 'netflow_summary';
3063			break;
3064	}
3065
3066	if (empty($content['name'])) {
3067		switch ($type_netflow) {
3068			case 'netflow_area':
3069				$return['name'] = __('Netflow Area');
3070				break;
3071			case 'netflow_pie':
3072				$return['name'] = __('Netflow Pie');
3073				break;
3074			case 'netflow_data':
3075				$return['name'] = __('Netflow Data');
3076				break;
3077			case 'netflow_statistics':
3078				$return['name'] = __('Netflow Statistics');
3079				break;
3080			case 'netflow_summary':
3081				$return['name'] = __('Netflow Summary');
3082				break;
3083		}
3084	}
3085
3086	$return['title'] = $content['name'];
3087	$return["description"] = $content["description"];
3088	$return["date"] = reporting_get_date_text($report, $content);
3089
3090	// Get chart
3091	reporting_set_conf_charts($width, $height, $only_image, $type,
3092		$content, $ttl);
3093
3094	if (!empty($force_width_chart)) {
3095		$width = $force_width_chart;
3096	}
3097
3098	if (!empty($force_height_chart)) {
3099		$height = $force_height_chart;
3100	}
3101
3102	// Get item filters
3103	$filter = db_get_row_sql("SELECT *
3104		FROM tnetflow_filter
3105		WHERE id_sg = '" . (int)$content['text'] . "'", false, true);
3106
3107	switch ($type) {
3108		case 'dinamic':
3109		case 'static':
3110			$return['chart'] = netflow_draw_item (
3111				$report['datetime'] - $content['period'],
3112				$report['datetime'],
3113				$content['top_n'],
3114				$type_netflow,
3115				$filter,
3116				$content['top_n_value'],
3117				$content ['server_name'],
3118				'HTML');
3119			break;
3120		case 'data':
3121			break;
3122	}
3123
3124	return reporting_check_structure_content($return);
3125}
3126
3127function reporting_simple_baseline_graph($report, $content,
3128	$type = 'dinamic', $force_width_chart = null,
3129	$force_height_chart = null) {
3130
3131	global $config;
3132
3133	if ($config['metaconsole']) {
3134		$id_meta = metaconsole_get_id_server($content["server_name"]);
3135
3136
3137		$server = metaconsole_get_connection_by_id ($id_meta);
3138		metaconsole_connect($server);
3139	}
3140
3141	$return['type'] = 'simple_baseline_graph';
3142
3143	if (empty($content['name'])) {
3144		$content['name'] = __('Simple baseline graph');
3145	}
3146
3147	$return['title'] = $content['name'];
3148	$return["description"] = $content["description"];
3149	$return["date"] = reporting_get_date_text($report, $content);
3150
3151	// Get chart
3152	reporting_set_conf_charts($width, $height, $only_image, $type,
3153		$content, $ttl);
3154
3155	if (!empty($force_width_chart)) {
3156		$width = $force_width_chart;
3157	}
3158
3159	if (!empty($force_height_chart)) {
3160		$height = $force_height_chart;
3161	}
3162
3163	switch ($type) {
3164		case 'dinamic':
3165		case 'static':
3166			$return['chart'] = grafico_modulo_sparse(
3167				$content['id_agent_module'],
3168				$content['period'],
3169				false,
3170				$width,
3171				$height,
3172				'',
3173				'',
3174				false,
3175				true,
3176				true,
3177				$report["datetime"],
3178				'',
3179				true,
3180				0,
3181				true,
3182				$only_image,
3183				ui_get_full_url(false, false, false, false),
3184				$ttl);
3185			break;
3186		case 'data':
3187			break;
3188	}
3189
3190	if ($config['metaconsole']) {
3191		metaconsole_restore_db();
3192	}
3193
3194	return reporting_check_structure_content($return);
3195}
3196
3197function reporting_prediction_date($report, $content) {
3198
3199	global $config;
3200
3201	$return['type'] = 'prediction_date';
3202
3203	if (empty($content['name'])) {
3204		$content['name'] = __('Prediction Date');
3205	}
3206
3207	$return['title'] = $content['name'];
3208	$return["description"] = $content["description"];
3209	$return["date"] = reporting_get_date_text($report, $content);
3210
3211	set_time_limit(500);
3212
3213	$intervals_text = $content['text'];
3214	$max_interval = substr($intervals_text, 0, strpos($intervals_text, ';'));
3215	$min_interval = substr($intervals_text, strpos($intervals_text, ';') + 1);
3216	$value = forecast_prediction_date ($content['id_agent_module'], $content['period'],  $max_interval, $min_interval);
3217
3218	if ($value === false) {
3219		$return["data"]['value'] = __('Unknown');
3220	}
3221	else {
3222		$return["data"]['value'] = date ('d M Y H:i:s', $value);
3223	}
3224
3225	return reporting_check_structure_content($return);
3226}
3227
3228function reporting_projection_graph($report, $content,
3229	$type = 'dinamic', $force_width_chart = null,
3230	$force_height_chart = null) {
3231
3232	global $config;
3233
3234	if ($config['metaconsole']) {
3235		$id_meta = metaconsole_get_id_server($content["server_name"]);
3236
3237
3238		$server = metaconsole_get_connection_by_id ($id_meta);
3239		metaconsole_connect($server);
3240	}
3241
3242	$return['type'] = 'projection_graph';
3243
3244	if (empty($content['name'])) {
3245		$content['name'] = __('Projection Graph');
3246	}
3247
3248	$return['title'] = $content['name'];
3249	$return["description"] = $content["description"];
3250	$return["date"] = reporting_get_date_text($report, $content);
3251
3252
3253
3254	$module_name = io_safe_output(
3255		modules_get_agentmodule_name($content['id_agent_module']));
3256	$agent_name = io_safe_output(
3257		modules_get_agentmodule_agent_name ($content['id_agent_module']));
3258
3259	$return['agent_name'] = $agent_name;
3260	$return['module_name'] = $module_name;
3261
3262
3263
3264	set_time_limit(500);
3265
3266	$output_projection = forecast_projection_graph(
3267		$content['id_agent_module'], $content['period'], $content['top_n_value']);
3268
3269	// If projection doesn't have data then don't draw graph
3270	if ($output_projection ==  NULL) {
3271		$output_projection = false;
3272	}
3273
3274	// Get chart
3275	reporting_set_conf_charts($width, $height, $only_image, $type,
3276		$content, $ttl);
3277
3278	if (!empty($force_width_chart)) {
3279		$width = $force_width_chart;
3280	}
3281
3282	if (!empty($force_height_chart)) {
3283		$height = $force_height_chart;
3284	}
3285
3286	switch ($type) {
3287		case 'dinamic':
3288		case 'static':
3289			$return['chart'] = graphic_combined_module(
3290				array($content['id_agent_module']),
3291				array(),
3292				$content['period'],
3293				$width,
3294				$height,
3295				'Projection%20Sample%20Graph',
3296				'',
3297				0,
3298				0,
3299				0,
3300				0,
3301				$report["datetime"],
3302				$only_image,
3303				ui_get_full_url(false, false, false, false) . '/',
3304				$ttl,
3305				// Important parameter, this tell to graphic_combined_module function that is a projection graph
3306				$output_projection,
3307				$content['top_n_value']
3308				);
3309			break;
3310		case 'data':
3311			$return['data'] = forecast_projection_graph(
3312				$content['id_agent_module'],
3313				$content['period'],
3314				$content['top_n_value'],
3315				false, false, true);
3316			break;
3317	}
3318
3319	if ($config['metaconsole']) {
3320		metaconsole_restore_db();
3321	}
3322
3323	return reporting_check_structure_content($return);
3324}
3325
3326function reporting_agent_configuration($report, $content) {
3327	global $config;
3328
3329	$return['type'] = 'agent_configuration';
3330
3331	if (empty($content['name'])) {
3332		$content['name'] = __('Agent configuration');
3333	}
3334
3335	$return['title'] = $content['name'];
3336	$return["description"] = $content["description"];
3337	$return["date"] = reporting_get_date_text($report, $content);
3338
3339	if ($config['metaconsole']) {
3340		$id_meta = metaconsole_get_id_server($content["server_name"]);
3341
3342
3343		$server = metaconsole_get_connection_by_id ($id_meta);
3344		metaconsole_connect($server);
3345	}
3346
3347	$sql = "
3348		SELECT *
3349		FROM tagente
3350		WHERE id_agente=" . $content['id_agent'];
3351	$agent_data = db_get_row_sql($sql);
3352
3353	$agent_configuration = array();
3354	$agent_configuration['name'] = $agent_data['nombre'];
3355	$agent_configuration['group'] = groups_get_name($agent_data['id_grupo']);
3356	$agent_configuration['group_icon'] =
3357		ui_print_group_icon ($agent_data['id_grupo'], true, '', '', false);
3358	$agent_configuration['os'] = os_get_name($agent_data["id_os"]);
3359	$agent_configuration['os_icon'] = ui_print_os_icon($agent_data["id_os"], true, true);
3360	$agent_configuration['address'] = $agent_data['direccion'];
3361	$agent_configuration['description'] =
3362		strip_tags(ui_bbcode_to_html($agent_data['comentarios']));
3363	$agent_configuration['enabled'] = (int)!$agent_data['disabled'];
3364	$agent_configuration['group'] = $report["group"];
3365
3366	$modules = agents_get_modules ($content['id_agent']);
3367
3368	$agent_configuration['modules'] = array();
3369	//Agent's modules
3370	if (!empty($modules)) {
3371		foreach ($modules as $id_agent_module => $module) {
3372			$sql = "
3373				SELECT *
3374				FROM tagente_modulo
3375				WHERE id_agente_modulo = $id_agent_module";
3376			$module_db = db_get_row_sql($sql);
3377
3378
3379			$data_module = array();
3380			$data_module['name'] = $module_db['nombre'];
3381			if ($module_db['disabled']) {
3382				$data_module['name'] .= " (" . __('Disabled') . ")";
3383			}
3384			$data_module['type_icon'] =
3385				ui_print_moduletype_icon($module_db['id_tipo_modulo'], true);
3386			$data_module['type'] =
3387				modules_get_type_name($module_db['id_tipo_modulo']);
3388			$data_module['max_warning'] =
3389				$module_db['max_warning'];
3390			$data_module['min_warning'] =
3391				$module_db['min_warning'];
3392			$data_module['max_critical'] =
3393				$module_db['max_critical'];
3394			$data_module['min_critical'] =
3395				$module_db['min_critical'];
3396			$data_module['threshold'] = $module_db['module_ff_interval'];
3397			$data_module['description'] = $module_db['descripcion'];
3398			if (($module_db['module_interval'] == 0) ||
3399				($module_db['module_interval'] == '')) {
3400
3401				$data_module['interval'] = db_get_value('intervalo',
3402					'tagente', 'id_agente', $content['id_agent']);
3403			}
3404			else {
3405				$data_module['interval'] = $module_db['module_interval'];
3406			}
3407			$data_module['unit'] = $module_db['unit'];
3408			$module_status = db_get_row(
3409				'tagente_estado', 'id_agente_modulo', $id_agent_module);
3410			modules_get_status($id_agent_module,
3411				$module_status['estado'],
3412				$module_status['datos'], $status, $title);
3413			$data_module['status_icon'] =
3414				ui_print_status_image($status, $title, true);
3415			$data_module['status'] = $title;
3416			$sql_tag = "
3417				SELECT name
3418				FROM ttag
3419				WHERE id_tag IN (
3420					SELECT id_tag
3421					FROM ttag_module
3422					WHERE id_agente_modulo = $id_agent_module)";
3423			$tags = db_get_all_rows_sql($sql_tag);
3424			if ($tags === false)
3425				$data_module['tags'] = array();
3426			else {
3427				foreach ($tags as $tag) {
3428					$data_module['tags'][] = $tag['name'];
3429				}
3430			}
3431
3432			$agent_configuration['modules'][] = $data_module;
3433		}
3434	}
3435
3436	$return['data'] = $agent_configuration;
3437
3438	if ($config['metaconsole']) {
3439		metaconsole_restore_db();
3440	}
3441
3442	return reporting_check_structure_content($return);
3443}
3444
3445function reporting_value($report, $content, $type) {
3446	global $config;
3447
3448	$return = array();
3449	switch ($type) {
3450		case 'max':
3451			$return['type'] = 'max_value';
3452			break;
3453		case 'min':
3454			$return['type'] = 'min_value';
3455			break;
3456		case 'avg':
3457			$return['type'] = 'avg_value';
3458			break;
3459		case 'sum':
3460			$return['type'] = 'sumatory';
3461			break;
3462		case 'MTTR':
3463			$return['type'] = 'MTTR';
3464			break;
3465		case 'MTBF':
3466			$return['type'] = 'MTBF';
3467			break;
3468		case 'TTO':
3469			$return['type'] = 'TTO';
3470			break;
3471		case 'TTRT':
3472			$return['type'] = 'TTRT';
3473			break;
3474	}
3475
3476
3477	if (empty($content['name'])) {
3478		switch ($type) {
3479			case 'max':
3480				$content['name'] = __('Max. Value');
3481				break;
3482			case 'min':
3483				$content['name'] = __('Min. Value');
3484				break;
3485			case 'avg':
3486				$content['name'] = __('AVG. Value');
3487				break;
3488			case 'sum':
3489				$content['name'] = __('Summatory');
3490				break;
3491			case 'MTTR':
3492				$content['name'] = __('MTTR');
3493				break;
3494			case 'MTBF':
3495				$content['name'] = __('MTBF');
3496				break;
3497			case 'TTO':
3498				$content['name'] = __('TTO');
3499				break;
3500			case 'TTRT':
3501				$return['type'] = __('TTRT');
3502				break;
3503		}
3504	}
3505
3506	if ($config['metaconsole']) {
3507		$id_meta = metaconsole_get_id_server($content["server_name"]);
3508
3509
3510		$server = metaconsole_get_connection_by_id ($id_meta);
3511		metaconsole_connect($server);
3512	}
3513
3514	$module_name = io_safe_output(
3515		modules_get_agentmodule_name($content['id_agent_module']));
3516	$agent_name = io_safe_output(
3517		modules_get_agentmodule_agent_name ($content['id_agent_module']));
3518	$unit = db_get_value('unit', 'tagente_modulo', 'id_agente_modulo',
3519		$content ['id_agent_module']);
3520
3521	$return['title'] = $content['name'];
3522	$return['subtitle'] = $agent_name . " - " . $module_name;
3523	$return["description"] = $content["description"];
3524	$return["date"] = reporting_get_date_text($report, $content);
3525
3526	$return['agent_name'] = $agent_name;
3527	$return['module_name'] = $module_name;
3528
3529	switch ($type) {
3530		case 'max':
3531			$value = reporting_get_agentmodule_data_max(
3532				$content['id_agent_module'], $content['period'], $report["datetime"]);
3533			$formated_value = format_for_graph($value, 2) . " " . $unit;
3534			break;
3535		case 'min':
3536			$value = reporting_get_agentmodule_data_min(
3537				$content['id_agent_module'], $content['period'], $report["datetime"]);
3538			$formated_value = format_for_graph($value, 2) . " " . $unit;
3539			break;
3540		case 'avg':
3541			$value = reporting_get_agentmodule_data_average(
3542				$content['id_agent_module'], $content['period'], $report["datetime"]);
3543			$formated_value = format_for_graph($value, 2) . " " . $unit;
3544			break;
3545		case 'sum':
3546			$value = reporting_get_agentmodule_data_sum(
3547				$content['id_agent_module'], $content['period'], $report["datetime"]);
3548			$formated_value = format_for_graph($value, 2) . " " . $unit;
3549			break;
3550		case 'MTTR':
3551			$value = reporting_get_agentmodule_mttr(
3552				$content['id_agent_module'], $content['period'], $report["datetime"]);
3553			$formated_value = null;
3554			break;
3555		case 'MTBF':
3556			$value = reporting_get_agentmodule_mtbf(
3557				$content['id_agent_module'], $content['period'], $report["datetime"]);
3558			$formated_value = null;
3559			break;
3560		case 'TTO':
3561			$value = reporting_get_agentmodule_tto(
3562				$content['id_agent_module'], $content['period'], $report["datetime"]);
3563			if ($value == 0) {
3564				$formated_value = null;
3565			}
3566			else {
3567				$formated_value = human_time_description_raw ($value);
3568			}
3569			break;
3570		case 'TTRT':
3571			$value = reporting_get_agentmodule_ttr(
3572				$content['id_agent_module'], $content['period'], $report["datetime"]);
3573			if ($value == 0) {
3574				$formated_value = null;
3575			}
3576			else {
3577				$formated_value = human_time_description_raw ($value);
3578			}
3579			break;
3580	}
3581
3582	$return['data'] = array(
3583		'value' => $value,
3584		'formated_value' => $formated_value);
3585
3586	if ($config['metaconsole']) {
3587		metaconsole_restore_db();
3588	}
3589
3590	return reporting_check_structure_content($return);
3591}
3592
3593function reporting_url($report, $content, $type = 'dinamic') {
3594	global $config;
3595
3596	$return = array();
3597	$return['type'] = 'url';
3598
3599	if (empty($content['name'])) {
3600		$content['name'] = __('Url');
3601	}
3602
3603	$return['title'] = $content['name'];
3604	$return["description"] = $content["description"];
3605	$return["date"] = reporting_get_date_text();
3606
3607	$return["url"] = $content["external_source"];
3608
3609	switch ($type) {
3610		case 'dinamic':
3611			$return["data"] = null;
3612			break;
3613		case 'data':
3614		case 'static':
3615			$curlObj = curl_init();
3616			curl_setopt($curlObj, CURLOPT_URL, $content['external_source']);
3617			curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
3618			$output = curl_exec($curlObj);
3619			curl_close($curlObj);
3620			$return["data"] = $output;
3621			break;
3622	}
3623
3624	return reporting_check_structure_content($return);
3625}
3626
3627function reporting_text($report, $content) {
3628
3629	global $config;
3630
3631	$return = array();
3632	$return['type'] = 'text';
3633
3634	if (empty($content['name'])) {
3635		$content['name'] = __('Text');
3636	}
3637
3638	$return['title'] = $content['name'];
3639	$return["description"] = $content["description"];
3640	$return["date"] = reporting_get_date_text();
3641
3642	$return["data"] = html_entity_decode($content['text']);
3643
3644	return reporting_check_structure_content($return);
3645}
3646
3647function reporting_sql($report, $content) {
3648
3649	global $config;
3650
3651	$return = array();
3652	$return['type'] = 'sql';
3653
3654	if (empty($content['name'])) {
3655		$content['name'] = __('SQL');
3656	}
3657
3658	$return['title'] = $content['name'];
3659	$return["description"] = $content["description"];
3660	$return["date"] = reporting_get_date_text();
3661
3662	if ($config['metaconsole']) {
3663		$id_meta = metaconsole_get_id_server($content["server_name"]);
3664
3665
3666		$server = metaconsole_get_connection_by_id ($id_meta);
3667		metaconsole_connect($server);
3668	}
3669
3670	if ($content['treport_custom_sql_id'] != 0) {
3671		switch ($config["dbtype"]) {
3672			case "mysql":
3673				$sql = io_safe_output (db_get_value_filter('`sql`', 'treport_custom_sql', array('id' => $content['treport_custom_sql_id'])));
3674				break;
3675			case "postgresql":
3676				$sql = io_safe_output (db_get_value_filter('"sql"', 'treport_custom_sql', array('id' => $content['treport_custom_sql_id'])));
3677				break;
3678			case "oracle":
3679				$sql = io_safe_output (db_get_value_filter('sql', 'treport_custom_sql', array('id' => $content['treport_custom_sql_id'])));
3680				break;
3681		}
3682	}
3683	else {
3684		$sql = io_safe_output ($content['external_source']);
3685	}
3686
3687	// Do a security check on SQL coming from the user
3688	$sql = check_sql ($sql);
3689
3690	$return['sql'] = $sql;
3691	$return['correct'] = 1;
3692	$return['error'] = "";
3693	$return['data'] = array();
3694	if ($sql != '') {
3695		$header = array();
3696		if ($content['header_definition'] != '') {
3697			$header = explode('|', $content['header_definition']);
3698			$return['header'] = $header;
3699		}
3700
3701		$result = db_get_all_rows_sql($sql);
3702		if ($result !== false) {
3703
3704			foreach ($result as $row) {
3705				$data_row = array();
3706
3707				$i = 0;
3708				foreach ($row as $dbkey => $field) {
3709					if (isset($header[$i])) {
3710						$key = $header[$i];
3711					}
3712					else {
3713						$key = $dbkey;
3714					}
3715					$data_row[$key] = $field;
3716
3717					$i++;
3718				}
3719
3720				$return['data'][] = $data_row;
3721			}
3722		}
3723	}
3724	else {
3725		$return['correct'] = 0;
3726		$return['error'] = __('Illegal query: Due security restrictions, there are some tokens or words you cannot use: *, delete, drop, alter, modify, union, password, pass, insert or update.');
3727	}
3728
3729	if ($config['metaconsole']) {
3730		metaconsole_restore_db();
3731	}
3732
3733	return reporting_check_structure_content($return);
3734}
3735
3736function reporting_availability($report, $content) {
3737
3738	global $config;
3739
3740	$return = array();
3741	$return['type'] = 'availability';
3742	$return['subtype'] = $content['group_by_agent'];
3743	$return['resume'] = $content['show_resume'];
3744
3745	if (empty($content['name'])) {
3746		$content['name'] = __('Availability');
3747	}
3748
3749	$return['title'] = $content['name'];
3750	$return["description"] = $content["description"];
3751	$return["date"] = reporting_get_date_text(
3752		$report,
3753		$content);
3754
3755	if ($content['show_graph']) {
3756		$return['kind_availability'] = "address";
3757	}
3758	else {
3759		$return['kind_availability'] = "module";
3760	}
3761
3762
3763	if (empty($content['subitems'])) {
3764		$sql = sprintf("
3765			SELECT id_agent_module,
3766				server_name, operation
3767			FROM treport_content_item
3768			WHERE id_report_content = %d",
3769			$content['id_rc']);
3770
3771		$items = db_process_sql ($sql);
3772	}
3773	else {
3774		$items = $content['subitems'];
3775	}
3776
3777
3778
3779
3780	$data = array();
3781
3782	$avg = 0;
3783	$min = null;
3784	$min_text = "";
3785	$max = null;
3786	$max_text = "";
3787	$count = 0;
3788
3789	if (!empty($items)) {
3790		foreach ($items as $item) {
3791			//aaMetaconsole connection
3792			$server_name = $item ['server_name'];
3793			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
3794				$connection = metaconsole_get_connection($server_name);
3795				if (metaconsole_load_external_db($connection) != NOERR) {
3796					//ui_print_error_message ("Error connecting to ".$server_name);
3797					continue;
3798				}
3799			}
3800
3801
3802
3803			if (modules_is_disable_agent($item['id_agent_module'])
3804				|| modules_is_not_init($item['id_agent_module'])) {
3805				//Restore dbconnection
3806				if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
3807					metaconsole_restore_db();
3808				}
3809
3810				continue;
3811			}
3812
3813			$row = array();
3814
3815			$text = "";
3816
3817			// HACK it is saved in show_graph field.
3818			// Show interfaces instead the modules
3819			if ($content['show_graph']) {
3820				$text = $row['availability_item'] = agents_get_address(
3821					modules_get_agentmodule_agent($item['id_agent_module']));
3822
3823				if (empty($text)) {
3824					$text = $row['availability_item'] = __('No Address');
3825				}
3826			}
3827			else {
3828				$text = $row['availability_item'] = modules_get_agentmodule_name(
3829					$item['id_agent_module']);
3830			}
3831
3832			$row['agent'] = modules_get_agentmodule_agent_name(
3833				$item['id_agent_module']);
3834
3835			$text = $row['agent'] . " (" . $text . ")";
3836
3837			$sla_value = reporting_get_agentmodule_sla(
3838				$item['id_agent_module'],
3839				$content['period'],
3840				0.50,
3841				1.50,
3842				$report["datetime"],
3843				null,
3844				$content['time_from'],
3845				$content['time_to']);
3846
3847			$item['interval_agent_module'] = modules_get_interval ($item['id_agent_module']);
3848			$unknown_seconds = modules_get_unknown_time ($item['id_agent_module'], $report["datetime"], $content['period']);
3849			if ($unknown_seconds !== false) {
3850				$count_checks = (int)(($content['period'] - $unknown_seconds)/$item['interval_agent_module']);
3851			}
3852
3853			if ($sla_value === false) {
3854				$row['checks'] = __('Unknown');
3855				$row['failed'] = __('Unknown');
3856				$row['fail'] = __('Unknown');
3857				$row['poling_time'] = __('Unknown');
3858				$row['time_unavaliable'] = __('Unknown');
3859				$row['ok'] = __('Unknown');
3860				$row['order'] = 0;
3861
3862				$percent_ok = 0;
3863			}
3864			else {
3865				$percent_ok = format_numeric($sla_value, 2);
3866				$percent_fail = (100 - $percent_ok);
3867
3868				$row['checks'] = format_numeric($count_checks, 0);
3869				$row['ok'] = format_numeric($percent_ok,2) . " %";
3870				$row['order'] = $percent_ok;
3871				$row['fail'] = format_numeric($percent_fail,2) . " %";
3872				$row['failed'] =
3873					format_numeric($percent_fail * $count_checks / 100, 0);
3874
3875				$row['poling_time'] = "-";
3876				if ($percent_ok > 0) {
3877				$row['poling_time'] =
3878					human_time_description_raw(
3879						($percent_ok * $count_checks / 100) * modules_get_interval($item['id_agent_module']),
3880					true);
3881				}
3882
3883				$row['time_unavaliable'] = "-";
3884				if ($percent_fail > 0) {
3885					$row['time_unavaliable'] =
3886						human_time_description_raw(
3887							($percent_fail * $count_checks / 100) * modules_get_interval($item['id_agent_module']),
3888						true);
3889				}
3890
3891			}
3892
3893			$data[] = $row;
3894
3895
3896			$avg = (($avg * $count) + $percent_ok) / ($count + 1);
3897			if (is_null($min)) {
3898				$min = $percent_ok;
3899				$min_text = $text;
3900			}
3901			else {
3902				if ($min > $percent_ok) {
3903					$min = $percent_ok;
3904					$min_text = $text;
3905				}
3906			}
3907			if (is_null($max)) {
3908				$max = $percent_ok;
3909				$max_text = $text;
3910			}
3911			else {
3912				if ($max < $percent_ok) {
3913					$max = $percent_ok;
3914					$max_text = $text;
3915				}
3916			}
3917
3918
3919			//Restore dbconnection
3920			if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
3921				metaconsole_restore_db();
3922			}
3923
3924			$count++;
3925		}
3926
3927
3928		switch ($content['order_uptodown']) {
3929			case REPORT_ITEM_ORDER_BY_AGENT_NAME:
3930				$temp = array();
3931				foreach ($data as $row) {
3932					$i = 0;
3933					foreach ($temp as $t_row) {
3934						if (strcmp($row['agent'], $t_row['agent']) < 0) {
3935							break;
3936						}
3937
3938						$i++;
3939					}
3940
3941					array_splice($temp, $i, 0, array($row));
3942				}
3943
3944				$data = $temp;
3945				break;
3946			case REPORT_ITEM_ORDER_BY_ASCENDING:
3947				$temp = array();
3948				foreach ($data as $row) {
3949					$i = 0;
3950					foreach ($temp as $t_row) {
3951						if ($row['order'] < $t_row['order']) {
3952							break;
3953						}
3954
3955						$i++;
3956					}
3957
3958					array_splice($temp, $i, 0, array($row));
3959				}
3960
3961				$data = $temp;
3962				break;
3963			case REPORT_ITEM_ORDER_BY_DESCENDING:
3964				$temp = array();
3965				foreach ($data as $row) {
3966					$i = 0;
3967					foreach ($temp as $t_row) {
3968
3969						if ($row['order'] > $t_row['order']) {
3970							break;
3971						}
3972
3973						$i++;
3974					}
3975
3976					array_splice($temp, $i, 0, array($row));
3977				}
3978
3979				$data = $temp;
3980				break;
3981		}
3982	}
3983
3984	$return["data"] = $data;
3985	$return["resume"] = array();
3986	$return["resume"]['min_text'] = $min_text;
3987	$return["resume"]['min'] = $min;
3988	$return["resume"]['avg'] = $avg;
3989	$return["resume"]['max_text'] = $max_text;
3990	$return["resume"]['max'] = $max;
3991
3992
3993	return reporting_check_structure_content($return);
3994}
3995
3996function reporting_general($report, $content) {
3997
3998	global $config;
3999
4000	$return = array();
4001	$return['type'] = 'general';
4002	$return['subtype'] = $content['group_by_agent'];
4003	$return['resume'] = $content['show_resume'];
4004
4005	if (empty($content['name'])) {
4006		$content['name'] = __('General');
4007	}
4008
4009	$return['title'] = $content['name'];
4010	$return["description"] = $content["description"];
4011	$return["date"] = reporting_get_date_text(
4012		$report,
4013		$content);
4014
4015	$return["data"] = array();
4016	$return["avg_value"] = 0;
4017	$return["min"] = array();
4018	$return["min"]["value"] = null;
4019	$return["min"]["formated_value"] = null;
4020	$return["min"]["agent"] = null;
4021	$return["min"]["module"] = null;
4022	$return["max"] = array();
4023	$return["max"]["value"] = null;
4024	$return["max"]["formated_value"] = null;
4025	$return["max"]["agent"] = null;
4026	$return["max"]["module"] = null;
4027
4028	if (empty($content['subitems'])) {
4029		$generals = db_get_all_rows_filter(
4030			'treport_content_item',
4031			array('id_report_content' => $content['id_rc']));
4032	}
4033	else {
4034		$generals = $content['subitems'];
4035	}
4036
4037
4038	if (empty($generals)) {
4039		$generals = array();
4040	}
4041
4042	$i = 0;
4043	foreach ($generals as $key => $row) {
4044		//Metaconsole connection
4045		$server_name = $row ['server_name'];
4046		if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
4047			$connection = metaconsole_get_connection($server_name);
4048			if (metaconsole_load_external_db($connection) != NOERR) {
4049				//ui_print_error_message ("Error connecting to ".$server_name);
4050				continue;
4051			}
4052		}
4053
4054		if (modules_is_disable_agent($row['id_agent_module']) ||
4055			modules_is_not_init($row['id_agent_module'])) {
4056
4057			if (is_metaconsole()) {
4058				//Restore db connection
4059				metaconsole_restore_db();
4060			}
4061
4062			continue;
4063		}
4064
4065		$mod_name = modules_get_agentmodule_name ($row['id_agent_module']);
4066		$ag_name = modules_get_agentmodule_agent_name ($row['id_agent_module']);
4067		$unit = db_get_value('unit', 'tagente_modulo',
4068			'id_agente_modulo',
4069			$row['id_agent_module']);
4070
4071		if ($content['period'] == 0) {
4072			$data_res[$key] =
4073				modules_get_last_value($row['id_agent_module']);
4074		}
4075		else {
4076			switch ($row['operation']) {
4077				case 'sum':
4078					$data_res[$key] =
4079						reporting_get_agentmodule_data_sum(
4080							$row['id_agent_module'], $content['period'], $report["datetime"]);
4081					break;
4082				case 'max':
4083					$data_res[$key] =
4084						reporting_get_agentmodule_data_max(
4085							$row['id_agent_module'], $content['period']);
4086					break;
4087				case 'min':
4088					$data_res[$key] =
4089						reporting_get_agentmodule_data_min(
4090							$row['id_agent_module'], $content['period']);
4091					break;
4092				case 'avg':
4093				default:
4094					$data_res[$key] =
4095						reporting_get_agentmodule_data_average(
4096							$row['id_agent_module'], $content['period']);
4097					break;
4098			}
4099		}
4100
4101		switch ($content['group_by_agent']) {
4102			case REPORT_GENERAL_NOT_GROUP_BY_AGENT:
4103				$id_agent_module[$key] = $row['id_agent_module'];
4104				$agent_name[$key] = $ag_name;
4105				$module_name[$key] = $mod_name;
4106				$units[$key] = $unit;
4107				$operations[$key] = $row['operation'];
4108				break;
4109			case REPORT_GENERAL_GROUP_BY_AGENT:
4110				if ($data_res[$key] === false) {
4111					$return["data"][$ag_name][$mod_name] = null;
4112				}
4113				else {
4114					if (!is_numeric($data_res[$key])) {
4115						$return["data"][$ag_name][$mod_name] = $data_res[$key];
4116					}
4117					else {
4118						$return["data"][$ag_name][$mod_name] =
4119							format_for_graph($data_res[$key], 2) . " " . $unit;
4120					}
4121				}
4122				break;
4123		}
4124
4125		// Calculate the avg, min and max
4126		if (is_numeric($data_res[$key])) {
4127			$change_min = false;
4128			if (is_null($return["min"]["value"])) {
4129				$change_min = true;
4130			}
4131			else {
4132				if ($return["min"]["value"] > $data_res[$key]) {
4133					$change_min = true;
4134				}
4135			}
4136			if ($change_min) {
4137				$return["min"]["value"] = $data_res[$key];
4138				$return["min"]["formated_value"] =
4139					format_for_graph($data_res[$key], 2) . " " . $unit;
4140				$return["min"]["agent"] = $ag_name;
4141				$return["min"]["module"] = $mod_name;
4142			}
4143
4144			$change_max = false;
4145			if (is_null($return["max"]["value"])) {
4146				$change_max = true;
4147			}
4148			else {
4149				if ($return["max"]["value"] < $data_res[$key]) {
4150					$change_max = true;
4151				}
4152			}
4153
4154			if ($change_max) {
4155				$return["max"]["value"] = $data_res[$key];
4156				$return["max"]["formated_value"] =
4157					format_for_graph($data_res[$key], 2) . " " . $unit;
4158				$return["max"]["agent"] = $ag_name;
4159				$return["max"]["module"] = $mod_name;
4160			}
4161
4162			if ($i == 0) {
4163				$return["avg_value"] = $data_res[$key];
4164			}
4165			else {
4166				$return["avg_value"] =
4167					(($return["avg_value"] * $i) / ($i + 1))
4168					+
4169					($data_res[$key] / ($i + 1));
4170			}
4171		}
4172
4173		$i++;
4174
4175		//Restore dbconnection
4176		if (($config ['metaconsole'] == 1) && $server_name != '' && defined('METACONSOLE')) {
4177			metaconsole_restore_db();
4178		}
4179	}
4180
4181	switch ($content['group_by_agent']) {
4182		case REPORT_GENERAL_NOT_GROUP_BY_AGENT:
4183			switch ($content['order_uptodown']) {
4184				case REPORT_ITEM_ORDER_BY_AGENT_NAME:
4185					array_multisort($agent_name, SORT_ASC,
4186						$data_res, SORT_ASC, $module_name, SORT_ASC,
4187						$id_agent_module, SORT_ASC, $operations,
4188						SORT_ASC);
4189					break;
4190				case REPORT_ITEM_ORDER_BY_ASCENDING:
4191					array_multisort($data_res, SORT_ASC,
4192						$agent_name, SORT_ASC, $module_name,
4193						SORT_ASC, $id_agent_module,
4194						SORT_ASC, $operations, SORT_ASC);
4195					break;
4196				case REPORT_ITEM_ORDER_BY_DESCENDING:
4197					array_multisort($data_res, SORT_DESC,
4198						$agent_name, SORT_ASC, $module_name,
4199						SORT_ASC, $id_agent_module,
4200						SORT_ASC, $operations, SORT_ASC);
4201					break;
4202				case REPORT_ITEM_ORDER_BY_UNSORT:
4203					break;
4204			}
4205
4206
4207
4208			$i = 0;
4209			foreach ($data_res as $d) {
4210				$data = array();
4211				$data['agent'] = $agent_name[$i];
4212				$data['module'] = $module_name[$i];
4213
4214
4215				$data['operator'] = "";
4216				if ($content['period'] != 0) {
4217					switch ($operations[$i]) {
4218						case 'sum':
4219							$data['operator'] = __('Summatory');
4220							break;
4221						case 'min':
4222							$data['operator'] = __('Minimal');
4223							break;
4224						case 'max':
4225							$data['operator'] = __('Maximun');
4226							break;
4227						case 'avg':
4228						default:
4229							$data['operator'] = __('Rate');
4230							break;
4231					}
4232				}
4233
4234				if ($d === false) {
4235					$data['value'] = null;
4236				}
4237				else {
4238
4239					switch ($config["dbtype"]) {
4240						case "mysql":
4241						case "postgresql":
4242							break;
4243						case "oracle":
4244							if (preg_match("/[0-9]+,[0-9]E+[+-][0-9]+/", $d)) {
4245								$d = oracle_format_float_to_php($d);
4246							}
4247							break;
4248					}
4249
4250					if (!is_numeric($d)) {
4251						$data['value'] = $d;
4252					}
4253					else {
4254						$data['value'] = $d;
4255						$data['formated_value'] = format_for_graph($d, 2) . " " .
4256							$units[$i];
4257					}
4258				}
4259				$return["data"][] = $data;
4260
4261				$i++;
4262			}
4263			break;
4264	}
4265
4266	return reporting_check_structure_content($return);
4267}
4268
4269function reporting_custom_graph($report, $content, $type = 'dinamic',
4270	$force_width_chart = null, $force_height_chart = null) {
4271
4272	global $config;
4273
4274	require_once ($config["homedir"] . '/include/functions_graph.php');
4275
4276	if ($config['metaconsole']) {
4277		$id_meta = metaconsole_get_id_server($content["server_name"]);
4278
4279
4280		$server = metaconsole_get_connection_by_id ($id_meta);
4281		metaconsole_connect($server);
4282	}
4283
4284	$graph = db_get_row ("tgraph", "id_graph", $content['id_gs']);
4285
4286	$return = array();
4287	$return['type'] = 'custom_graph';
4288
4289	if (empty($content['name'])) {
4290		$content['name'] = __('Simple graph');
4291	}
4292
4293	$return['title'] = $content['name'];
4294	$return['subtitle'] = $graph['name'];
4295	$return["description"] = $content["description"];
4296	$return["date"] = reporting_get_date_text(
4297		$report,
4298		$content);
4299
4300	$graphs = db_get_all_rows_field_filter ("tgraph_source",
4301		"id_graph", $content['id_gs']);
4302	$modules = array ();
4303	$weights = array ();
4304	if ($graphs === false)
4305		$graphs = array();
4306
4307	foreach ($graphs as $graph_item) {
4308		array_push ($modules, $graph_item['id_agent_module']);
4309		array_push ($weights, $graph_item["weight"]);
4310	}
4311
4312	$return['chart'] = '';
4313	// Get chart
4314	reporting_set_conf_charts($width, $height, $only_image, $type,
4315		$content, $ttl);
4316
4317	$height += count($modules) * REPORTING_CUSTOM_GRAPH_LEGEND_EACH_MODULE_VERTICAL_SIZE;
4318
4319	switch ($type) {
4320		case 'dinamic':
4321		case 'static':
4322			$return['chart'] = graphic_combined_module(
4323				$modules,
4324				$weights,
4325				$content['period'],
4326				$width, $height,
4327				'Combined%20Sample%20Graph',
4328				'',
4329				0,
4330				0,
4331				0,
4332				$graph["stacked"],
4333				$report["datetime"],
4334				$only_image,
4335				ui_get_full_url(false, false, false, false),
4336				$ttl);
4337			break;
4338		case 'data':
4339			break;
4340	}
4341
4342	if ($config['metaconsole']) {
4343		metaconsole_restore_db();
4344	}
4345
4346	return reporting_check_structure_content($return);
4347}
4348
4349function reporting_simple_graph($report, $content, $type = 'dinamic',
4350	$force_width_chart = null, $force_height_chart = null) {
4351
4352	global $config;
4353
4354
4355	if ($config['metaconsole']) {
4356		$id_meta = metaconsole_get_id_server($content["server_name"]);
4357
4358
4359		$server = metaconsole_get_connection_by_id ($id_meta);
4360		metaconsole_connect($server);
4361	}
4362
4363
4364	$return = array();
4365	$return['type'] = 'simple_graph';
4366
4367	if (empty($content['name'])) {
4368		$content['name'] = __('Simple graph');
4369	}
4370
4371
4372
4373	$module_name = io_safe_output(
4374		modules_get_agentmodule_name($content['id_agent_module']));
4375	$agent_name = io_safe_output(
4376		modules_get_agentmodule_agent_name ($content['id_agent_module']));
4377
4378
4379
4380
4381	$return['title'] = $content['name'];
4382	$return['subtitle'] = $agent_name . " - " . $module_name;
4383	$return['agent_name'] = $agent_name;
4384	$return['module_name'] = $module_name;
4385	$return["description"] = $content["description"];
4386	$return["date"] = reporting_get_date_text(
4387		$report,
4388		$content);
4389
4390	$only_avg = true;
4391	// Due to database compatibility problems, the 'only_avg' value
4392	// is stored into the json contained into the 'style' column.
4393	if (isset($style['only_avg'])) {
4394		$only_avg = (bool) $style['only_avg'];
4395	}
4396
4397	$moduletype_name = modules_get_moduletype_name(
4398		modules_get_agentmodule_type(
4399			$content['id_agent_module']));
4400
4401
4402
4403	$return['chart'] = '';
4404	// Get chart
4405	reporting_set_conf_charts($width, $height, $only_image, $type,
4406		$content, $ttl);
4407
4408	if (!empty($force_width_chart)) {
4409		$width = $force_width_chart;
4410	}
4411
4412	if (!empty($force_height_chart)) {
4413		$height = $force_height_chart;
4414	}
4415
4416	switch ($type) {
4417		case 'dinamic':
4418		case 'static':
4419			if (preg_match ("/string/", $moduletype_name)) {
4420
4421				$urlImage = ui_get_full_url(false, false, false, false);
4422
4423				$return['chart'] = grafico_modulo_string(
4424					$content['id_agent_module'],
4425					$content['period'],
4426					false,
4427					$width,
4428					$height,
4429					'',
4430					'',
4431					false,
4432					$only_avg,
4433					false,
4434					$report["datetime"],
4435					$only_image,
4436					$urlImage,
4437					"",
4438					$ttl);
4439
4440			}
4441			else {
4442				// HACK it is saved in show_graph field.
4443				$time_compare_overlapped = false;
4444				if ($content['show_graph']) {
4445					$time_compare_overlapped = 'overlapped';
4446				}
4447
4448				$return['chart'] = grafico_modulo_sparse(
4449					$content['id_agent_module'],
4450					$content['period'],
4451					false,
4452					$width,
4453					$height,
4454					'',
4455					'',
4456					false,
4457					$only_avg,
4458					true,
4459					$report["datetime"],
4460					'',
4461					0,
4462					0,
4463					true,
4464					$only_image,
4465					ui_get_full_url(false, false, false, false),
4466					$ttl,
4467					false,
4468					'',
4469					$time_compare_overlapped,
4470					true);
4471			}
4472			break;
4473		case 'data':
4474			$data = modules_get_agentmodule_data(
4475				$content['id_agent_module'],
4476				$content['period'],
4477				$report["datetime"]);
4478
4479			foreach ($data as $d) {
4480				$return['chart'][$d['utimestamp']] = $d['data'];
4481			}
4482
4483			break;
4484	}
4485
4486	if ($config['metaconsole']) {
4487		metaconsole_restore_db();
4488	}
4489
4490	return reporting_check_structure_content($return);
4491}
4492
4493function reporting_get_date_text($report = null, $content = null) {
4494	global $config;
4495
4496	$return = array();
4497	$return['date'] = null;
4498	$return['period'] = null;
4499	$return['from'] = null;
4500	$return['to'] = null;
4501
4502	if (!empty($report) && !empty($content)) {
4503
4504		if ($content['period'] == 0) {
4505			$es = json_decode($content['external_source'], true);
4506			if ($es['date'] == 0) {
4507				$return['period'] = 0;
4508			}
4509			else {
4510				$return['date'] = $es['date'];
4511			}
4512		}
4513		else {
4514			$return['period'] = $content['period'];
4515			$return['from'] = $report["datetime"] - $content['period'];
4516			$return['to'] = $report["datetime"];
4517		}
4518	}
4519
4520	return $return;
4521}
4522
4523/**
4524 * Check the common items exits
4525 */
4526function reporting_check_structure_report($return) {
4527	if (!isset($return['group_name']))
4528		$return['group_name'] = "";
4529	if (!isset($return['title']))
4530		$return['title'] = "";
4531	if (!isset($return['datetime']))
4532		$return['datetime'] = "";
4533	if (!isset($return['period']))
4534		$return['period'] = "";
4535
4536	return $return;
4537}
4538
4539/**
4540 * Check the common items exits
4541 */
4542function reporting_check_structure_content($report) {
4543	if (!isset($report['title']))
4544		$report['title'] = "";
4545	if (!isset($report['subtitle']))
4546		$report['subtitle'] = "";
4547	if (!isset($report['description']))
4548		$report['description'] = "";
4549	if (!isset($report["date"])) {
4550		$report["date"]['date'] = "";
4551		$report["date"]['period'] = "";
4552		$report["date"]['from'] = "";
4553		$report["date"]['to'] = "";
4554	}
4555
4556	return $report;
4557}
4558
4559function reporting_set_conf_charts(&$width, &$height, &$only_image, $type,
4560	$content, &$ttl) {
4561	switch ($type) {
4562		case 'dinamic':
4563			$only_image = false;
4564			$width = 900;
4565			$height = 230;
4566			$ttl = 1;
4567			break;
4568		case 'static':
4569			$ttl = 2;
4570			$only_image = true;
4571			if ($content['style']['show_in_landscape']) {
4572				$height = 1100;
4573				$width = 1700;
4574			}
4575			else {
4576				$height = 360;
4577				$width = 780;
4578			}
4579			break;
4580		case 'data':
4581			break;
4582	}
4583}
4584
4585
4586
4587
4588
4589
4590
4591
4592////////////////////////////////////////////////////////////////////////
4593////////////////////////////////////////////////////////////////////////
4594////////////////////////////////////////////////////////////////////////
4595// MAYBE MOVE THE NEXT FUNCTIONS TO A FILE NAMED AS FUNCTION_REPORTING.UTILS.PHP //
4596////////////////////////////////////////////////////////////////////////
4597////////////////////////////////////////////////////////////////////////
4598////////////////////////////////////////////////////////////////////////
4599
4600/**
4601 * Gets a detailed reporting of groups's events.
4602 *
4603 * @param unknown_type $id_group Id of the group.
4604 * @param unknown_type $period Time period of the report.
4605 * @param unknown_type $date Date of the report.
4606 * @param unknown_type $return Whether to return or not.
4607 * @param unknown_type $html Whether to return HTML code or not.
4608 *
4609 * @return string Report of groups's events
4610 */
4611function reporting_get_count_events_validated ($filter, $period = 0,
4612	$date = 0,
4613	$filter_event_validated = false, $filter_event_critical = false,
4614	$filter_event_warning = false, $filter_event_no_validated = false,
4615	$filter_event_search = false) {
4616
4617	if (!is_numeric ($date)) {
4618		$date = strtotime ($date);
4619	}
4620	if (empty ($date)) {
4621		$date = get_system_time ();
4622	}
4623
4624	return events_get_count_events_validated($filter, $period, $date,
4625		$filter_event_validated, $filter_event_critical,
4626		$filter_event_warning, $filter_event_no_validated,
4627		$filter_event_search);
4628}
4629
4630/**
4631 * Gets a detailed reporting of groups's events.
4632 *
4633 * @param unknown_type $id_group Id of the group.
4634 * @param unknown_type $period Time period of the report.
4635 * @param unknown_type $date Date of the report.
4636 * @param unknown_type $return Whether to return or not.
4637 * @param unknown_type $html Whether to return HTML code or not.
4638 *
4639 * @return string Report of groups's events
4640 */
4641function reporting_get_count_events_by_criticity ($filter, $period = 0,
4642	$date = 0,
4643	$filter_event_validated = false, $filter_event_critical = false,
4644	$filter_event_warning = false, $filter_event_no_validated = false,
4645	$filter_event_search = false) {
4646
4647	if (!is_numeric ($date)) {
4648		$date = strtotime ($date);
4649	}
4650	if (empty ($date)) {
4651		$date = get_system_time ();
4652	}
4653
4654	return events_get_count_events_by_criticity($filter, $period, $date,
4655		$filter_event_validated, $filter_event_critical,
4656		$filter_event_warning, $filter_event_no_validated,
4657		$filter_event_search);
4658}
4659
4660/**
4661 * Gets a detailed reporting of groups's events.
4662 *
4663 * @param unknown_type $filter.
4664 * @param unknown_type $period Time period of the report.
4665 * @param unknown_type $date Date of the report.
4666 * @param unknown_type $return Whether to return or not.
4667 * @param unknown_type $html Whether to return HTML code or not.
4668 *
4669 * @return string Report of groups's events
4670 */
4671function reporting_get_count_events_validated_by_user ($filter, $period = 0,
4672	$date = 0,
4673	$filter_event_validated = false, $filter_event_critical = false,
4674	$filter_event_warning = false, $filter_event_no_validated = false,
4675	$filter_event_search = false) {
4676
4677	if (!is_numeric ($date)) {
4678		$date = strtotime ($date);
4679	}
4680	if (empty ($date)) {
4681		$date = get_system_time ();
4682	}
4683
4684	return events_get_count_events_validated_by_user($filter, $period, $date,
4685		$filter_event_validated, $filter_event_critical,
4686		$filter_event_warning, $filter_event_no_validated, $filter_event_search);
4687}
4688
4689/**
4690 * Gets a detailed reporting of groups's events.
4691 *
4692 * @param unknown_type $id_group Id of the group.
4693 * @param unknown_type $period Time period of the report.
4694 * @param unknown_type $date Date of the report.
4695 * @param unknown_type $return Whether to return or not.
4696 * @param unknown_type $html Whether to return HTML code or not.
4697 *
4698 * @return string Report of groups's events
4699 */
4700function reporting_get_group_detailed_event ($id_group, $period = 0,
4701	$date = 0, $return = false, $html = true,
4702	$filter_event_validated = false, $filter_event_critical = false,
4703	$filter_event_warning = false, $filter_event_no_validated = false,
4704	$filter_event_filter_search = null, $return_type = false) {
4705
4706	global $config;
4707
4708	if (!is_numeric ($date)) {
4709		$date = strtotime ($date);
4710	}
4711	if (empty ($date)) {
4712		$date = get_system_time ();
4713	}
4714
4715	$table = new stdClass();
4716	$table->width = '99%';
4717
4718	$table->align = array();
4719	$table->align[0] = 'center';
4720	$table->align[2] = 'center';
4721
4722	$table->data = array ();
4723
4724	$table->head = array ();
4725	$table->head[0] = __('Status');
4726	$table->head[1] = __('Name');
4727	$table->head[2] = __('Type');
4728	$table->head[3] = __('Agent');
4729	$table->head[4] = __('Severity');
4730	$table->head[5] = __('Val. by');
4731	$table->head[6] = __('Timestamp');
4732
4733	$events = events_get_group_events($id_group, $period, $date,
4734		$filter_event_validated, $filter_event_critical,
4735		$filter_event_warning, $filter_event_no_validated,
4736		$filter_event_filter_search);
4737
4738	if ($return_type === 'hash') {
4739		return $events;
4740	}
4741
4742	if ($events) {
4743		$note = '';
4744		if (count($events) >= 1000) {
4745			$note .= '* ' . __('Maximum of events shown') . ' (1000)<br>';
4746		}
4747		foreach ($events as $k => $event) {
4748			//First pass along the class of this row
4749			$table->cellclass[$k][1] = $table->cellclass[$k][3] =
4750			$table->cellclass[$k][4] = $table->cellclass[$k][5] =
4751			$table->cellclass[$k][6] =
4752				get_priority_class ($event["criticity"]);
4753
4754			$data = array ();
4755
4756			// Colored box
4757			switch ($event['estado']) {
4758				case 0:
4759					$img_st = "images/star.png";
4760					$title_st = __('New event');
4761					break;
4762				case 1:
4763					$img_st = "images/tick.png";
4764					$title_st = __('Event validated');
4765					break;
4766				case 2:
4767					$img_st = "images/hourglass.png";
4768					$title_st = __('Event in process');
4769					break;
4770			}
4771			$data[] = html_print_image ($img_st, true,
4772				array ("class" => "image_status",
4773					"width" => 16,
4774					"title" => $title_st,
4775					"id" => 'status_img_' . $event["id_evento"]));
4776
4777			$data[] = ui_print_truncate_text(
4778				io_safe_output($event['evento']),
4779				140, false, true);
4780
4781			//$data[1] = $event['event_type'];
4782			$data[] = events_print_type_img ($event["event_type"], true);
4783
4784			if (!empty($event['id_agente']))
4785				$data[] = agents_get_name($event['id_agente']);
4786			else
4787				$data[] = __('Pandora System');
4788			$data[] = get_priority_name ($event['criticity']);
4789			if (empty($event['id_usuario']) && $event['estado'] == EVENT_VALIDATE) {
4790				$data[] = '<i>' . __('System') . '</i>';
4791			}
4792			else {
4793				$user_name = db_get_value ('fullname', 'tusuario', 'id_user', $event['id_usuario']);
4794				$data[] = io_safe_output($user_name);
4795			}
4796			$data[] = '<font style="font-size: 6pt;">' .
4797				date($config['date_format'], $event['timestamp_rep']) .
4798				'</font>';
4799			array_push ($table->data, $data);
4800		}
4801
4802		if ($html) {
4803			return html_print_table ($table, $return) . $note;
4804		}
4805		else {
4806			return $table;
4807		}
4808	}
4809	else {
4810		return false;
4811	}
4812}
4813
4814/**
4815 * Get a detailed report of summarized events per agent
4816 *
4817 * It construct a table object with all the grouped events happened in an agent
4818 * during a period of time.
4819 *
4820 * @param mixed Module id to get the report from.
4821 * @param int Period of time (in seconds) to get the report.
4822 * @param int Beginning date (unixtime) of the report
4823 * @param bool Flag to return or echo the report table (echo by default).
4824 * @param bool Flag to return the html or table object, by default html.
4825 *
4826 * @return mixed A table object (XHTML) or object table is false the html.
4827 */
4828function reporting_get_module_detailed_event ($id_modules, $period = 0,
4829	$date = 0, $return = false, $html = true, $only_data = false) {
4830
4831	global $config;
4832
4833	$id_modules = (array)safe_int ($id_modules, 1);
4834
4835	if (!is_numeric ($date)) {
4836		$date = strtotime ($date);
4837	}
4838	if (empty ($date)) {
4839		$date = get_system_time ();
4840	}
4841
4842
4843	$events = array ();
4844
4845	foreach ($id_modules as $id_module) {
4846		$event = events_get_module ($id_module, (int) $period, (int) $date);
4847		if (!empty ($event)) {
4848			array_push ($events, $event);
4849		}
4850	}
4851
4852	if ($only_data) {
4853		return $event;
4854	}
4855
4856	if ($events) {
4857		$note = '';
4858		if (count($events) >= 1000) {
4859			$note .= '* ' . __('Maximum of events shown') . ' (1000)<br>';
4860		}
4861		foreach ($events as $eventRow) {
4862			foreach ($eventRow as $k => $event) {
4863				//$k = count($table->data);
4864				$table->cellclass[$k][1] = $table->cellclass[$k][2] =
4865				$table->cellclass[$k][3] = $table->cellclass[$k][4] =
4866				$table->cellclass[$k][5] =  get_priority_class ($event["criticity"]);
4867
4868				$data = array ();
4869
4870				// Colored box
4871				switch ($event['estado']) {
4872					case 0:
4873						$img_st = "images/star.png";
4874						$title_st = __('New event');
4875						break;
4876					case 1:
4877						$img_st = "images/tick.png";
4878						$title_st = __('Event validated');
4879						break;
4880					case 2:
4881						$img_st = "images/hourglass.png";
4882						$title_st = __('Event in process');
4883						break;
4884				}
4885				$data[0] = html_print_image ($img_st, true,
4886					array ("class" => "image_status",
4887						"width" => 16,
4888						"title" => $title_st,
4889						"id" => 'status_img_' . $event["id_evento"]));
4890
4891				$data[1] = io_safe_output($event['evento']);
4892				$data[2] = $event['event_type'];
4893				$data[3] = get_priority_name ($event['criticity']);
4894				$data[4] = $event['event_rep'];
4895				$data[5] = date($config['date_format'], $event['timestamp_rep']);
4896				array_push ($table->data, $data);
4897			}
4898		}
4899
4900		if ($html) {
4901			return html_print_table ($table, $return) . $note;
4902		}
4903		else {
4904			return $table;
4905		}
4906	}
4907	else {
4908		return false;
4909	}
4910}
4911
4912
4913/**
4914 * Get a detailed report of summarized events per agent
4915 *
4916 * It construct a table object with all the grouped events happened in an agent
4917 * during a period of time.
4918 *
4919 * @param mixed Agent id(s) to get the report from.
4920 * @param int Period of time (in seconds) to get the report.
4921 * @param int Beginning date (unixtime) of the report
4922 * @param bool Flag to return or echo the report table (echo by default).
4923 *
4924 * @return A table object (XHTML)
4925 */
4926function reporting_get_agents_detailed_event ($id_agents, $period = 0,
4927	$date = 0, $return = false, $filter_event_validated = false,
4928	$filter_event_critical = false, $filter_event_warning = false,
4929	$filter_event_no_validated = false, $only_data = false) {
4930
4931	global $config;
4932
4933	if ($only_data) {
4934		$return_data = array();
4935	}
4936
4937	$id_agents = (array)safe_int ($id_agents, 1);
4938
4939	if (!is_numeric ($date)) {
4940		$date = strtotime ($date);
4941	}
4942	if (empty ($date)) {
4943		$date = get_system_time ();
4944	}
4945
4946
4947
4948	$events = array ();
4949
4950	foreach ($id_agents as $id_agent) {
4951		$event = events_get_agent ($id_agent,
4952			(int)$period,
4953			(int)$date,
4954			$filter_event_validated, $filter_event_critical,
4955			$filter_event_warning, $filter_event_no_validated);
4956
4957		if (empty($event)) {
4958			$event = array();
4959		}
4960
4961		if ($only_data) {
4962			foreach ($event as $e) {
4963				$return_data[] = array(
4964					'status' => $e['estado'],
4965					'count' => $e['event_rep'],
4966					'name' => $e['evento'],
4967					'type' => $e["event_type"],
4968					'criticity' => $e["criticity"],
4969					'validated_by' => $e['id_usuario'],
4970					'timestamp' => $e['timestamp_rep']
4971				);
4972			}
4973		}
4974		else {
4975			if (!empty ($event)) {
4976				array_push ($events, $event);
4977			}
4978		}
4979	}
4980
4981	if ($only_data) {
4982		return $return_data;
4983	}
4984
4985	if ($events) {
4986		$note = '';
4987		if (count($events) >= 1000) {
4988			$note .= '* ' . __('Maximum of events shown') . ' (1000)<br>';
4989		}
4990		foreach ($events as $eventRow) {
4991			foreach ($eventRow as $k => $event) {
4992				//First pass along the class of this row
4993				$table->cellclass[$k][1] = $table->cellclass[$k][2] =
4994				$table->cellclass[$k][4] = $table->cellclass[$k][5] =
4995				$table->cellclass[$k][6] =
4996					get_priority_class ($event["criticity"]);
4997
4998				$data = array ();
4999				// Colored box
5000				switch ($event['estado']) {
5001					case 0:
5002						$img_st = "images/star.png";
5003						$title_st = __('New event');
5004						break;
5005					case 1:
5006						$img_st = "images/tick.png";
5007						$title_st = __('Event validated');
5008						break;
5009					case 2:
5010						$img_st = "images/hourglass.png";
5011						$title_st = __('Event in process');
5012						break;
5013				}
5014				$data[] = html_print_image ($img_st, true,
5015					array ("class" => "image_status",
5016						"width" => 16,
5017						"title" => $title_st));
5018
5019				$data[] = $event['event_rep'];
5020
5021				$data[] = ui_print_truncate_text(
5022					io_safe_output($event['evento']),
5023					140, false, true);
5024				//$data[] = $event['event_type'];
5025				$data[] = events_print_type_img ($event["event_type"], true);
5026
5027				$data[] = get_priority_name ($event['criticity']);
5028				if (empty($event['id_usuario']) && $event['estado'] == EVENT_VALIDATE) {
5029					$data[] = '<i>' . __('System') . '</i>';
5030				}
5031				else {
5032					$user_name = db_get_value ('fullname', 'tusuario', 'id_user', $event['id_usuario']);
5033					$data[] = io_safe_output($user_name);
5034				}
5035				$data[] = '<font style="font-size: 6pt;">' .
5036					date($config['date_format'], $event['timestamp_rep']) . '</font>';
5037				array_push ($table->data, $data);
5038			}
5039		}
5040	}
5041
5042	if ($events)
5043		return html_print_table ($table, $return) . $note;
5044}
5045
5046/**
5047 * Get general statistical info on a group
5048 *
5049 * @param int Group Id to get info from. 0 = all
5050 *
5051 * @return array Group statistics
5052 */
5053function reporting_get_group_stats ($id_group = 0, $access = 'AR') {
5054	global $config;
5055
5056	$data = array ();
5057	$data["monitor_checks"] = 0;
5058	$data["monitor_not_init"] = 0;
5059	$data["monitor_unknown"] = 0;
5060	$data["monitor_ok"] = 0;
5061	$data["monitor_bad"] = 0; // Critical + Unknown + Warning
5062	$data["monitor_warning"] = 0;
5063	$data["monitor_critical"] = 0;
5064	$data["monitor_not_normal"] = 0;
5065	$data["monitor_alerts"] = 0;
5066	$data["monitor_alerts_fired"] = 0;
5067	$data["monitor_alerts_fire_count"] = 0;
5068	$data["total_agents"] = 0;
5069	$data["total_alerts"] = 0;
5070	$data["total_checks"] = 0;
5071	$data["alerts"] = 0;
5072	$data["agents_unknown"] = 0;
5073	$data["monitor_health"] = 100;
5074	$data["alert_level"] = 100;
5075	$data["module_sanity"] = 100;
5076	$data["server_sanity"] = 100;
5077	$data["total_not_init"] = 0;
5078	$data["monitor_non_init"] = 0;
5079	$data["agent_ok"] = 0;
5080	$data["agent_warning"] = 0;
5081	$data["agent_critical"] = 0;
5082	$data["agent_unknown"] = 0;
5083	$data["agent_not_init"] = 0;
5084
5085	$cur_time = get_system_time ();
5086
5087	//Check for access credentials using check_acl. More overhead, much safer
5088	if (!check_acl ($config["id_user"], $id_group, $access)) {
5089		return $data;
5090	}
5091
5092	if ($id_group == 0) {
5093		$id_group = array_keys(
5094			users_get_groups($config['id_user'], $access, false));
5095	}
5096
5097	// -----------------------------------------------------------------
5098	// Server processed stats. NOT realtime (taken from tgroup_stat)
5099	// -----------------------------------------------------------------
5100	if ($config["realtimestats"] == 0) {
5101
5102		if (!is_array($id_group)) {
5103			$my_group = $id_group;
5104			$id_group = array();
5105			$id_group[0] = $my_group;
5106		}
5107
5108		foreach ($id_group as $group) {
5109			$group_stat = db_get_all_rows_sql ("SELECT *
5110				FROM tgroup_stat, tgrupo
5111				WHERE tgrupo.id_grupo = tgroup_stat.id_group
5112					AND tgroup_stat.id_group = $group
5113				ORDER BY nombre");
5114
5115			$data["monitor_checks"] += $group_stat[0]["modules"];
5116			$data["agent_not_init"] += $group_stat[0]["non-init"];
5117			$data["agent_unknown"] += $group_stat[0]["unknown"];
5118			$data["agent_ok"] += $group_stat[0]["normal"];
5119			$data["agent_warning"] += $group_stat[0]["warning"];
5120			$data["agent_critical"] += $group_stat[0]["critical"];
5121			$data["monitor_alerts"] += $group_stat[0]["alerts"];
5122			$data["monitor_alerts_fired"] += $group_stat[0]["alerts_fired"];
5123			$data["monitor_alerts_fire_count"] += $group_stat[0]["alerts_fired"];
5124			$data["total_checks"] += $group_stat[0]["modules"];
5125			$data["total_alerts"] += $group_stat[0]["alerts"];
5126			$data["total_agents"] += $group_stat[0]["agents"];
5127			$data["agents_unknown"] += $group_stat[0]["agents_unknown"];
5128			$data["utimestamp"] = $group_stat[0]["utimestamp"];
5129
5130			// This fields are not in database
5131			$data["monitor_ok"] += (int) groups_get_normal_monitors($group);
5132			$data["monitor_warning"] += (int) groups_get_warning_monitors($group);
5133			$data["monitor_critical"] += (int) groups_get_critical_monitors($group);
5134			$data["monitor_unknown"] += (int) groups_get_unknown_monitors($group);
5135			$data["monitor_not_init"] += (int) groups_get_not_init_monitors($group);
5136		}
5137
5138	// -------------------------------------------------------------------
5139	// Realtime stats, done by PHP Console
5140	// -------------------------------------------------------------------
5141	}
5142	else {
5143
5144		if (!is_array($id_group)) {
5145			$my_group = $id_group;
5146			$id_group = array();
5147			$id_group[0] = $my_group;
5148		}
5149
5150		// Store the groups where we are quering
5151		$covered_groups = array();
5152		$group_array = array();
5153		foreach ($id_group as $group) {
5154			$children = groups_get_childrens($group);
5155
5156			//Show empty groups only if they have children with agents
5157			//$group_array = array();
5158
5159			foreach ($children as $sub) {
5160				// If the group is quering previously, we ingore it
5161				if (!in_array($sub['id_grupo'],$covered_groups)) {
5162					array_push($covered_groups, $sub['id_grupo']);
5163					array_push($group_array, $sub['id_grupo']);
5164				}
5165
5166			}
5167
5168			// Add id of this group to create the clause
5169			// If the group is quering previously, we ingore it
5170			if (!in_array($group,$covered_groups)) {
5171				array_push($covered_groups, $group);
5172				array_push($group_array, $group);
5173			}
5174
5175			// If there are not groups to query, we jump to nextone
5176
5177			if (empty($group_array)) {
5178				continue;
5179			}
5180		}
5181
5182		if (!empty($group_array)) {
5183			// FOR THE FUTURE: Split the groups into groups with tags restrictions and groups without it
5184			// To calculate in the light way the non tag restricted and in the heavy way the others
5185			/*
5186			$group_restricted_data = tags_get_acl_tags($config['id_user'], $group_array, $access, 'data');
5187			$tags_restricted_groups = array_keys($group_restricted_data);
5188
5189			$no_tags_restricted_groups = $group_array;
5190			foreach ($no_tags_restricted_groups as $k => $v) {
5191				if (in_array($v, $tags_restricted_groups)) {
5192					unset($no_tags_restricted_groups[$k]);
5193				}
5194			}
5195			*/
5196
5197			if (!empty($group_array)) {
5198				// Get monitor NOT INIT, except disabled AND async modules
5199				$data["monitor_not_init"] += (int) groups_get_not_init_monitors ($group_array, array(), array(), false, false, true);
5200
5201				// Get monitor OK, except disabled and non-init
5202				$data["monitor_ok"] += (int) groups_get_normal_monitors ($group_array, array(), array(), false, false, true);
5203
5204				// Get monitor CRITICAL, except disabled and non-init
5205				$data["monitor_critical"] += (int) groups_get_critical_monitors ($group_array, array(), array(), false, false, true);
5206
5207				// Get monitor WARNING, except disabled and non-init
5208				$data["monitor_warning"] += (int) groups_get_warning_monitors ($group_array, array(), array(), false, false, true);
5209
5210				// Get monitor UNKNOWN, except disabled and non-init
5211				$data["monitor_unknown"] += (int) groups_get_unknown_monitors ($group_array, array(), array(), false, false, true);
5212
5213				// Get alerts configured, except disabled
5214				$data["monitor_alerts"] += groups_monitor_alerts ($group_array) ;
5215
5216				// Get alert configured currently FIRED, except disabled
5217				$data["monitor_alerts_fired"] += groups_monitor_fired_alerts ($group_array);
5218
5219				// Calculate totals using partial counts from above
5220
5221				// Get TOTAL non-init modules, except disabled ones and async modules
5222				$data["total_not_init"] += $data["monitor_not_init"];
5223
5224				// Get TOTAL agents in a group
5225				$data["total_agents"] += (int) groups_get_total_agents ($group_array, array(), array(), false, false, true);
5226
5227				// Get Agents OK
5228				$data["agent_ok"] += (int) groups_get_normal_agents ($group_array, array(), array(), false, false, true);
5229
5230				// Get Agents Warning
5231				$data["agent_warning"] += (int) groups_get_warning_agents ($group_array, array(), array(), false, false, true);
5232
5233				// Get Agents Critical
5234				$data["agent_critical"] += (int) groups_get_critical_agents ($group_array, array(), array(), false, false, true);
5235
5236				// Get Agents Unknown
5237				$data["agent_unknown"] += (int) groups_get_unknown_agents ($group_array, array(), array(), false, false, true);
5238
5239				// Get Agents Not init
5240				$data["agent_not_init"] += (int) groups_get_not_init_agents ($group_array, array(), array(), false, false, true);
5241			}
5242
5243			// Get total count of monitors for this group, except disabled.
5244			$data["monitor_checks"] = $data["monitor_not_init"] + $data["monitor_unknown"] + $data["monitor_warning"] + $data["monitor_critical"] + $data["monitor_ok"];
5245
5246			// Calculate not_normal monitors
5247			$data["monitor_not_normal"] += $data["monitor_checks"] - $data["monitor_ok"];
5248		}
5249
5250		// Get total count of monitors for this group, except disabled.
5251
5252		$data["monitor_checks"] = $data["monitor_not_init"] + $data["monitor_unknown"] + $data["monitor_warning"] + $data["monitor_critical"] + $data["monitor_ok"];
5253
5254		/*
5255		 Monitor health (percentage)
5256		 Data health (percentage)
5257		 Global health (percentage)
5258		 Module sanity (percentage)
5259		 Alert level (percentage)
5260
5261		 Server Sanity	0% Uninitialized modules
5262
5263		 */
5264	}
5265
5266	if ($data["monitor_unknown"] > 0 && $data["monitor_checks"] > 0) {
5267		$data["monitor_health"] = format_numeric (100 - ($data["monitor_not_normal"] / ($data["monitor_checks"] / 100)), 1);
5268	}
5269	else {
5270		$data["monitor_health"] = 100;
5271	}
5272
5273	if ($data["monitor_not_init"] > 0 && $data["monitor_checks"] > 0) {
5274		$data["module_sanity"] = format_numeric (100 - ($data["monitor_not_init"] / ($data["monitor_checks"] / 100)), 1);
5275	}
5276	else {
5277		$data["module_sanity"] = 100;
5278	}
5279
5280	if (isset($data["alerts"])) {
5281		if ($data["monitor_alerts_fired"] > 0 && $data["alerts"] > 0) {
5282			$data["alert_level"] = format_numeric (100 - ($data	["monitor_alerts_fired"] / ($data["alerts"] / 100)), 1);
5283		}
5284		else {
5285			$data["alert_level"] = 100;
5286		}
5287	}
5288	else {
5289		$data["alert_level"] = 100;
5290		$data["alerts"] = 0;
5291	}
5292
5293	$data["monitor_bad"] = $data["monitor_critical"] + $data["monitor_warning"];
5294
5295	if ($data["monitor_bad"] > 0 && $data["monitor_checks"] > 0) {
5296		$data["global_health"] = format_numeric (100 - ($data["monitor_bad"] / ($data["monitor_checks"] / 100)), 1);
5297	}
5298	else {
5299		$data["global_health"] = 100;
5300	}
5301
5302	$data["server_sanity"] = format_numeric (100 - $data["module_sanity"], 1);
5303
5304
5305	$data['alert_fired'] = 0;
5306	if ($data["monitor_alerts_fired"] > 0) {
5307		$data['alert_fired'] = 1;
5308	}
5309
5310
5311	if ($data["monitor_critical"] > 0) {
5312		$data['status'] = 'critical';
5313	}
5314	elseif ($data["monitor_warning"] > 0) {
5315		$data['status'] = 'warning';
5316	}
5317	elseif (($data["monitor_unknown"] > 0) ||  ($data["agents_unknown"] > 0)) {
5318		$data['status'] = 'unknown';
5319	}
5320	elseif ($data["monitor_ok"] > 0)  {
5321		$data['status'] = 'ok';
5322	}
5323	elseif ($data["agent_not_init"] > 0)  {
5324		$data['status'] = 'not_init';
5325	}
5326	else {
5327		$data['status'] = 'none';
5328	}
5329
5330	return ($data);
5331}
5332
5333function reporting_get_stats_indicators($data, $width = 280, $height = 20, $html = true) {
5334	$table_ind = html_get_predefined_table();
5335
5336	$servers = array();
5337	$servers["all"] = (int) db_get_value ('COUNT(id_server)','tserver');
5338	$servers["up"] = (int) servers_check_status ();
5339	$servers["down"] = $servers["all"] - $servers["up"];
5340	if ($servers["all"] == 0) {
5341		$servers["health"] = 0;
5342	}
5343	else {
5344		$servers["health"] = $servers["up"] / ($servers["all"] / 100);
5345	}
5346
5347	if ($html) {
5348		$tdata[0] = '<fieldset class="databox tactical_set">
5349						<legend>' .
5350							__('Server health') . ui_print_help_tip (sprintf(__('%d Downed servers'), $servers["down"]), true) .
5351						'</legend>' .
5352						progress_bar($servers["health"], $width, $height, '', 0) . '</fieldset>';
5353		$table_ind->rowclass[] = '';
5354		$table_ind->data[] = $tdata;
5355
5356		$tdata[0] = '<fieldset class="databox tactical_set">
5357						<legend>' .
5358							__('Monitor health') . ui_print_help_tip (sprintf(__('%d Not Normal monitors'), $data["monitor_not_normal"]), true) .
5359						'</legend>' .
5360						progress_bar($data["monitor_health"], $width, $height, $data["monitor_health"].'% '.__('of monitors up'), 0) . '</fieldset>';
5361		$table_ind->rowclass[] = '';
5362		$table_ind->data[] = $tdata;
5363
5364		$tdata[0] = '<fieldset class="databox tactical_set">
5365						<legend>' .
5366							__('Module sanity') . ui_print_help_tip (sprintf(__('%d Not inited monitors'), $data["monitor_not_init"]), true) .
5367						'</legend>' .
5368						progress_bar($data["module_sanity"], $width, $height, $data["module_sanity"].'% '.__('of total modules inited'), 0) . '</fieldset>';
5369		$table_ind->rowclass[] = '';
5370		$table_ind->data[] = $tdata;
5371
5372		$tdata[0] = '<fieldset class="databox tactical_set">
5373						<legend>' .
5374							__('Alert level') . ui_print_help_tip (sprintf(__('%d Fired alerts'), $data["monitor_alerts_fired"]), true) .
5375						'</legend>' .
5376						progress_bar($data["alert_level"], $width, $height, $data["alert_level"].'% '.__('of defined alerts not fired'), 0) . '</fieldset>';
5377		$table_ind->rowclass[] = '';
5378		$table_ind->data[] = $tdata;
5379
5380
5381		return html_print_table($table_ind, true);
5382	}
5383	else {
5384		$return = array();
5385
5386		$return['server_health'] = array(
5387			'title' => __('Server health'),
5388			'graph' => progress_bar($servers["health"], $width, $height, '', 0));
5389		$return['monitor_health'] = array(
5390			'title' => __('Monitor health'),
5391			'graph' => progress_bar($data["monitor_health"], $width, $height, $data["monitor_health"].'% '.__('of monitors up'), 0));
5392		$return['module_sanity'] = array(
5393			'title' => __('Module sanity'),
5394			'graph' => progress_bar($data["module_sanity"], $width, $height, $data["module_sanity"].'% '.__('of total modules inited'), 0));
5395		$return['alert_level'] = array(
5396			'title' => __('Alert level'),
5397			'graph' => progress_bar($data["alert_level"], $width, $height, $data["alert_level"].'% '.__('of defined alerts not fired'), 0));
5398
5399		return $return;
5400	}
5401}
5402
5403function reporting_get_stats_alerts($data, $links = false) {
5404	global $config;
5405
5406	// Link URLS
5407	$mobile = false;
5408	if (isset($data['mobile'])) {
5409		if ($data['mobile']) {
5410			$mobile = true;
5411		}
5412	}
5413
5414	if ($mobile) {
5415		$urls = array();
5416		$urls['monitor_alerts'] = "index.php?page=alerts&status=all_enabled";
5417		$urls['monitor_alerts_fired'] = "index.php?page=alerts&status=fired";
5418	}
5419	else {
5420		$urls = array();
5421		if ($links) {
5422			$urls['monitor_alerts'] = "index.php?sec=estado&sec2=operation/agentes/alerts_status&pure=" . $config['pure'];
5423			$urls['monitor_alerts_fired'] = "index.php?sec=estado&sec2=operation/agentes/alerts_status&filter=fired&pure=" . $config['pure'];
5424		} else {
5425			$urls['monitor_alerts'] = "index.php?sec=estado&amp;sec2=operation/agentes/alerts_status&amp;refr=60";
5426			$urls['monitor_alerts_fired'] = "index.php?sec=estado&amp;sec2=operation/agentes/alerts_status&amp;refr=60&filter=fired";
5427		}
5428	}
5429
5430	// Alerts table
5431	$table_al = html_get_predefined_table();
5432
5433	$tdata = array();
5434	$tdata[0] = html_print_image('images/bell.png', true, array('title' => __('Defined alerts')));
5435	$tdata[1] = $data["monitor_alerts"] <= 0 ? '-' : $data["monitor_alerts"];
5436	$tdata[1] = '<a class="big_data" href="' . $urls["monitor_alerts"] . '">' . $tdata[1] . '</a>';
5437
5438	$tdata[2] = html_print_image('images/bell_error.png', true, array('title' => __('Fired alerts')));
5439	$tdata[3] = $data["monitor_alerts_fired"] <= 0 ? '-' : $data["monitor_alerts_fired"];
5440	$tdata[3] = '<a style="color: ' . COL_ALERTFIRED . ';" class="big_data" href="' . $urls["monitor_alerts_fired"] . '">' . $tdata[3] . '</a>';
5441	$table_al->rowclass[] = '';
5442	$table_al->data[] = $tdata;
5443
5444	if (!defined('METACONSOLE')) {
5445		$output = '<fieldset class="databox tactical_set">
5446					<legend>' .
5447						__('Defined and fired alerts') .
5448					'</legend>' .
5449					html_print_table($table_al, true) . '</fieldset>';
5450	}
5451	else {
5452		// Remove the defined alerts cause with the new cache table is difficult to retrieve them
5453		unset($table_al->data[0][0], $table_al->data[0][1]);
5454
5455		$table_al->class = "tactical_view";
5456		$table_al->style = array();
5457		$output = '<fieldset class="tactical_set">
5458					<legend>' .
5459						__('Fired alerts') .
5460					'</legend>' .
5461					html_print_table($table_al, true) . '</fieldset>';
5462	}
5463	return $output;
5464}
5465
5466
5467function reporting_get_stats_modules_status($data, $graph_width = 250, $graph_height = 150, $links = false, $data_agents=false) {
5468	global $config;
5469
5470	// Link URLS
5471	if ($links === false) {
5472		$urls = array();
5473		$urls['monitor_critical'] = "index.php?" .
5474			"sec=estado&amp;sec2=operation/agentes/status_monitor&amp;" .
5475			"refr=60&amp;status=" . AGENT_MODULE_STATUS_CRITICAL_BAD . "&pure=" . $config['pure'];
5476		$urls['monitor_warning'] = "index.php?" .
5477			"sec=estado&amp;sec2=operation/agentes/status_monitor&amp;" .
5478			"refr=60&amp;status=" . AGENT_MODULE_STATUS_WARNING . "&pure=" . $config['pure'];
5479		$urls['monitor_ok'] = "index.php?" .
5480			"sec=estado&amp;sec2=operation/agentes/status_monitor&amp;" .
5481			"refr=60&amp;status=" . AGENT_MODULE_STATUS_NORMAL . "&pure=" . $config['pure'];
5482		$urls['monitor_unknown'] = "index.php?" .
5483			"sec=estado&amp;sec2=operation/agentes/status_monitor&amp;" .
5484			"refr=60&amp;status=" . AGENT_MODULE_STATUS_UNKNOWN . "&pure=" . $config['pure'];
5485		$urls['monitor_not_init'] = "index.php?" .
5486			"sec=estado&amp;sec2=operation/agentes/status_monitor&amp;" .
5487			"refr=60&amp;status=" . AGENT_MODULE_STATUS_NOT_INIT . "&pure=" . $config['pure'];
5488	}
5489	else {
5490		$urls = array();
5491		$urls['monitor_critical'] = $links['monitor_critical'];
5492		$urls['monitor_warning'] = $links['monitor_warning'];
5493		$urls['monitor_ok'] = $links['monitor_ok'];
5494		$urls['monitor_unknown'] = $links['monitor_unknown'];
5495		$urls['monitor_not_init'] = $links['monitor_not_init'];
5496	}
5497
5498	// Modules by status table
5499	$table_mbs = html_get_predefined_table();
5500
5501	$tdata = array();
5502	$tdata[0] = html_print_image('images/module_critical.png', true, array('title' => __('Monitor critical')));
5503	$tdata[1] = $data["monitor_critical"] <= 0 ? '-' : $data["monitor_critical"];
5504	$tdata[1] = '<a style="color: ' . COL_CRITICAL . ';" class="big_data" href="' . $urls['monitor_critical'] . '">' . $tdata[1] . '</a>';
5505
5506	$tdata[2] = html_print_image('images/module_warning.png', true, array('title' => __('Monitor warning')));
5507	$tdata[3] = $data["monitor_warning"] <= 0 ? '-' : $data["monitor_warning"];
5508	$tdata[3] = '<a style="color: ' . COL_WARNING_DARK . ';" class="big_data" href="' . $urls['monitor_warning'] . '">' . $tdata[3] . '</a>';
5509	$table_mbs->rowclass[] = '';
5510	$table_mbs->data[] = $tdata;
5511
5512	$tdata = array();
5513	$tdata[0] = html_print_image('images/module_ok.png', true, array('title' => __('Monitor normal')));
5514	$tdata[1] = $data["monitor_ok"] <= 0 ? '-' : $data["monitor_ok"];
5515	$tdata[1] = '<a style="color: ' . COL_NORMAL . ';" class="big_data" href="' . $urls["monitor_ok"] . '">' . $tdata[1] . '</a>';
5516
5517	$tdata[2] = html_print_image('images/module_unknown.png', true, array('title' => __('Monitor unknown')));
5518	$tdata[3] = $data["monitor_unknown"] <= 0 ? '-' : $data["monitor_unknown"];
5519	$tdata[3] = '<a style="color: ' . COL_UNKNOWN . ';" class="big_data" href="' . $urls["monitor_unknown"] . '">' . $tdata[3] . '</a>';
5520	$table_mbs->rowclass[] = '';
5521	$table_mbs->data[] = $tdata;
5522
5523	$tdata = array();
5524	$tdata[0] = html_print_image('images/module_notinit.png', true, array('title' => __('Monitor not init')));
5525	$tdata[1] = $data["monitor_not_init"] <= 0 ? '-' : $data["monitor_not_init"];
5526	$tdata[1] = '<a style="color: ' . COL_NOTINIT . ';" class="big_data" href="' . $urls["monitor_not_init"] . '">' . $tdata[1] . '</a>';
5527
5528	$tdata[2] = $tdata[3] = '';
5529	$table_mbs->rowclass[] = '';
5530	$table_mbs->data[] = $tdata;
5531
5532	if ($data["monitor_checks"] > 0) {
5533		$tdata = array();
5534		$table_mbs->colspan[count($table_mbs->data)][0] = 4;
5535		$table_mbs->cellstyle[count($table_mbs->data)][0] = 'text-align: center;';
5536		$tdata[0] = '<div id="outter_status_pie" style="height: ' . $graph_height . 'px">' .
5537			'<div id="status_pie" style="margin: auto; width: ' . $graph_width . 'px;">' .
5538				graph_agent_status(false, $graph_width, $graph_height, true, true, $data_agents) .
5539			'</div></div>';
5540		$table_mbs->rowclass[] = '';
5541		$table_mbs->data[] = $tdata;
5542	}
5543
5544	if(!defined("METACONSOLE")) {
5545		$output = '
5546			<fieldset class="databox tactical_set">
5547				<legend>' .
5548					__('Monitors by status') .
5549				'</legend>' .
5550				html_print_table($table_mbs, true) .
5551			'</fieldset>';
5552	}
5553	else {
5554		$table_mbs->class = "tactical_view";
5555		$table_mbs->style=array();
5556		$output = '
5557			<fieldset class="tactical_set">
5558				<legend>' .
5559					__('Monitors by status') .
5560				'</legend>' .
5561				html_print_table($table_mbs, true) .
5562			'</fieldset>';
5563	}
5564	return $output;
5565}
5566
5567function reporting_get_stats_agents_monitors($data) {
5568	global $config;
5569
5570	// Link URLS
5571	$mobile = false;
5572	if (isset($data['mobile'])) {
5573		if ($data['mobile']) {
5574			$mobile = true;
5575		}
5576	}
5577
5578	if ($mobile) {
5579		$urls = array();
5580		$urls['total_agents'] = "index.php?page=agents";
5581		$urls['monitor_checks'] = "index.php?page=modules";
5582	}
5583	else {
5584		$urls = array();
5585		$urls['total_agents'] = "index.php?sec=estado&amp;sec2=operation/agentes/estado_agente&amp;refr=60";
5586		$urls['monitor_checks'] = "index.php?sec=estado&amp;sec2=operation/agentes/status_monitor&amp;refr=60&amp;status=-1";
5587	}
5588
5589	// Agents and modules table
5590	$table_am = html_get_predefined_table();
5591
5592	$tdata = array();
5593	$tdata[0] = html_print_image('images/agent.png', true, array('title' => __('Total agents')));
5594	$tdata[1] = $data["total_agents"] <= 0 ? '-' : $data["total_agents"];
5595	$tdata[1] = '<a class="big_data" href="' . $urls['total_agents'] . '">' . $tdata[1] . '</a>';
5596
5597	$tdata[2] = html_print_image('images/module.png', true, array('title' => __('Monitor checks')));
5598	$tdata[3] = $data["monitor_checks"] <= 0 ? '-' : $data["monitor_checks"];
5599	$tdata[3] = '<a class="big_data" href="' . $urls['monitor_checks'] . '">' . $tdata[3] . '</a>';
5600	$table_am->rowclass[] = '';
5601	$table_am->data[] = $tdata;
5602
5603	$output = '<fieldset class="databox tactical_set">
5604				<legend>' .
5605					__('Total agents and monitors') .
5606				'</legend>' .
5607				html_print_table($table_am, true) . '</fieldset>';
5608
5609	return $output;
5610}
5611
5612function reporting_get_stats_users($data) {
5613	global $config;
5614
5615	// Link URLS
5616	$urls = array();
5617	if (check_acl ($config['id_user'], 0, "UM")) {
5618		$urls['defined_users'] = "index.php?sec=gusuarios&amp;sec2=godmode/users/user_list";
5619	}
5620	else {
5621		$urls['defined_users'] = 'javascript:';
5622	}
5623
5624	// Users table
5625	$table_us = html_get_predefined_table();
5626
5627	$tdata = array();
5628	$tdata[0] = html_print_image('images/user_green.png', true, array('title' => __('Defined users')));
5629	$tdata[1] = count (get_users ());
5630	$tdata[1] = '<a class="big_data" href="' . $urls["defined_users"] . '">' . $tdata[1] . '</a>';
5631
5632	$tdata[2] = $tdata[3] = '&nbsp;';
5633	$table_us->rowclass[] = '';
5634	$table_us->data[] = $tdata;
5635
5636	$output = '<fieldset class="databox tactical_set">
5637				<legend>' .
5638					__('Users') .
5639				'</legend>' .
5640				html_print_table($table_us, true) . '</fieldset>';
5641
5642	return $output;
5643}
5644
5645/**
5646 * Get the average value of an agent module in a period of time.
5647 *
5648 * @param int Agent module id
5649 * @param int Period of time to check (in seconds)
5650 * @param int Top date to check the values. Default current time.
5651 *
5652 * @return float The average module value in the interval.
5653 */
5654function reporting_get_agentmodule_data_average ($id_agent_module, $period=0, $date = 0) {
5655	global $config;
5656
5657	// Initialize variables
5658	if (empty ($date)) $date = get_system_time ();
5659	$datelimit = $date - $period;
5660
5661	$search_in_history_db = db_search_in_history_db($datelimit);
5662
5663	$id_module_type = modules_get_agentmodule_type ($id_agent_module);
5664	$module_type = modules_get_moduletype_name ($id_module_type);
5665	$uncompressed_module = is_module_uncompressed ($module_type);
5666
5667	// Get module data
5668	$interval_data = db_get_all_rows_sql ('SELECT *
5669		FROM tagente_datos
5670		WHERE id_agente_modulo = ' . (int) $id_agent_module .
5671			' AND utimestamp > ' . (int) $datelimit .
5672			' AND utimestamp < ' . (int) $date .
5673		' ORDER BY utimestamp ASC', $search_in_history_db);
5674	if ($interval_data === false) $interval_data = array ();
5675
5676	// Uncompressed module data
5677	if ($uncompressed_module) {
5678		$min_necessary = 1;
5679
5680	// Compressed module data
5681	}
5682	else {
5683		// Get previous data
5684		$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
5685		if ($previous_data !== false) {
5686			$previous_data['utimestamp'] = $datelimit;
5687			array_unshift ($interval_data, $previous_data);
5688		}
5689
5690		// Get next data
5691		$next_data = modules_get_next_data ($id_agent_module, $date);
5692		if ($next_data !== false) {
5693			$next_data['utimestamp'] = $date;
5694			array_push ($interval_data, $next_data);
5695		}
5696		else if (count ($interval_data) > 0) {
5697			// Propagate the last known data to the end of the interval
5698			$next_data = array_pop ($interval_data);
5699			array_push ($interval_data, $next_data);
5700			$next_data['utimestamp'] = $date;
5701			array_push ($interval_data, $next_data);
5702		}
5703
5704		$min_necessary = 2;
5705	}
5706
5707	if (count ($interval_data) < $min_necessary) {
5708		return false;
5709	}
5710
5711	// Set initial conditions
5712	$total = 0;
5713	$count = 0;
5714	if (! $uncompressed_module) {
5715		$previous_data = array_shift ($interval_data);
5716
5717		// Do not count the empty start of an interval as 0
5718		if ($previous_data['utimestamp'] != $datelimit) {
5719			$period = $date - $previous_data['utimestamp'];
5720		}
5721	}
5722
5723	switch ($config["dbtype"]) {
5724		case "mysql":
5725		case "postgresql":
5726			// Do none
5727			break;
5728		case "oracle":
5729			$previous_data['datos'] =
5730				oracle_format_float_to_php($previous_data['datos']);
5731			break;
5732	}
5733
5734	foreach ($interval_data as $data) {
5735		switch ($config["dbtype"]) {
5736			case "mysql":
5737			case "postgresql":
5738				// Do none
5739				break;
5740			case "oracle":
5741				$data['datos'] =
5742					oracle_format_float_to_php($data['datos']);
5743				break;
5744		}
5745
5746		if (! $uncompressed_module) {
5747			$total += $previous_data['datos'] * ($data['utimestamp'] - $previous_data['utimestamp']);
5748			$previous_data = $data;
5749		}
5750		else {
5751			$total += $data['datos'];
5752			$count++;
5753		}
5754	}
5755
5756	// Compressed module data
5757	if (! $uncompressed_module) {
5758		if ($period == 0) {
5759			return 0;
5760		}
5761
5762		return $total / $period;
5763	}
5764
5765	// Uncompressed module data
5766	if ($count == 0) {
5767		return 0;
5768	}
5769
5770	return $total / $count;
5771}
5772
5773
5774/**
5775 * Get the MTTR value of an agent module in a period of time. See
5776 * http://en.wikipedia.org/wiki/Mean_time_to_recovery
5777 *
5778 * @param int Agent module id
5779 * @param int Period of time to check (in seconds)
5780 * @param int Top date to check the values. Default current time.
5781 *
5782 * @return float The MTTR value in the interval.
5783 */
5784function reporting_get_agentmodule_mttr ($id_agent_module, $period = 0, $date = 0) {
5785
5786	// Initialize variables
5787	if (empty ($date)) $date = get_system_time ();
5788
5789	// Read module configuration
5790	$datelimit = $date - $period;
5791	$search_in_history_db = db_search_in_history_db($datelimit);
5792
5793	$module = db_get_row_sql ('SELECT max_critical, min_critical, id_tipo_modulo
5794		FROM tagente_modulo
5795		WHERE id_agente_modulo = ' . (int) $id_agent_module);
5796	if ($module === false) {
5797		return false;
5798	}
5799
5800	$critical_min = $module['min_critical'];
5801	$critical_max = $module['max_critical'];
5802	$module_type = $module['id_tipo_modulo'];
5803
5804	// Set critical_min and critical for proc modules
5805	$module_type_str = modules_get_type_name ($module_type);
5806	if (strstr ($module_type_str, 'proc') !== false &&
5807		($critical_min == 0 && $critical_max == 0)) {
5808		$critical_min = 1;
5809	}
5810
5811	// Get module data
5812	$interval_data = db_get_all_rows_sql ('SELECT * FROM tagente_datos
5813		WHERE id_agente_modulo = ' . (int) $id_agent_module .
5814		' AND utimestamp > ' . (int) $datelimit .
5815		' AND utimestamp < ' . (int) $date .
5816		' ORDER BY utimestamp ASC', $search_in_history_db);
5817	if ($interval_data === false) $interval_data = array ();
5818
5819	// Get previous data
5820	$previous_data = modules_get_previous_data(
5821		$id_agent_module, $datelimit);
5822	if ($previous_data !== false) {
5823		$previous_data['utimestamp'] = $datelimit;
5824		array_unshift ($interval_data, $previous_data);
5825	}
5826
5827	// Get next data
5828	$next_data = modules_get_next_data ($id_agent_module, $date);
5829	if ($next_data !== false) {
5830		$next_data['utimestamp'] = $date;
5831		array_push ($interval_data, $next_data);
5832	}
5833	else if (count ($interval_data) > 0) {
5834		// Propagate the last known data to the end of the interval
5835		$next_data = array_pop ($interval_data);
5836		array_push ($interval_data, $next_data);
5837		$next_data['utimestamp'] = $date;
5838		array_push ($interval_data, $next_data);
5839	}
5840
5841	if (count ($interval_data) < 2) {
5842		return false;
5843	}
5844
5845	// Set initial conditions
5846	$critical_period = 0;
5847	$first_data = array_shift ($interval_data);
5848	$previous_utimestamp = $first_data['utimestamp'];
5849
5850	switch ($config["dbtype"]) {
5851		case "mysql":
5852		case "postgresql":
5853			// Do none
5854			break;
5855		case "oracle":
5856			$first_data['datos'] =
5857				oracle_format_float_to_php($first_data['datos']);
5858			break;
5859	}
5860
5861	if ((($critical_max > $critical_min AND ($first_data['datos'] > $critical_max OR $first_data['datos'] < $critical_min))) OR
5862		($critical_max <= $critical_min AND $first_data['datos'] < $critical_min)) {
5863		$previous_status = 1;
5864		$critical_count = 1;
5865	}
5866	else {
5867		$previous_status = 0;
5868		$critical_count = 0;
5869	}
5870
5871	foreach ($interval_data as $data) {
5872		switch ($config["dbtype"]) {
5873			case "mysql":
5874			case "postgresql":
5875				// Do none
5876				break;
5877			case "oracle":
5878				$data['datos'] =
5879					oracle_format_float_to_php($data['datos']);
5880				break;
5881		}
5882
5883		// Previous status was critical
5884		if ($previous_status == 1) {
5885			$critical_period += $data['utimestamp'] - $previous_utimestamp;
5886		}
5887
5888		// Re-calculate previous status for the next data
5889		if ((($critical_max > $critical_min AND ($data['datos'] > $critical_max OR $data['datos'] < $critical_min))) OR
5890			($critical_max <= $critical_min AND $data['datos'] < $critical_min)) {
5891			if ($previous_status == 0) {
5892				$critical_count++;
5893			}
5894			$previous_status = 1;
5895		}
5896		else {
5897			$previous_status = 0;
5898		}
5899
5900		$previous_utimestamp = $data['utimestamp'];
5901	}
5902
5903	if ($critical_count == 0) {
5904		return 0;
5905	}
5906
5907	return $critical_period / $critical_count;
5908}
5909
5910
5911/**
5912 * Get the MTBF value of an agent module in a period of time. See
5913 * http://en.wikipedia.org/wiki/Mean_time_between_failures
5914 *
5915 * @param int Agent module id
5916 * @param int Period of time to check (in seconds)
5917 * @param int Top date to check the values. Default current time.
5918 *
5919 * @return float The MTBF value in the interval.
5920 */
5921function reporting_get_agentmodule_mtbf ($id_agent_module, $period = 0, $date = 0) {
5922
5923	// Initialize variables
5924	if (empty ($date)) $date = get_system_time ();
5925
5926	// Read module configuration
5927	$datelimit = $date - $period;
5928	$search_in_history_db = db_search_in_history_db($datelimit);
5929
5930	$module = db_get_row_sql ('SELECT max_critical, min_critical, id_tipo_modulo
5931		FROM tagente_modulo
5932		WHERE id_agente_modulo = ' . (int) $id_agent_module);
5933	if ($module === false) {
5934		return false;
5935	}
5936
5937	$critical_min = $module['min_critical'];
5938	$critical_max = $module['max_critical'];
5939	$module_type = $module['id_tipo_modulo'];
5940
5941	// Set critical_min and critical for proc modules
5942	$module_type_str = modules_get_type_name ($module_type);
5943	if (strstr ($module_type_str, 'proc') !== false &&
5944		($critical_min == 0 && $critical_max == 0)) {
5945		$critical_min = 1;
5946	}
5947
5948	// Get module data
5949	$interval_data = db_get_all_rows_sql ('SELECT * FROM tagente_datos
5950		WHERE id_agente_modulo = ' . (int) $id_agent_module .
5951		' AND utimestamp > ' . (int) $datelimit .
5952		' AND utimestamp < ' . (int) $date .
5953		' ORDER BY utimestamp ASC', $search_in_history_db);
5954	if ($interval_data === false) $interval_data = array ();
5955
5956	// Get previous data
5957	$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
5958	if ($previous_data !== false) {
5959		$previous_data['utimestamp'] = $datelimit;
5960		array_unshift ($interval_data, $previous_data);
5961	}
5962
5963	// Get next data
5964	$next_data = modules_get_next_data ($id_agent_module, $date);
5965	if ($next_data !== false) {
5966		$next_data['utimestamp'] = $date;
5967		array_push ($interval_data, $next_data);
5968	}
5969	else if (count ($interval_data) > 0) {
5970		// Propagate the last known data to the end of the interval
5971		$next_data = array_pop ($interval_data);
5972		array_push ($interval_data, $next_data);
5973		$next_data['utimestamp'] = $date;
5974		array_push ($interval_data, $next_data);
5975	}
5976
5977	if (count ($interval_data) < 2) {
5978		return false;
5979	}
5980
5981	// Set initial conditions
5982	$critical_period = 0;
5983	$first_data = array_shift ($interval_data);
5984	$previous_utimestamp = $first_data['utimestamp'];
5985
5986	switch ($config["dbtype"]) {
5987		case "mysql":
5988		case "postgresql":
5989			// Do none
5990			break;
5991		case "oracle":
5992			$first_data['datos'] =
5993				oracle_format_float_to_php($first_data['datos']);
5994			break;
5995	}
5996
5997	if ((($critical_max > $critical_min AND ($first_data['datos'] > $critical_max OR $first_data['datos'] < $critical_min))) OR
5998			($critical_max <= $critical_min AND $first_data['datos'] < $critical_min)) {
5999		$previous_status = 1;
6000		$critical_count = 1;
6001	}
6002	else {
6003		$previous_status = 0;
6004		$critical_count = 0;
6005	}
6006
6007	foreach ($interval_data as $data) {
6008		// Previous status was critical
6009		if ($previous_status == 1) {
6010			$critical_period += $data['utimestamp'] - $previous_utimestamp;
6011		}
6012
6013		switch ($config["dbtype"]) {
6014			case "mysql":
6015			case "postgresql":
6016				// Do none
6017				break;
6018			case "oracle":
6019				$data['datos'] =
6020					oracle_format_float_to_php($data['datos']);
6021				break;
6022		}
6023
6024		// Re-calculate previous status for the next data
6025		if ((($critical_max > $critical_min AND ($data['datos'] > $critical_max OR $data['datos'] < $critical_min))) OR
6026			($critical_max <= $critical_min AND $data['datos'] < $critical_min)) {
6027			if ($previous_status == 0) {
6028				$critical_count++;
6029			}
6030			$previous_status = 1;
6031		}
6032		else {
6033			$previous_status = 0;
6034		}
6035
6036		$previous_utimestamp = $data['utimestamp'];
6037	}
6038
6039	if ($critical_count == 0) {
6040		return 0;
6041	}
6042
6043	return ($period - $critical_period) / $critical_count;
6044}
6045
6046
6047/**
6048 * Get the TTO value of an agent module in a period of time.
6049 *
6050 * @param int Agent module id
6051 * @param int Period of time to check (in seconds)
6052 * @param int Top date to check the values. Default current time.
6053 *
6054 * @return float The TTO value in the interval.
6055 */
6056function reporting_get_agentmodule_tto ($id_agent_module, $period = 0, $date = 0) {
6057
6058	// Initialize variables
6059	if (empty ($date)) $date = get_system_time ();
6060
6061	// Read module configuration
6062	$datelimit = $date - $period;
6063	$search_in_history_db = db_search_in_history_db($datelimit);
6064
6065	$module = db_get_row_sql ('SELECT max_critical, min_critical, id_tipo_modulo
6066		FROM tagente_modulo
6067		WHERE id_agente_modulo = ' . (int) $id_agent_module);
6068	if ($module === false) {
6069		return false;
6070	}
6071
6072	$critical_min = $module['min_critical'];
6073	$critical_max = $module['max_critical'];
6074	$module_type = $module['id_tipo_modulo'];
6075
6076	// Set critical_min and critical for proc modules
6077	$module_type_str = modules_get_type_name ($module_type);
6078	if (strstr ($module_type_str, 'proc') !== false &&
6079		($critical_min == 0 && $critical_max == 0)) {
6080		$critical_min = 1;
6081	}
6082
6083	// Get module data
6084	$interval_data = db_get_all_rows_sql ('SELECT * FROM tagente_datos
6085		WHERE id_agente_modulo = ' . (int) $id_agent_module .
6086		' AND utimestamp > ' . (int) $datelimit .
6087		' AND utimestamp < ' . (int) $date .
6088		' ORDER BY utimestamp ASC', $search_in_history_db);
6089	if ($interval_data === false) $interval_data = array ();
6090
6091	// Get previous data
6092	$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
6093	if ($previous_data !== false) {
6094		$previous_data['utimestamp'] = $datelimit;
6095		array_unshift ($interval_data, $previous_data);
6096	}
6097
6098	// Get next data
6099	$next_data = modules_get_next_data ($id_agent_module, $date);
6100	if ($next_data !== false) {
6101		$next_data['utimestamp'] = $date;
6102		array_push ($interval_data, $next_data);
6103	}
6104	else if (count ($interval_data) > 0) {
6105		// Propagate the last known data to the end of the interval
6106		$next_data = array_pop ($interval_data);
6107		array_push ($interval_data, $next_data);
6108		$next_data['utimestamp'] = $date;
6109		array_push ($interval_data, $next_data);
6110	}
6111
6112	if (count ($interval_data) < 2) {
6113		return false;
6114	}
6115
6116	// Set initial conditions
6117	$critical_period = 0;
6118	$first_data = array_shift ($interval_data);
6119	$previous_utimestamp = $first_data['utimestamp'];
6120	if ((($critical_max > $critical_min AND ($first_data['datos'] > $critical_max OR $first_data['datos'] < $critical_min))) OR
6121			($critical_max <= $critical_min AND $first_data['datos'] < $critical_min)) {
6122		$previous_status = 1;
6123	}
6124	else {
6125		$previous_status = 0;
6126	}
6127
6128	foreach ($interval_data as $data) {
6129		// Previous status was critical
6130		if ($previous_status == 1) {
6131			$critical_period += $data['utimestamp'] - $previous_utimestamp;
6132		}
6133
6134		// Re-calculate previous status for the next data
6135		if ((($critical_max > $critical_min AND ($data['datos'] > $critical_max OR $data['datos'] < $critical_min))) OR
6136			($critical_max <= $critical_min AND $data['datos'] < $critical_min)) {
6137			$previous_status = 1;
6138		}
6139		else {
6140			$previous_status = 0;
6141		}
6142
6143		$previous_utimestamp = $data['utimestamp'];
6144	}
6145
6146	return $period - $critical_period;
6147}
6148
6149/**
6150 * Get the TTR value of an agent module in a period of time.
6151 *
6152 * @param int Agent module id
6153 * @param int Period of time to check (in seconds)
6154 * @param int Top date to check the values. Default current time.
6155 *
6156 * @return float The TTR value in the interval.
6157 */
6158function reporting_get_agentmodule_ttr ($id_agent_module, $period = 0, $date = 0) {
6159
6160	// Initialize variables
6161	if (empty ($date)) $date = get_system_time ();
6162
6163	// Read module configuration
6164	$datelimit = $date - $period;
6165	$search_in_history_db = db_search_in_history_db($datelimit);
6166
6167	$module = db_get_row_sql ('SELECT max_critical, min_critical, id_tipo_modulo
6168		FROM tagente_modulo
6169		WHERE id_agente_modulo = ' . (int) $id_agent_module);
6170	if ($module === false) {
6171		return false;
6172	}
6173
6174	$critical_min = $module['min_critical'];
6175	$critical_max = $module['max_critical'];
6176	$module_type = $module['id_tipo_modulo'];
6177
6178	// Set critical_min and critical for proc modules
6179	$module_type_str = modules_get_type_name ($module_type);
6180	if (strstr ($module_type_str, 'proc') !== false &&
6181		($critical_min == 0 && $critical_max == 0)) {
6182		$critical_min = 1;
6183	}
6184
6185	// Get module data
6186	$interval_data = db_get_all_rows_sql ('SELECT * FROM tagente_datos
6187		WHERE id_agente_modulo = ' . (int) $id_agent_module .
6188		' AND utimestamp > ' . (int) $datelimit .
6189		' AND utimestamp < ' . (int) $date .
6190		' ORDER BY utimestamp ASC', $search_in_history_db);
6191	if ($interval_data === false) $interval_data = array ();
6192
6193	// Get previous data
6194	$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
6195	if ($previous_data !== false) {
6196		$previous_data['utimestamp'] = $datelimit;
6197		array_unshift ($interval_data, $previous_data);
6198	}
6199
6200	// Get next data
6201	$next_data = modules_get_next_data ($id_agent_module, $date);
6202	if ($next_data !== false) {
6203		$next_data['utimestamp'] = $date;
6204		array_push ($interval_data, $next_data);
6205	}
6206	else if (count ($interval_data) > 0) {
6207		// Propagate the last known data to the end of the interval
6208		$next_data = array_pop ($interval_data);
6209		array_push ($interval_data, $next_data);
6210		$next_data['utimestamp'] = $date;
6211		array_push ($interval_data, $next_data);
6212	}
6213
6214	if (count ($interval_data) < 2) {
6215		return false;
6216	}
6217
6218	// Set initial conditions
6219	$critical_period = 0;
6220	$first_data = array_shift ($interval_data);
6221	$previous_utimestamp = $first_data['utimestamp'];
6222	if ((($critical_max > $critical_min AND ($first_data['datos'] > $critical_max OR $first_data['datos'] < $critical_min))) OR
6223			($critical_max <= $critical_min AND $first_data['datos'] < $critical_min)) {
6224		$previous_status = 1;
6225	}
6226	else {
6227		$previous_status = 0;
6228	}
6229
6230	foreach ($interval_data as $data) {
6231		// Previous status was critical
6232		if ($previous_status == 1) {
6233			$critical_period += $data['utimestamp'] - $previous_utimestamp;
6234		}
6235
6236		// Re-calculate previous status for the next data
6237		if ((($critical_max > $critical_min AND ($data['datos'] > $critical_max OR $data['datos'] < $critical_min))) OR
6238			($critical_max <= $critical_min AND $data['datos'] < $critical_min)) {
6239			$previous_status = 1;
6240		}
6241		else {
6242			$previous_status = 0;
6243		}
6244
6245		$previous_utimestamp = $data['utimestamp'];
6246	}
6247
6248	return $critical_period;
6249}
6250
6251
6252/**
6253 * Get a detailed report of the modules of the agent
6254 *
6255 * @param int $id_agent Agent id to get the report for.
6256 * @param string $filter filter for get partial modules.
6257 *
6258 * @return array An array
6259 */
6260function reporting_get_agent_module_info ($id_agent, $filter = false) {
6261	global $config;
6262
6263	$return = array ();
6264	$return["last_contact"] = 0; //Last agent contact
6265	$return["status"] = STATUS_AGENT_NO_DATA;
6266	$return["status_img"] = ui_print_status_image (STATUS_AGENT_NO_DATA, __('Agent without data'), true);
6267	$return["alert_status"] = "notfired";
6268	$return["alert_value"] = STATUS_ALERT_NOT_FIRED;
6269	$return["alert_img"] = ui_print_status_image (STATUS_ALERT_NOT_FIRED, __('Alert not fired'), true);
6270	$return["agent_group"] = agents_get_agent_group ($id_agent);
6271
6272	if (!check_acl ($config["id_user"], $return["agent_group"], "AR")) {
6273		return $return;
6274	}
6275
6276	if ($filter != '') {
6277		$filter = 'AND ';
6278	}
6279
6280	$filter = 'disabled = 0';
6281
6282	$modules = agents_get_modules($id_agent, false, $filter, true, false);
6283
6284	if ($modules === false) {
6285		return $return;
6286	}
6287
6288	$now = get_system_time ();
6289
6290	// Get modules status for this agent
6291
6292	$agent = db_get_row ("tagente", "id_agente", $id_agent);
6293
6294	$return["total_count"] = $agent["total_count"];
6295	$return["normal_count"] = $agent["normal_count"];
6296	$return["warning_count"] = $agent["warning_count"];
6297	$return["critical_count"] = $agent["critical_count"];
6298	$return["unknown_count"] = $agent["unknown_count"];
6299	$return["fired_count"] = $agent["fired_count"];
6300	$return["notinit_count"] = $agent["notinit_count"];
6301
6302	if ($return["total_count"] > 0) {
6303		if ($return["critical_count"] > 0) {
6304			$return["status"] = STATUS_AGENT_CRITICAL;
6305			$return["status_img"] = ui_print_status_image (STATUS_AGENT_CRITICAL, __('At least one module in CRITICAL status'), true);
6306		}
6307		else if ($return["warning_count"] > 0) {
6308			$return["status"] = STATUS_AGENT_WARNING;
6309			$return["status_img"] = ui_print_status_image (STATUS_AGENT_WARNING, __('At least one module in WARNING status'), true);
6310		}
6311		else if ($return["unknown_count"] > 0) {
6312			$return["status"] = STATUS_AGENT_DOWN;
6313			$return["status_img"] = ui_print_status_image (STATUS_AGENT_DOWN, __('At least one module is in UKNOWN status'), true);
6314		}
6315		else {
6316			$return["status"] = STATUS_AGENT_OK;
6317			$return["status_img"] = ui_print_status_image (STATUS_AGENT_OK, __('All Monitors OK'), true);
6318		}
6319	}
6320
6321	//Alert not fired is by default
6322	if ($return["fired_count"] > 0) {
6323		$return["alert_status"] = "fired";
6324		$return["alert_img"] = ui_print_status_image (STATUS_ALERT_FIRED, __('Alert fired'), true);
6325		$return["alert_value"] = STATUS_ALERT_FIRED;
6326	}
6327	elseif (groups_give_disabled_group ($return["agent_group"])) {
6328		$return["alert_status"] = "disabled";
6329		$return["alert_value"] = STATUS_ALERT_DISABLED;
6330		$return["alert_img"] = ui_print_status_image (STATUS_ALERT_DISABLED, __('Alert disabled'), true);
6331	}
6332
6333	return $return;
6334}
6335
6336
6337/**
6338 * Print tiny statistics of the status of one agent, group, etc.
6339 *
6340 * @param mixed Array with the counts of the total modules, normal modules, critical modules, warning modules, unknown modules and fired alerts
6341 * @param bool return or echo flag
6342 *
6343 * @return string html formatted tiny stats of modules/alerts of an agent
6344 */
6345function reporting_tiny_stats ($counts_info, $return = false, $type = 'agent', $separator = ':', $strict_user = false) {
6346	global $config;
6347
6348	$out = '';
6349
6350	// Depend the type of object, the stats will refer agents, modules...
6351	switch ($type) {
6352		case 'modules':
6353			$template_title['total_count'] = __('%d Total modules');
6354			$template_title['normal_count'] = __('%d Normal modules');
6355			$template_title['critical_count'] = __('%d Critical modules');
6356			$template_title['warning_count'] = __('%d Warning modules');
6357			$template_title['unknown_count'] = __('%d Unknown modules');
6358			break;
6359		case 'agent':
6360			$template_title['total_count'] = __('%d Total modules');
6361			$template_title['normal_count'] = __('%d Normal modules');
6362			$template_title['critical_count'] = __('%d Critical modules');
6363			$template_title['warning_count'] = __('%d Warning modules');
6364			$template_title['unknown_count'] = __('%d Unknown modules');
6365			$template_title['fired_count'] = __('%d Fired alerts');
6366			break;
6367		default:
6368			$template_title['total_count'] = __('%d Total agents');
6369			$template_title['normal_count'] = __('%d Normal agents');
6370			$template_title['critical_count'] = __('%d Critical agents');
6371			$template_title['warning_count'] = __('%d Warning agents');
6372			$template_title['unknown_count'] = __('%d Unknown agents');
6373			$template_title['not_init_count'] = __('%d not init agents');
6374			$template_title['fired_count'] = __('%d Fired alerts');
6375			break;
6376	}
6377
6378	if ($strict_user && $type == 'agent') {
6379
6380		$acltags = tags_get_user_module_and_tags ($config['id_user'],'AR', $strict_user);
6381		$filter['disabled'] = 0;
6382		$id_agent = $counts_info['id_agente'];
6383
6384		$counts_info = array();
6385		$counts_info['normal_count'] = count(tags_get_agent_modules ($id_agent, false, $acltags, false, $filter, false, AGENT_MODULE_STATUS_NORMAL));
6386		$counts_info['warning_count'] = count(tags_get_agent_modules ($id_agent, false, $acltags, false, $filter, false, AGENT_MODULE_STATUS_WARNING));
6387		$counts_info['critical_count'] = count(tags_get_agent_modules ($id_agent, false, $acltags, false, $filter, false, AGENT_MODULE_STATUS_CRITICAL_BAD));
6388		$counts_info['notinit_count'] = count(tags_get_agent_modules ($id_agent, false, $acltags, false, $filter, false, AGENT_MODULE_STATUS_NOT_INIT));
6389		$counts_info['unknown_count'] = count(tags_get_agent_modules ($id_agent, false, $acltags, false, $filter, false, AGENT_MODULE_STATUS_UNKNOWN));
6390		$counts_info['total_count'] = $counts_info['normal_count'] + $counts_info['warning_count'] + $counts_info['critical_count'] + $counts_info['unknown_count'] + $counts_info['notinit_count'];
6391
6392		$all_agent_modules = tags_get_agent_modules ($id_agent, false, $acltags, false, $filter);
6393		if (!empty($all_agent_modules)) {
6394			$mod_clause = "(".implode(',', array_keys($all_agent_modules)).")";
6395
6396			$counts_info['fired_count'] = (int) db_get_sql ("SELECT COUNT(times_fired)
6397				FROM talert_template_modules
6398				WHERE times_fired != 0 AND id_agent_module IN ".$mod_clause);
6399		}
6400		else {
6401			$counts_info['fired_count'] = 0;
6402		}
6403	}
6404
6405	// Store the counts in a data structure to print hidden divs with titles
6406	$stats = array();
6407
6408	if (isset($counts_info['total_count'])) {
6409		$not_init = isset($counts_info['notinit_count']) ? $counts_info['notinit_count'] : 0;
6410		$total_count = $counts_info['total_count'] - $not_init;
6411		$stats[] = array('name' => 'total_count', 'count' => $total_count, 'title' => sprintf($template_title['total_count'], $total_count));
6412	}
6413
6414	if (isset($counts_info['normal_count'])) {
6415		$normal_count = $counts_info['normal_count'];
6416		$stats[] = array('name' => 'normal_count', 'count' => $normal_count, 'title' => sprintf($template_title['normal_count'], $normal_count));
6417	}
6418
6419	if (isset($counts_info['critical_count'])) {
6420		$critical_count = $counts_info['critical_count'];
6421		$stats[] = array('name' => 'critical_count', 'count' => $critical_count, 'title' => sprintf($template_title['critical_count'], $critical_count));
6422	}
6423
6424	if (isset($counts_info['warning_count'])) {
6425		$warning_count = $counts_info['warning_count'];
6426		$stats[] = array('name' => 'warning_count', 'count' => $warning_count, 'title' => sprintf($template_title['warning_count'], $warning_count));
6427	}
6428
6429	if (isset($counts_info['unknown_count'])) {
6430		$unknown_count = $counts_info['unknown_count'];
6431		$stats[] = array('name' => 'unknown_count', 'count' => $unknown_count, 'title' => sprintf($template_title['unknown_count'], $unknown_count));
6432	}
6433
6434	if (isset($counts_info['not_init_count'])) {
6435		$not_init_count = $counts_info['not_init_count'];
6436		$stats[] = array('name' => 'not_init_count',
6437			'count' => $not_init_count,
6438			'title' => sprintf($template_title['not_init_count'], $not_init_count));
6439	}
6440
6441	if (isset($template_title['fired_count'])) {
6442		if (isset($counts_info['fired_count'])) {
6443			$fired_count = $counts_info['fired_count'];
6444			$stats[] = array('name' => 'fired_count', 'count' => $fired_count, 'title' => sprintf($template_title['fired_count'], $fired_count));
6445		}
6446	}
6447
6448	$uniq_id = uniqid();
6449
6450	foreach ($stats as $stat) {
6451		$params = array('id' => 'forced_title_' . $stat['name'] . '_' . $uniq_id,
6452						'class' => 'forced_title_layer',
6453						'content' => $stat['title'],
6454						'hidden' => true);
6455		$out .= html_print_div($params, true);
6456	}
6457
6458	// If total count is less than 0, is an error. Never show negative numbers
6459	if ($total_count < 0) {
6460		$total_count = 0;
6461	}
6462
6463	$out .= '<b>' . '<span id="total_count_' . $uniq_id . '" class="forced_title" style="font-size: 7pt">' . $total_count . '</span>';
6464	if (isset($fired_count) && $fired_count > 0)
6465		$out .= ' ' . $separator . ' <span class="orange forced_title" id="fired_count_' . $uniq_id . '" style="font-size: 7pt">' . $fired_count . '</span>';
6466	if (isset($critical_count) && $critical_count > 0)
6467		$out .= ' ' . $separator . ' <span class="red forced_title" id="critical_count_' . $uniq_id . '" style="font-size: 7pt">' . $critical_count . '</span>';
6468	if (isset($warning_count) && $warning_count > 0)
6469		$out .= ' ' . $separator . ' <span class="yellow forced_title" id="warning_count_' . $uniq_id . '" style="font-size: 7pt">' . $warning_count . '</span>';
6470	if (isset($unknown_count) && $unknown_count > 0)
6471		$out .= ' ' . $separator . ' <span class="grey forced_title" id="unknown_count_' . $uniq_id . '" style="font-size: 7pt">' . $unknown_count . '</span>';
6472	if (isset($not_init_count) && $not_init_count > 0)
6473		$out .= ' ' . $separator . ' <span class="blue forced_title" id="not_init_count_' . $uniq_id . '" style="font-size: 7pt">' . $not_init_count . '</span>';
6474	if (isset($normal_count) && $normal_count > 0)
6475		$out .= ' ' . $separator . ' <span class="green forced_title" id="normal_count_' . $uniq_id . '" style="font-size: 7pt">' . $normal_count . '</span>';
6476
6477	$out .= '</b>';
6478
6479	if ($return) {
6480		return $out;
6481	}
6482	else {
6483		echo $out;
6484	}
6485}
6486
6487
6488/**
6489 * Get SLA of a module.
6490 *
6491 * @param int Agent module to calculate SLA
6492 * @param int Period to check the SLA compliance.
6493 * @param int Minimum data value the module in the right interval
6494 * @param int Maximum data value the module in the right interval. False will
6495 * ignore max value
6496 * @param int Beginning date of the report in UNIX time (current date by default).
6497 * @param array $dayWeek  Array of days week to extract as array('monday' => false, 'tuesday' => true....), and by default is null.
6498 * @param string $timeFrom Time in the day to start to extract in mysql format, by default null.
6499 * @param string $timeTo Time in the day to end to extract in mysql format, by default null.
6500 *
6501 * @return float SLA percentage of the requested module. False if no data were
6502 * found
6503 */
6504function reporting_get_agentmodule_sla ($id_agent_module, $period = 0,
6505	$min_value = 1, $max_value = false, $date = 0, $daysWeek = null,
6506	$timeFrom = null, $timeTo = null) {
6507
6508	global $config;
6509
6510
6511
6512	if (empty($id_agent_module))
6513		return false;
6514
6515	// Set initial conditions
6516	$bad_period = 0;
6517	// Limit date to start searching data
6518	$datelimit = $date - $period;
6519	$search_in_history_db = db_search_in_history_db($datelimit);
6520
6521	// Initialize variables
6522	if (empty ($date)) {
6523		$date = get_system_time ();
6524	}
6525	if ($daysWeek === null) {
6526		$daysWeek = array();
6527	}
6528
6529
6530
6531
6532	// Calculate the SLA for large time without hours
6533	if ($timeFrom == $timeTo) {
6534
6535		// Get interval data
6536		$sql = sprintf ('SELECT *
6537			FROM tagente_datos
6538			WHERE id_agente_modulo = %d
6539				AND utimestamp > %d AND utimestamp <= %d',
6540			$id_agent_module, $datelimit, $date);
6541
6542		//Add the working times (mon - tue - wed ...) and from time to time
6543		$days = array();
6544		//Translate to mysql week days
6545		if ($daysWeek) {
6546			foreach ($daysWeek as $key => $value) {
6547				if (!$value) {
6548					if ($key == 'monday') {
6549						$days[] = 2;
6550					}
6551					if ($key == 'tuesday') {
6552						$days[] = 3;
6553					}
6554					if ($key == 'wednesday') {
6555						$days[] = 4;
6556					}
6557					if ($key == 'thursday') {
6558						$days[] = 5;
6559					}
6560					if ($key == 'friday') {
6561						$days[] = 6;
6562					}
6563					if ($key == 'saturday') {
6564						$days[] = 7;
6565					}
6566					if ($key == 'sunday') {
6567						$days[] = 1;
6568					}
6569				}
6570			}
6571		}
6572
6573		if (count($days) > 0) {
6574			$sql .= ' AND DAYOFWEEK(FROM_UNIXTIME(utimestamp)) NOT IN (' . implode(',', $days) . ')';
6575		}
6576
6577		$sql .= "\n";
6578		$sql .= ' ORDER BY utimestamp ASC';
6579		$interval_data = db_get_all_rows_sql ($sql, $search_in_history_db);
6580
6581		if ($interval_data === false) {
6582			$interval_data = array ();
6583		}
6584
6585		// Calculate planned downtime dates
6586		$downtime_dates = reporting_get_planned_downtimes_intervals(
6587			$id_agent_module, $datelimit, $date);
6588
6589		// Get previous data
6590		$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
6591
6592		if ($previous_data !== false) {
6593			$previous_data['utimestamp'] = $datelimit;
6594			array_unshift ($interval_data, $previous_data);
6595		}
6596
6597		// Get next data
6598		$next_data = modules_get_next_data ($id_agent_module, $date);
6599
6600		if ($next_data !== false) {
6601			$next_data['utimestamp'] = $date;
6602			array_push ($interval_data, $next_data);
6603		}
6604		else if (count ($interval_data) > 0) {
6605			// Propagate the last known data to the end of the interval
6606			$next_data = array_pop ($interval_data);
6607			array_push ($interval_data, $next_data);
6608			$next_data['utimestamp'] = $date;
6609			array_push ($interval_data, $next_data);
6610		}
6611
6612		if (count ($interval_data) < 2) {
6613			return false;
6614		}
6615
6616
6617		$first_data = array_shift ($interval_data);
6618
6619		// Do not count the empty start of an interval as 0
6620		if ($first_data['utimestamp'] != $datelimit) {
6621			$period = $date - $first_data['utimestamp'];
6622		}
6623
6624		$previous_utimestamp = $first_data['utimestamp'];
6625		if (
6626			(
6627				(
6628					$max_value > $min_value AND (
6629						$first_data['datos'] > $max_value OR
6630						$first_data['datos'] < $min_value
6631					)
6632				)
6633			) OR
6634			(
6635				$max_value <= $min_value AND
6636				$first_data['datos'] < $min_value
6637			)
6638		) {
6639
6640			$previous_status = 1;
6641			foreach ($downtime_dates as $date_dt) {
6642
6643				if (($date_dt['date_from'] <= $previous_utimestamp) AND
6644					($date_dt['date_to'] >= $previous_utimestamp)) {
6645
6646					$previous_status = 0;
6647				}
6648			}
6649		}
6650		else {
6651			$previous_status = 0;
6652		}
6653
6654
6655
6656
6657
6658		foreach ($interval_data as $data) {
6659			// Previous status was critical
6660			if ($previous_status == 1) {
6661				$bad_period += $data['utimestamp'] - $previous_utimestamp;
6662			}
6663
6664			if (array_key_exists('datos', $data)) {
6665				// Re-calculate previous status for the next data
6666				if ((($max_value > $min_value AND ($data['datos'] > $max_value OR $data['datos'] < $min_value))) OR
6667					($max_value <= $min_value AND $data['datos'] < $min_value)) {
6668
6669					$previous_status = 1;
6670					foreach ($downtime_dates as $date_dt) {
6671						if (($date_dt['date_from'] <= $data['utimestamp']) AND ($date_dt['date_to'] >= $data['utimestamp'])) {
6672							$previous_status = 0;
6673						}
6674					}
6675				}
6676				else {
6677					$previous_status = 0;
6678				}
6679			}
6680
6681			$previous_utimestamp = $data['utimestamp'];
6682		}
6683
6684		// Return the percentage of SLA compliance
6685		return (float) (100 - ($bad_period / $period) * 100);
6686	}
6687	elseif ($period <= SECONDS_1DAY) {
6688
6689
6690		return reporting_get_agentmodule_sla_day(
6691			$id_agent_module,
6692			$period,
6693			$min_value,
6694			$max_value,
6695			$date,
6696			$daysWeek,
6697			$timeFrom,
6698			$timeTo);
6699	}
6700	else {
6701
6702		// Extract the data each day
6703
6704		$sla = 0;
6705
6706		$i = 0;
6707		for ($interval = SECONDS_1DAY; $interval <= $period; $interval = $interval + SECONDS_1DAY) {
6708
6709
6710			$sla_day = reporting_get_agentmodule_sla(
6711				$id_agent_module,
6712				SECONDS_1DAY,
6713				$min_value,
6714				$max_value,
6715				$datelimit + $interval,
6716				$daysWeek,
6717				$timeFrom, $timeTo);
6718
6719
6720
6721			// Avoid to add the period of module not init
6722			if ($sla_day !== false) {
6723				$sla += $sla_day;
6724				$i++;
6725			}
6726		}
6727
6728		$sla = $sla / $i;
6729
6730		return $sla;
6731	}
6732}
6733
6734
6735/**
6736 * Get Monitor report of a module.
6737 * if (($min_value < $data['datos'])OR ($max_value > 0 AND
6738		($data['datos'] > $min_value AND $data['datos'] < $max_value)))
6739 * @param int Agent module to calculate monitor report
6740 * @param int Period to check the SLA compliance.
6741 * @param int Minimum data value the module in the right interval
6742 * @param int Maximum data value the module in the right interval. False will
6743 * ignore max value
6744 * @param int Beginning date of the report in UNIX time (current date by default).
6745 *
6746 * @return float Monitor percentage of the requested module. False if no data were
6747 * found
6748 */
6749function reporting_get_agentmodule_monitor ($id_agent_module, $period = 0, $min_value = 1, $max_value = false, $date = 0) {
6750	global $config;
6751
6752
6753
6754	if (empty($id_agent_module))
6755		return false;
6756
6757	// Set initial conditions
6758	$bad_period = 0;
6759	// Limit date to start searching data
6760	$datelimit = $date - $period;
6761	$search_in_history_db = db_search_in_history_db($datelimit);
6762
6763	// Initialize variables
6764	if (empty ($date)) {
6765		$date = get_system_time ();
6766	}
6767	if ($daysWeek === null) {
6768		$daysWeek = array();
6769	}
6770
6771
6772
6773
6774	// Calculate the SLA for large time without hours
6775
6776	// Get interval data
6777	$sql = sprintf ('SELECT *
6778		FROM tagente_datos
6779		WHERE id_agente_modulo = %d
6780			AND utimestamp > %d AND utimestamp <= %d',
6781		$id_agent_module, $datelimit, $date);
6782
6783	$sql .= ' ORDER BY utimestamp ASC';
6784	$interval_data = db_get_all_rows_sql ($sql, $search_in_history_db);
6785
6786	if ($interval_data === false) {
6787		$interval_data = array ();
6788	}
6789
6790	// Calculate planned downtime dates
6791	$downtime_dates = reporting_get_planned_downtimes_intervals(
6792		$id_agent_module, $datelimit, $date);
6793
6794	// Get previous data
6795	$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
6796
6797	if ($previous_data !== false) {
6798		$previous_data['utimestamp'] = $datelimit;
6799		array_unshift ($interval_data, $previous_data);
6800	}
6801
6802	// Get next data
6803	$next_data = modules_get_next_data ($id_agent_module, $date);
6804
6805	if ($next_data !== false) {
6806		$next_data['utimestamp'] = $date;
6807		array_push ($interval_data, $next_data);
6808	}
6809	else if (count ($interval_data) > 0) {
6810		// Propagate the last known data to the end of the interval
6811		$next_data = array_pop ($interval_data);
6812		array_push ($interval_data, $next_data);
6813		$next_data['utimestamp'] = $date;
6814		array_push ($interval_data, $next_data);
6815	}
6816
6817	if (count ($interval_data) < 2) {
6818		return false;
6819	}
6820
6821
6822	$first_data = array_shift ($interval_data);
6823
6824	// Do not count the empty start of an interval as 0
6825	if ($first_data['utimestamp'] != $datelimit) {
6826		$period = $date - $first_data['utimestamp'];
6827	}
6828
6829	$previous_utimestamp = $first_data['utimestamp'];
6830	if (($max_value > 0 AND $min_value > 0 ) AND ($data['datos'] > $min_value
6831		AND $data['datos'] < $max_value)) {
6832
6833		$previous_status = 1;
6834		foreach ($downtime_dates as $date_dt) {
6835
6836			if (($date_dt['date_from'] <= $previous_utimestamp) AND
6837				($date_dt['date_to'] >= $previous_utimestamp)) {
6838
6839				$previous_status = 0;
6840			}
6841		}
6842	}
6843	else {
6844		$previous_status = 0;
6845	}
6846
6847	foreach ($interval_data as $data) {
6848		// Previous status was critical
6849		if ($previous_status == 1) {
6850			$bad_period += $data['utimestamp'] - $previous_utimestamp;
6851		}
6852
6853		if (array_key_exists('datos', $data)) {
6854			// Re-calculate previous status for the next data
6855			if (($max_value > 0) AND ($data['datos'] > $min_value
6856				AND $data['datos'] < $max_value)) {
6857
6858				$previous_status = 1;
6859				foreach ($downtime_dates as $date_dt) {
6860					if (($date_dt['date_from'] <= $data['utimestamp']) AND ($date_dt['date_to'] >= $data['utimestamp'])) {
6861						$previous_status = 0;
6862					}
6863				}
6864			}
6865			else {
6866				$previous_status = 0;
6867			}
6868		}
6869
6870		$previous_utimestamp = $data['utimestamp'];
6871	}
6872
6873	// Return the percentage of SLA compliance
6874	return (float) (100 - ($bad_period / $period) * 100);
6875}
6876
6877
6878/**
6879 * Get the time intervals where an agentmodule is affected by the planned downtimes.
6880 *
6881 * @param int Agent module to calculate planned downtimes intervals.
6882 * @param int Start date in utimestamp.
6883 * @param int End date in utimestamp.
6884 * @param bool Whether ot not to get the planned downtimes that affect the service associated with the agentmodule.
6885 *
6886 * @return Array with time intervals.
6887 */
6888function reporting_get_planned_downtimes_intervals ($id_agent_module, $start_date, $end_date, $check_services = false) {
6889	global $config;
6890
6891	if (empty($id_agent_module))
6892		return false;
6893
6894	require_once ($config['homedir'] . '/include/functions_planned_downtimes.php');
6895
6896	$malformed_planned_downtimes = planned_downtimes_get_malformed();
6897	if (empty($malformed_planned_downtimes))
6898		$malformed_planned_downtimes = array();
6899
6900	switch ($config["dbtype"]) {
6901		case "mysql":
6902		case "postgresql":
6903			$tpdr_description = "tpdr.description";
6904			break;
6905		case "oracle":
6906			$tpdr_description = "to_char(tpdr.description)";
6907			break;
6908	}
6909
6910
6911	$sql_downtime = "
6912		SELECT DISTINCT(tpdr.id),
6913				tpdr.name,
6914				" . $tpdr_description . ",
6915				tpdr.date_from,
6916				tpdr.date_to,
6917				tpdr.executed,
6918				tpdr.id_group,
6919				tpdr.only_alerts,
6920				tpdr.monday,
6921				tpdr.tuesday,
6922				tpdr.wednesday,
6923				tpdr.thursday,
6924				tpdr.friday,
6925				tpdr.saturday,
6926				tpdr.sunday,
6927				tpdr.periodically_time_from,
6928				tpdr.periodically_time_to,
6929				tpdr.periodically_day_from,
6930				tpdr.periodically_day_to,
6931				tpdr.type_downtime,
6932				tpdr.type_execution,
6933				tpdr.type_periodicity,
6934				tpdr.id_user
6935		FROM (
6936				SELECT tpd.*
6937				FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam
6938				WHERE tpd.id = tpda.id_downtime
6939					AND tpda.all_modules = 1
6940					AND tpda.id_agent = tam.id_agente
6941					AND tam.id_agente_modulo = $id_agent_module
6942			UNION ALL
6943				SELECT tpd.*
6944				FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm
6945				WHERE tpd.id = tpdm.id_downtime
6946					AND tpdm.id_agent_module = $id_agent_module
6947		) tpdr
6948		ORDER BY tpdr.id";
6949
6950
6951
6952	$downtimes = db_get_all_rows_sql($sql_downtime);
6953
6954	if ($downtimes == false) {
6955		$downtimes = array();
6956	}
6957	$downtime_dates = array();
6958	foreach ($downtimes as $downtime) {
6959		$downtime_id = $downtime['id'];
6960		$downtime_type = $downtime['type_execution'];
6961		$downtime_periodicity = $downtime['type_periodicity'];
6962
6963		if ($downtime_type == 'once') {
6964			$dates = array();
6965			$dates['date_from'] = $downtime['date_from'];
6966			$dates['date_to'] = $downtime['date_to'];
6967			$downtime_dates[] = $dates;
6968		}
6969		else if ($downtime_type == 'periodically') {
6970
6971			// If a planned downtime have malformed dates, its intervals aren't taken account
6972			$downtime_malformed = false;
6973			foreach ($malformed_planned_downtimes as $malformed_planned_downtime) {
6974				if ($downtime_id == $malformed_planned_downtime['id']) {
6975					$downtime_malformed = true;
6976					break;
6977				}
6978			}
6979			if ($downtime_malformed == true) {
6980				continue;
6981			}
6982			// If a planned downtime have malformed dates, its intervals aren't taken account
6983
6984			$downtime_time_from = $downtime['periodically_time_from'];
6985			$downtime_time_to = $downtime['periodically_time_to'];
6986
6987			$downtime_hour_from = date("H", strtotime($downtime_time_from));
6988			$downtime_minute_from = date("i", strtotime($downtime_time_from));
6989			$downtime_second_from = date("s", strtotime($downtime_time_from));
6990			$downtime_hour_to = date("H", strtotime($downtime_time_to));
6991			$downtime_minute_to = date("i", strtotime($downtime_time_to));
6992			$downtime_second_to = date("s", strtotime($downtime_time_to));
6993
6994			if ($downtime_periodicity == "monthly") {
6995				$downtime_day_from = $downtime['periodically_day_from'];
6996				$downtime_day_to = $downtime['periodically_day_to'];
6997
6998				$date_aux = strtotime(date("Y-m-01", $start_date));
6999				$year_aux = date("Y", $date_aux);
7000				$month_aux = date("m", $date_aux);
7001
7002				$end_year = date("Y", $end_date);
7003				$end_month = date("m", $end_date);
7004
7005				while ($year_aux < $end_year || ($year_aux == $end_year && $month_aux <= $end_month)) {
7006
7007					if ($downtime_day_from > $downtime_day_to) {
7008						$dates = array();
7009						$dates['date_from'] = strtotime("$year_aux-$month_aux-$downtime_day_from $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7010						$dates['date_to'] = strtotime(date("Y-m-t H:i:s", strtotime("$year_aux-$month_aux-28 23:59:59")));
7011						$downtime_dates[] = $dates;
7012
7013						$dates = array();
7014						if ($month_aux + 1 <= 12) {
7015							$dates['date_from'] = strtotime("$year_aux-".($month_aux + 1)."-01 00:00:00");
7016							$dates['date_to'] = strtotime("$year_aux-".($month_aux + 1)."-$downtime_day_to $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7017						}
7018						else {
7019							$dates['date_from'] = strtotime(($year_aux + 1)."-01-01 00:00:00");
7020							$dates['date_to'] = strtotime(($year_aux + 1)."-01-$downtime_day_to $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7021						}
7022						$downtime_dates[] = $dates;
7023					}
7024					else {
7025						if ($downtime_day_from == $downtime_day_to && strtotime($downtime_time_from) > strtotime($downtime_time_to)) {
7026							$date_aux_from = strtotime("$year_aux-$month_aux-$downtime_day_from $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7027							$max_day_num = date('t', $date_aux);
7028
7029							$dates = array();
7030							$dates['date_from'] = strtotime("$year_aux-$month_aux-$downtime_day_from $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7031							$dates['date_to'] = strtotime("$year_aux-$month_aux-$downtime_day_from 23:59:59");
7032							$downtime_dates[] = $dates;
7033
7034							if ($downtime_day_to + 1 > $max_day_num) {
7035
7036								$dates = array();
7037								if ($month_aux + 1 <= 12) {
7038									$dates['date_from'] = strtotime("$year_aux-".($month_aux + 1)."-01 00:00:00");
7039									$dates['date_to'] = strtotime("$year_aux-".($month_aux + 1)."-01 $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7040								}
7041								else {
7042									$dates['date_from'] = strtotime(($year_aux + 1)."-01-01 00:00:00");
7043									$dates['date_to'] = strtotime(($year_aux + 1)."-01-01 $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7044								}
7045								$downtime_dates[] = $dates;
7046							}
7047							else {
7048								$dates = array();
7049								$dates['date_from'] = strtotime("$year_aux-$month_aux-".($downtime_day_to + 1)." 00:00:00");
7050								$dates['date_to'] = strtotime("$year_aux-$month_aux-".($downtime_day_to + 1)." $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7051								$downtime_dates[] = $dates;
7052							}
7053						}
7054						else {
7055							$dates = array();
7056							$dates['date_from'] = strtotime("$year_aux-$month_aux-$downtime_day_from $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7057							$dates['date_to'] = strtotime("$year_aux-$month_aux-$downtime_day_to $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7058							$downtime_dates[] = $dates;
7059						}
7060					}
7061
7062					$month_aux++;
7063					if ($month_aux > 12) {
7064						$month_aux = 1;
7065						$year_aux++;
7066					}
7067				}
7068			}
7069			else if ($downtime_periodicity == "weekly") {
7070				$date_aux = $start_date;
7071				$active_days = array();
7072				$active_days[0] = ($downtime['sunday'] == 1) ? true : false;
7073				$active_days[1] = ($downtime['monday'] == 1) ? true : false;
7074				$active_days[2] = ($downtime['tuesday'] == 1) ? true : false;
7075				$active_days[3] = ($downtime['wednesday'] == 1) ? true : false;
7076				$active_days[4] = ($downtime['thursday'] == 1) ? true : false;
7077				$active_days[5] = ($downtime['friday'] == 1) ? true : false;
7078				$active_days[6] = ($downtime['saturday'] == 1) ? true : false;
7079
7080				while ($date_aux <= $end_date) {
7081					$weekday_num = date('w', $date_aux);
7082
7083					if ($active_days[$weekday_num]) {
7084						$day_num = date('d', $date_aux);
7085						$month_num = date('m', $date_aux);
7086						$year_num = date('Y', $date_aux);
7087
7088						$max_day_num = date('t', $date_aux);
7089
7090						if (strtotime($downtime_time_from) > strtotime($downtime_time_to)) {
7091							$dates = array();
7092							$dates['date_from'] = strtotime("$year_num-$month_num-$day_num $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7093							$dates['date_to'] = strtotime("$year_num-$month_num-$day_num 23:59:59");
7094							$downtime_dates[] = $dates;
7095
7096							$dates = array();
7097							if ($day_num + 1 > $max_day_num) {
7098								if ($month_num + 1 > 12) {
7099									$dates['date_from'] = strtotime(($year_num + 1)."-01-01 00:00:00");
7100									$dates['date_to'] = strtotime(($year_num + 1)."-01-01 $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7101								}
7102								else {
7103									$dates['date_from'] = strtotime("$year_num-".($month_num + 1)."-01 00:00:00");
7104									$dates['date_to'] = strtotime("$year_num-".($month_num + 1)."-01 $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7105								}
7106							}
7107							else {
7108								$dates['date_from'] = strtotime("$year_num-$month_num-".($day_num + 1)." 00:00:00");
7109								$dates['date_to'] = strtotime("$year_num-$month_num-".($day_num + 1)." $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7110							}
7111							$downtime_dates[] = $dates;
7112						}
7113						else {
7114							$dates = array();
7115							$dates['date_from'] = strtotime("$year_num-$month_num-$day_num $downtime_hour_from:$downtime_minute_from:$downtime_second_from");
7116							$dates['date_to'] = strtotime("$year_num-$month_num-$day_num $downtime_hour_to:$downtime_minute_to:$downtime_second_to");
7117							$downtime_dates[] = $dates;
7118						}
7119					}
7120
7121					$date_aux += SECONDS_1DAY;
7122				}
7123			}
7124		}
7125	}
7126
7127	if ($check_services) {
7128		enterprise_include_once("include/functions_services.php");
7129		if (function_exists("services_get_planned_downtimes_intervals")) {
7130			services_get_planned_downtimes_intervals($downtime_dates, $start_date, $end_date, false, $id_agent_module);
7131		}
7132	}
7133
7134	return $downtime_dates;
7135}
7136
7137/**
7138 * Gets a detailed reporting of groups's events.
7139 *
7140 * @param unknown_type $id_group Id of the group.
7141 * @param unknown_type $period Time period of the report.
7142 * @param unknown_type $date Date of the report.
7143 * @param unknown_type $return Whether to return or not.
7144 * @param unknown_type $html Whether to return HTML code or not.
7145 *
7146 * @return string Report of groups's events
7147 */
7148function reporting_get_count_events_by_agent ($id_group, $period = 0,
7149	$date = 0,
7150	$filter_event_validated = false, $filter_event_critical = false,
7151	$filter_event_warning = false, $filter_event_no_validated = false,
7152	$filter_event_filter_search = null) {
7153
7154	if (!is_numeric ($date)) {
7155		$date = strtotime ($date);
7156	}
7157	if (empty ($date)) {
7158		$date = get_system_time ();
7159	}
7160
7161	return events_get_count_events_by_agent($id_group, $period, $date,
7162		$filter_event_validated, $filter_event_critical,
7163		$filter_event_warning, $filter_event_no_validated,
7164		$filter_event_filter_search);
7165}
7166
7167/**
7168 * Get the maximum value of an agent module in a period of time.
7169 *
7170 * @param int Agent module id to get the maximum value.
7171 * @param int Period of time to check (in seconds)
7172 * @param int Top date to check the values. Default current time.
7173 *
7174 * @return float The maximum module value in the interval.
7175 */
7176function reporting_get_agentmodule_data_max ($id_agent_module, $period=0, $date = 0) {
7177	global $config;
7178
7179	// Initialize variables
7180	if (empty ($date)) $date = get_system_time ();
7181	$datelimit = $date - $period;
7182
7183	$search_in_history_db = db_search_in_history_db($datelimit);
7184
7185	$id_module_type = modules_get_agentmodule_type ($id_agent_module);
7186	$module_type = modules_get_moduletype_name ($id_module_type);
7187	$uncompressed_module = is_module_uncompressed ($module_type);
7188
7189	// Get module data
7190	$interval_data = db_get_all_rows_sql ('SELECT *
7191		FROM tagente_datos
7192		WHERE id_agente_modulo = ' . (int) $id_agent_module .
7193			' AND utimestamp > ' . (int) $datelimit .
7194			' AND utimestamp < ' . (int) $date .
7195		' ORDER BY utimestamp ASC', $search_in_history_db);
7196
7197	if ($interval_data === false) $interval_data = array ();
7198
7199	// Uncompressed module data
7200	if ($uncompressed_module) {
7201
7202	// Compressed module data
7203	}
7204	else {
7205		// Get previous data
7206		$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
7207		if ($previous_data !== false) {
7208			$previous_data['utimestamp'] = $datelimit;
7209			array_unshift ($interval_data, $previous_data);
7210		}
7211
7212		// Get next data
7213		$next_data = modules_get_next_data ($id_agent_module, $date);
7214		if ($next_data !== false) {
7215			$next_data['utimestamp'] = $date;
7216			array_push ($interval_data, $next_data);
7217		}
7218		else if (count ($interval_data) > 0) {
7219			// Propagate the last known data to the end of the interval
7220			$next_data = array_pop ($interval_data);
7221			array_push ($interval_data, $next_data);
7222			$next_data['utimestamp'] = $date;
7223			array_push ($interval_data, $next_data);
7224		}
7225	}
7226
7227	// Set initial conditions
7228	if (empty($iterval_data)) {
7229		$max = 0;
7230	}
7231	else {
7232		if ($uncompressed_module || $interval_data[0]['utimestamp'] == $datelimit) {
7233			$max = $interval_data[0]['datos'];
7234		}
7235		else {
7236			$max = 0;
7237		}
7238	}
7239
7240	switch ($config["dbtype"]) {
7241		case "mysql":
7242		case "postgresql":
7243			// Do none
7244			break;
7245		case "oracle":
7246			$max = oracle_format_float_to_php($max);
7247			break;
7248	}
7249
7250
7251
7252	foreach ($interval_data as $data) {
7253		switch ($config["dbtype"]) {
7254			case "mysql":
7255			case "postgresql":
7256				// Do none
7257				break;
7258			case "oracle":
7259				$data['datos'] =
7260					oracle_format_float_to_php($data['datos']);
7261				break;
7262		}
7263
7264		if ($data['datos'] > $max) {
7265			$max = $data['datos'];
7266		}
7267	}
7268
7269	return $max;
7270}
7271
7272/**
7273 * Get the minimum value of an agent module in a period of time.
7274 *
7275 * @param int Agent module id to get the minimum value.
7276 * @param int Period of time to check (in seconds)
7277 * @param int Top date to check the values in Unix time. Default current time.
7278 *
7279 * @return float The minimum module value of the module
7280 */
7281function reporting_get_agentmodule_data_min ($id_agent_module, $period=0, $date = 0) {
7282	global $config;
7283
7284	// Initialize variables
7285	if (empty ($date)) $date = get_system_time ();
7286	$datelimit = $date - $period;
7287
7288	$search_in_history_db = db_search_in_history_db($datelimit);
7289
7290	$id_module_type = modules_get_agentmodule_type ($id_agent_module);
7291	$module_type = modules_get_moduletype_name ($id_module_type);
7292	$uncompressed_module = is_module_uncompressed ($module_type);
7293
7294	// Get module data
7295	$interval_data = db_get_all_rows_sql ('SELECT *
7296		FROM tagente_datos
7297		WHERE id_agente_modulo = ' . (int) $id_agent_module .
7298			' AND utimestamp > ' . (int) $datelimit .
7299			' AND utimestamp < ' . (int) $date .
7300		' ORDER BY utimestamp ASC', $search_in_history_db);
7301	if ($interval_data === false) $interval_data = array ();
7302
7303	// Uncompressed module data
7304	if ($uncompressed_module) {
7305		$min_necessary = 1;
7306
7307	// Compressed module data
7308	}
7309	else {
7310		// Get previous data
7311		$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
7312		if ($previous_data !== false) {
7313			$previous_data['utimestamp'] = $datelimit;
7314			array_unshift ($interval_data, $previous_data);
7315		}
7316
7317		// Get next data
7318		$next_data = modules_get_next_data ($id_agent_module, $date);
7319		if ($next_data !== false) {
7320			$next_data['utimestamp'] = $date;
7321			array_push ($interval_data, $next_data);
7322		}
7323		else if (count ($interval_data) > 0) {
7324			// Propagate the last known data to the end of the interval
7325			$next_data = array_pop ($interval_data);
7326			array_push ($interval_data, $next_data);
7327			$next_data['utimestamp'] = $date;
7328			array_push ($interval_data, $next_data);
7329		}
7330	}
7331
7332	if (count ($interval_data) < 1) {
7333		return false;
7334	}
7335
7336	// Set initial conditions
7337	$min = $interval_data[0]['datos'];
7338
7339	switch ($config["dbtype"]) {
7340		case "mysql":
7341		case "postgresql":
7342			// Do none
7343			break;
7344		case "oracle":
7345			$min = oracle_format_float_to_php($min);
7346			break;
7347	}
7348
7349	foreach ($interval_data as $data) {
7350		switch ($config["dbtype"]) {
7351			case "mysql":
7352			case "postgresql":
7353				// Do none
7354				break;
7355			case "oracle":
7356				$data['datos'] =
7357					oracle_format_float_to_php($data['datos']);
7358				break;
7359		}
7360
7361		if ($data['datos'] < $min) {
7362			$min = $data['datos'];
7363		}
7364	}
7365
7366	return $min;
7367}
7368
7369/**
7370 * Get the sum of values of an agent module in a period of time.
7371 *
7372 * @param int Agent module id to get the sumatory.
7373 * @param int Period of time to check (in seconds)
7374 * @param int Top date to check the values. Default current time.
7375 *
7376 * @return float The sumatory of the module values in the interval.
7377 */
7378function reporting_get_agentmodule_data_sum ($id_agent_module,
7379	$period = 0, $date = 0) {
7380
7381	global $config;
7382
7383	// Initialize variables
7384	if (empty ($date)) $date = get_system_time ();
7385	$datelimit = $date - $period;
7386
7387	$search_in_history_db = db_search_in_history_db($datelimit);
7388
7389	$id_module_type = db_get_value ('id_tipo_modulo', 'tagente_modulo',
7390		'id_agente_modulo', $id_agent_module);
7391	$module_name = db_get_value ('nombre', 'ttipo_modulo', 'id_tipo',
7392		$id_module_type);
7393	$module_interval = modules_get_interval ($id_agent_module);
7394	$uncompressed_module = is_module_uncompressed ($module_name);
7395
7396	// Wrong module type
7397	if (is_module_data_string ($module_name)) {
7398		return 0;
7399	}
7400
7401	// Incremental modules are treated differently
7402	$module_inc = is_module_inc ($module_name);
7403
7404	// Get module data
7405	$interval_data = db_get_all_rows_sql('
7406			SELECT * FROM tagente_datos
7407			WHERE id_agente_modulo = ' . (int) $id_agent_module . '
7408				AND utimestamp > ' . (int) $datelimit . '
7409				AND utimestamp < ' . (int) $date . '
7410			ORDER BY utimestamp ASC', $search_in_history_db);
7411	if ($interval_data === false) $interval_data = array ();
7412
7413	// Uncompressed module data
7414	if ($uncompressed_module) {
7415		$min_necessary = 1;
7416
7417	// Compressed module data
7418	}
7419	else {
7420		// Get previous data
7421		$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
7422		if ($previous_data !== false) {
7423			$previous_data['utimestamp'] = $datelimit;
7424			array_unshift ($interval_data, $previous_data);
7425		}
7426
7427		// Get next data
7428		$next_data = modules_get_next_data ($id_agent_module, $date);
7429		if ($next_data !== false) {
7430			$next_data['utimestamp'] = $date;
7431			array_push ($interval_data, $next_data);
7432		}
7433		else if (count ($interval_data) > 0) {
7434			// Propagate the last known data to the end of the interval
7435			$next_data = array_pop ($interval_data);
7436			array_push ($interval_data, $next_data);
7437			$next_data['utimestamp'] = $date;
7438			array_push ($interval_data, $next_data);
7439		}
7440
7441		$min_necessary = 2;
7442	}
7443
7444	if (count ($interval_data) < $min_necessary) {
7445		return false;
7446	}
7447
7448	// Set initial conditions
7449	$total = 0;
7450	if (! $uncompressed_module) {
7451		$previous_data = array_shift ($interval_data);
7452	}
7453
7454	foreach ($interval_data as $data) {
7455		switch ($config["dbtype"]) {
7456			case "mysql":
7457			case "postgresql":
7458				// Do none
7459				break;
7460			case "oracle":
7461				$data['datos'] =
7462					oracle_format_float_to_php($data['datos']);
7463				break;
7464		}
7465
7466		if ($uncompressed_module) {
7467			$total += $data['datos'];
7468		}
7469		else if ($module_inc) {
7470			$total += $previous_data['datos'] * ($data['utimestamp'] - $previous_data['utimestamp']);
7471		}
7472		else {
7473			$total += $previous_data['datos'] * ($data['utimestamp'] - $previous_data['utimestamp']) / $module_interval;
7474		}
7475		$previous_data = $data;
7476	}
7477
7478	return $total;
7479}
7480
7481/**
7482 * Get the planned downtimes that affect the passed modules on an specific datetime range.
7483 *
7484 * @param int Start date in utimestamp.
7485 * @param int End date in utimestamp.
7486 * @param array The agent modules ids.
7487 *
7488 * @return Array with the planned downtimes that are executed in any moment of the range selected and affect the
7489 * agent modules selected.
7490 */
7491function reporting_get_planned_downtimes ($start_date, $end_date, $id_agent_modules = false) {
7492	global $config;
7493
7494	$start_time = date("H:i:s", $start_date);
7495	$end_time = date("H:i:s", $end_date);
7496
7497	$start_day = date("d", $start_date);
7498	$end_day = date("d", $end_date);
7499
7500	$start_month = date("m", $start_date);
7501	$end_month = date("m", $end_date);
7502
7503	if ($start_date > $end_date) {
7504		return false;
7505	}
7506
7507	if ($end_date - $start_date >= SECONDS_1MONTH) {
7508		// If the date range is larger than 1 month, every monthly planned downtime will be inside
7509		$periodically_monthly_w = "type_periodicity = 'monthly'";
7510	}
7511	else {
7512		// Check if the range is larger than the planned downtime execution, or if its start or end
7513		// is inside the planned downtime execution.
7514		// The start and end time is very important.
7515		$periodically_monthly_w = "type_periodicity = 'monthly'
7516									AND (((periodically_day_from > '$start_day'
7517												OR (periodically_day_from = '$start_day'
7518													AND periodically_time_from >= '$start_time'))
7519											AND (periodically_day_to < '$end_day'
7520												OR (periodically_day_to = '$end_day'
7521													AND periodically_time_to <= '$end_time')))
7522										OR ((periodically_day_from < '$start_day'
7523												OR (periodically_day_from = '$start_day'
7524													AND periodically_time_from <= '$start_time'))
7525											AND (periodically_day_to > '$start_day'
7526												OR (periodically_day_to = '$start_day'
7527													AND periodically_time_to >= '$start_time')))
7528										OR ((periodically_day_from < '$end_day'
7529												OR (periodically_day_from = '$end_day'
7530													AND periodically_time_from <= '$end_time'))
7531											AND (periodically_day_to > '$end_day'
7532												OR (periodically_day_to = '$end_day'
7533													AND periodically_time_to >= '$end_time'))))";
7534	}
7535
7536	$periodically_weekly_days = array();
7537	$date_aux = $start_date;
7538	$i = 0;
7539
7540	if (($end_date - $start_date) >= SECONDS_1WEEK) {
7541		// If the date range is larger than 7 days, every weekly planned downtime will be inside.
7542		for ($i = 0; $i < 7; $i++) {
7543			$weekday_actual = strtolower(date('l', $date_aux));
7544			$periodically_weekly_days[] = "($weekday_actual = 1)";
7545			$date_aux += SECONDS_1DAY;
7546		}
7547	}
7548	else if (($end_date - $start_date) <= SECONDS_1DAY && $start_day == $end_day) {
7549		// If the date range is smaller than 1 day, the start and end days can be equal or consecutive.
7550		// If they are equal, the execution times have to be contained in the date range times or contain
7551		// the start or end time of the date range.
7552		$weekday_actual = strtolower(date('l', $start_date));
7553		$periodically_weekly_days[] = "($weekday_actual = 1
7554			AND ((periodically_time_from > '$start_time' AND periodically_time_to < '$end_time')
7555				OR (periodically_time_from = '$start_time'
7556					OR (periodically_time_from < '$start_time'
7557						AND periodically_time_to >= '$start_time'))
7558				OR (periodically_time_from = '$end_time'
7559					OR (periodically_time_from < '$end_time'
7560						AND periodically_time_to >= '$end_time'))))";
7561	}
7562	else {
7563		while ($date_aux <= $end_date && $i < 7) {
7564
7565			$weekday_actual = strtolower(date('l', $date_aux));
7566			$day_num_actual = date('d', $date_aux);
7567
7568			if ($date_aux == $start_date) {
7569				$periodically_weekly_days[] = "($weekday_actual = 1 AND periodically_time_to >= '$start_time')";
7570			}
7571			else if ($day_num_actual == $end_day) {
7572				$periodically_weekly_days[] = "($weekday_actual = 1 AND periodically_time_from <= '$end_time')";
7573			}
7574			else {
7575				$periodically_weekly_days[] = "($weekday_actual = 1)";
7576			}
7577
7578			$date_aux += SECONDS_1DAY;
7579			$i++;
7580		}
7581	}
7582
7583	if (!empty($periodically_weekly_days)) {
7584		$periodically_weekly_w = "type_periodicity = 'weekly' AND (".implode(" OR ", $periodically_weekly_days).")";
7585		$periodically_condition = "(($periodically_monthly_w) OR ($periodically_weekly_w))";
7586	}
7587	else {
7588		$periodically_condition = "($periodically_monthly_w)";
7589	}
7590
7591	if ($id_agent_modules !== false) {
7592		if (empty($id_agent_modules))
7593			return array();
7594
7595		$id_agent_modules_str = implode(",", $id_agent_modules);
7596
7597		switch ($config["dbtype"]) {
7598			case "mysql":
7599			case "postgresql":
7600				$tpdr_description = "tpdr.description";
7601				break;
7602			case "oracle":
7603				$tpdr_description = "to_char(tpdr.description)";
7604				break;
7605		}
7606
7607		$sql_downtime = "
7608			SELECT
7609				DISTINCT(tpdr.id),
7610				tpdr.name,
7611				" . $tpdr_description . ",
7612				tpdr.date_from,
7613				tpdr.date_to,
7614				tpdr.executed,
7615				tpdr.id_group,
7616				tpdr.only_alerts,
7617				tpdr.monday,
7618				tpdr.tuesday,
7619				tpdr.wednesday,
7620				tpdr.thursday,
7621				tpdr.friday,
7622				tpdr.saturday,
7623				tpdr.sunday,
7624				tpdr.periodically_time_from,
7625				tpdr.periodically_time_to,
7626				tpdr.periodically_day_from,
7627				tpdr.periodically_day_to,
7628				tpdr.type_downtime,
7629				tpdr.type_execution,
7630				tpdr.type_periodicity,
7631				tpdr.id_user
7632			FROM (
7633					SELECT tpd.*
7634					FROM tplanned_downtime tpd, tplanned_downtime_agents tpda, tagente_modulo tam
7635					WHERE (tpd.id = tpda.id_downtime
7636							AND tpda.all_modules = 1
7637							AND tpda.id_agent = tam.id_agente
7638							AND tam.id_agente_modulo IN ($id_agent_modules_str))
7639						AND ((type_execution = 'periodically'
7640								AND $periodically_condition)
7641							OR (type_execution = 'once'
7642								AND ((date_from >= '$start_date' AND date_to <= '$end_date')
7643									OR (date_from <= '$start_date' AND date_to >= '$end_date')
7644									OR (date_from <= '$start_date' AND date_to >= '$start_date')
7645									OR (date_from <= '$end_date' AND date_to >= '$end_date'))))
7646				UNION ALL
7647					SELECT tpd.*
7648					FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm
7649					WHERE (tpd.id = tpdm.id_downtime
7650							AND tpdm.id_agent_module IN ($id_agent_modules_str))
7651						AND ((type_execution = 'periodically'
7652								AND $periodically_condition)
7653							OR (type_execution = 'once'
7654								AND ((date_from >= '$start_date' AND date_to <= '$end_date')
7655									OR (date_from <= '$start_date' AND date_to >= '$end_date')
7656									OR (date_from <= '$start_date' AND date_to >= '$start_date')
7657									OR (date_from <= '$end_date' AND date_to >= '$end_date'))))
7658			) tpdr
7659			ORDER BY tpdr.id";
7660	}
7661	else {
7662		$sql_downtime = "SELECT *
7663						FROM tplanned_downtime tpd, tplanned_downtime_modules tpdm
7664						WHERE (type_execution = 'periodically'
7665									AND $periodically_condition)
7666								OR (type_execution = 'once'
7667									AND ((date_from >= '$start_date' AND date_to <= '$end_date')
7668										OR (date_from <= '$start_date' AND date_to >= '$end_date')
7669										OR (date_from <= '$start_date' AND date_to >= '$start_date')
7670										OR (date_from <= '$end_date' AND date_to >= '$end_date')))";
7671	}
7672
7673	$downtimes = db_get_all_rows_sql($sql_downtime);
7674	if ($downtimes == false) {
7675		$downtimes = array();
7676	}
7677
7678	return $downtimes;
7679}
7680
7681/**
7682 * Get SLA of a module.
7683 *
7684 * @param int Agent module to calculate SLA
7685 * @param int Period to check the SLA compliance.
7686 * @param int Minimum data value the module in the right interval
7687 * @param int Maximum data value the module in the right interval. False will
7688 * ignore max value
7689 * @param int Beginning date of the report in UNIX time (current date by default).
7690 * @param array $dayWeek  Array of days week to extract as array('monday' => false, 'tuesday' => true....), and by default is null.
7691 * @param string $timeFrom Time in the day to start to extract in mysql format, by default null.
7692 * @param string $timeTo Time in the day to end to extract in mysql format, by default null.
7693 *
7694 * @return float SLA percentage of the requested module. False if no data were
7695 * found
7696 */
7697function reporting_get_agentmodule_sla_day ($id_agent_module, $period = 0, $min_value = 1, $max_value = false, $date = 0, $daysWeek = null, $timeFrom = null, $timeTo = null) {
7698	global $config;
7699
7700	if (empty($id_agent_module))
7701		return false;
7702
7703	// Initialize variables
7704	if (empty ($date)) {
7705		$date = get_system_time ();
7706	}
7707	if ($daysWeek === null) {
7708		$daysWeek = array();
7709	}
7710	// Limit date to start searching data
7711	$datelimit = $date - $period;
7712
7713	// Substract the not working time
7714	// Initialize the working time status machine ($wt_status)
7715	// Search the first data at worktime start
7716	list ($period_reduced, $wt_status, $datelimit_increased) = reporting_get_agentmodule_sla_day_period ($period, $date, $timeFrom, $timeTo);
7717	if ($period_reduced <= 0) {
7718		return false;
7719	}
7720
7721	$wt_points = reporting_get_agentmodule_sla_working_timestamp ($period, $date, $timeFrom, $timeTo);
7722
7723	$search_in_history_db = db_search_in_history_db($datelimit);
7724
7725	// Get interval data
7726	$sql = sprintf ('SELECT *
7727		FROM tagente_datos
7728		WHERE id_agente_modulo = %d
7729			AND utimestamp > %d
7730			AND utimestamp <= %d',
7731		$id_agent_module, $datelimit, $date);
7732
7733	//Add the working times (mon - tue - wed ...) and from time to time
7734	$days = array();
7735	//Translate to mysql week days
7736	if ($daysWeek) {
7737		foreach ($daysWeek as $key => $value) {
7738			if (!$value) {
7739				if ($key == 'monday') {
7740					$days[] = 2;
7741				}
7742				if ($key == 'tuesday') {
7743					$days[] = 3;
7744				}
7745				if ($key == 'wednesday') {
7746					$days[] = 4;
7747				}
7748				if ($key == 'thursday') {
7749					$days[] = 5;
7750				}
7751				if ($key == 'friday') {
7752					$days[] = 6;
7753				}
7754				if ($key == 'saturday') {
7755					$days[] = 7;
7756				}
7757				if ($key == 'sunday') {
7758					$days[] = 1;
7759				}
7760			}
7761		}
7762	}
7763
7764	/* The not working time consideration is now doing in foreach loop above
7765	switch ($config["dbtype"]) {
7766		case "mysql":
7767		case "postgresql":
7768			if (count($days) > 0) {
7769				$sql .= ' AND DAYOFWEEK(FROM_UNIXTIME(utimestamp)) NOT IN (' . implode(',', $days) . ')';
7770			}
7771			if ($timeFrom < $timeTo) {
7772				$sql .= ' AND (TIME(FROM_UNIXTIME(utimestamp)) >= "' . $timeFrom . '" AND TIME(FROM_UNIXTIME(utimestamp)) <= "'. $timeTo . '")';
7773			}
7774			elseif ($timeFrom > $timeTo) {
7775				$sql .= ' AND (TIME(FROM_UNIXTIME(utimestamp)) >= "' . $timeFrom . '" OR TIME(FROM_UNIXTIME(utimestamp)) <= "'. $timeTo . '")';
7776			}
7777			break;
7778		case "oracle":
7779			break;
7780	}
7781	* */
7782
7783
7784	$sql .= ' ORDER BY utimestamp ASC';
7785	$interval_data = db_get_all_rows_sql ($sql, $search_in_history_db);
7786
7787	if ($interval_data === false) {
7788		$interval_data = array ();
7789	}
7790
7791	// Calculate planned downtime dates
7792	$downtime_dates =
7793		reporting_get_planned_downtimes_intervals($id_agent_module, $datelimit, $date);
7794
7795	// Get previous data
7796	$previous_data = modules_get_previous_data($id_agent_module, $datelimit + $datelimit_increased);
7797
7798	if ($previous_data !== false) {
7799		$previous_data['utimestamp'] = $datelimit + $datelimit_increased;
7800		array_unshift ($interval_data, $previous_data);
7801	} else if (count ($interval_data) > 0) {
7802		// Propagate undefined status to first time point
7803		$first_interval_time = array_shift ($interval_data);
7804		$previous_point = $datelimit + $datelimit_increased;
7805		$point = $datelimit + $datelimit_increased;
7806		// Remove rebased points and substract time only on working time
7807		while ($wt_points[0] <= $first_interval_time['utimestamp']) {
7808			$point = array_shift ($wt_points);
7809			if ($wt_status){
7810				$period_reduced -= $point - $previous_point;
7811			}
7812			$wt_status = !$wt_status;
7813			$previous_point = $point;
7814		}
7815		if ($wt_status){
7816			$period_reduced -= $first_interval_time['utimestamp'] - $point;
7817		}
7818		array_unshift ($interval_data, $first_interval_time);
7819	}
7820
7821	if (count ($wt_points) < 2) {
7822		return false;
7823	}
7824
7825	// Get next data
7826	$next_data = modules_get_next_data ($id_agent_module, $date);
7827
7828	if ($next_data !== false) {
7829		$next_data['utimestamp'] = $date;
7830		array_push ($interval_data, $next_data);
7831	}
7832	else if (count ($interval_data) > 0) {
7833		// Propagate the last known data to the end of the interval
7834		$next_data = array_pop ($interval_data);
7835		array_push ($interval_data, $next_data);
7836		$next_data['utimestamp'] = $date;
7837		array_push ($interval_data, $next_data);
7838	}
7839
7840	if (count ($interval_data) < 2) {
7841		return false;
7842	}
7843
7844	// Set initial conditions
7845	$bad_period = 0;
7846	$first_data = array_shift ($interval_data);
7847
7848	// Do not count the empty start of an interval as 0
7849	if ($first_data['utimestamp'] != $datelimit) {
7850		$period = $date - $first_data['utimestamp'];
7851	}
7852
7853	$previous_utimestamp = $first_data['utimestamp'];
7854	if ((($max_value > $min_value AND ($first_data['datos'] > $max_value OR $first_data['datos'] < $min_value))) OR
7855		($max_value <= $min_value AND $first_data['datos'] < $min_value)) {
7856
7857		$previous_status = 1;
7858		foreach ($downtime_dates as $date_dt) {
7859			if (($date_dt['date_from'] <= $previous_utimestamp) AND ($date_dt['date_to'] >= $previous_utimestamp)) {
7860				$previous_status = 0;
7861			}
7862		}
7863	}
7864	else {
7865		$previous_status = 0;
7866	}
7867
7868
7869
7870	foreach ($interval_data as $data) {
7871		// Test if working time is changed
7872		while ($wt_points[0] <= $data['utimestamp']) {
7873			$intermediate_point = array_shift($wt_points);
7874			if ($wt_status && ($previous_status == 1)) {
7875				$bad_period += $intermediate_point - $previous_utimestamp;
7876			}
7877			$previous_utimestamp = $intermediate_point;
7878			$wt_status = !$wt_status;
7879		}
7880
7881		// Increses bad_period only if it is working time
7882		if ($wt_status && ($previous_status == 1)) {
7883			$bad_period += $data['utimestamp'] - $previous_utimestamp;
7884		}
7885
7886		if (array_key_exists('datos', $data)) {
7887			// Re-calculate previous status for the next data
7888			if ((($max_value > $min_value AND ($data['datos'] > $max_value OR $data['datos'] < $min_value))) OR
7889				($max_value <= $min_value AND $data['datos'] < $min_value)) {
7890
7891				$previous_status = 1;
7892				foreach ($downtime_dates as $date_dt) {
7893					if (($date_dt['date_from'] <= $data['utimestamp']) AND ($date_dt['date_to'] >= $data['utimestamp'])) {
7894						$previous_status = 0;
7895					}
7896				}
7897			}
7898			else {
7899				$previous_status = 0;
7900			}
7901		}
7902
7903		$previous_utimestamp = $data['utimestamp'];
7904	}
7905
7906
7907	// Return the percentage of SLA compliance
7908	return (float) (100 - ($bad_period / $period_reduced) * 100);
7909}
7910
7911/**
7912 * Get several SLA data for an agentmodule within a period divided on subperiods
7913 *
7914 * @param int Agent module to calculate SLA
7915 * @param int Period to check the SLA compliance.
7916 * @param int Minimum data value the module in the right interval
7917 * @param int Maximum data value the module in the right interval. False will
7918 * ignore max value
7919 * @param array $days Array of days week to extract as array('monday' => false, 'tuesday' => true....), and by default is null.
7920 * @param string $timeFrom Time in the day to start to extract in mysql format, by default null.
7921 * @param string $timeTo Time in the day to end to extract in mysql format, by default null.
7922 *
7923 * @return Array with values either 1, 2, 3 or 4 depending if the SLA percentage for this subperiod
7924 * is within the sla limits, on the edge, outside or with an unknown value.
7925 */
7926function reporting_get_agentmodule_sla_array ($id_agent_module, $period = 0, $min_value = 1, $max_value = false, $date = 0, $daysWeek = null, $timeFrom = null, $timeTo = null) {
7927	global $config;
7928
7929	if (empty($id_agent_module))
7930		return false;
7931
7932	// Initialize variables
7933	if (empty ($date)) {
7934		$date = get_system_time ();
7935	}
7936	if ($daysWeek === null) {
7937		$daysWeek = array();
7938	}
7939
7940	// Hotfix: The edge values are confuse to the users
7941	$percent = 0;
7942
7943	// Limit date to start searching data
7944	$datelimit = $date - $period;
7945
7946	$search_in_history_db = db_search_in_history_db($datelimit);
7947
7948	// Get interval data
7949	$sql = sprintf ('SELECT * FROM tagente_datos
7950		WHERE id_agente_modulo = %d
7951			AND utimestamp > %d AND utimestamp <= %d',
7952		$id_agent_module, $datelimit, $date);
7953
7954	//Add the working times (mon - tue - wed ...) and from time to time
7955	$days = array();
7956	//Translate to mysql week days
7957
7958	if ($daysWeek) {
7959		foreach ($daysWeek as $key => $value) {
7960			if (!$value) {
7961				if ($key == 'monday') {
7962					$days[] = 2;
7963				}
7964				if ($key == 'tuesday') {
7965					$days[] = 3;
7966				}
7967				if ($key == 'wednesday') {
7968					$days[] = 4;
7969				}
7970				if ($key == 'thursday') {
7971					$days[] = 5;
7972				}
7973				if ($key == 'friday') {
7974					$days[] = 6;
7975				}
7976				if ($key == 'saturday') {
7977					$days[] = 7;
7978				}
7979				if ($key == 'sunday') {
7980					$days[] = 1;
7981				}
7982			}
7983		}
7984	}
7985
7986	if (count($days) > 0) {
7987		$sql .= ' AND DAYOFWEEK(FROM_UNIXTIME(utimestamp)) NOT IN (' . implode(',', $days) . ')';
7988	}
7989
7990	if ($timeFrom != $timeTo) {
7991		if ($timeFrom < $timeTo) {
7992			$sql .= ' AND (TIME(FROM_UNIXTIME(utimestamp)) >= \'' .
7993				$timeFrom . '\'
7994				AND TIME(FROM_UNIXTIME(utimestamp)) <= \'' .
7995				$timeTo . '\')';
7996		}
7997		elseif ($timeFrom > $timeTo) {
7998			$sql .= ' AND (TIME(FROM_UNIXTIME(utimestamp)) >= \'' .
7999				$timeFrom . '\'
8000				OR TIME(FROM_UNIXTIME(utimestamp)) <= \''.
8001				$timeTo . '\')';
8002		}
8003	}
8004
8005	$sql .= ' ORDER BY utimestamp ASC';
8006	$interval_data = db_get_all_rows_sql ($sql, $search_in_history_db);
8007
8008	if ($interval_data === false) {
8009		$interval_data = array ();
8010	}
8011
8012
8013	// Indexing data
8014	$interval_data_indexed = array();
8015	foreach($interval_data as $idata) {
8016		$interval_data_indexed[$idata['utimestamp']]['data'] = $idata['datos'];
8017	}
8018
8019	//-----------Calculate unknown status events------------------------
8020	$events_unknown = db_get_all_rows_filter ('tevento',
8021		array ('id_agentmodule' => $id_agent_module,
8022			"utimestamp > $datelimit",
8023			"utimestamp < $date",
8024			'order' => 'utimestamp ASC'),
8025		array ('id_evento', 'evento', 'timestamp', 'utimestamp', 'event_type'));
8026
8027	if ($events_unknown === false) {
8028		$events_unknown = array ();
8029	}
8030
8031	// Add unknown periods to data
8032	for ($i = 0; isset($events_unknown[$i]); $i++) {
8033		$eu = $events_unknown[$i];
8034
8035		if ($eu['event_type'] == 'going_unknown') {
8036			$interval_data_indexed[$eu['utimestamp']]['data'] = 0;
8037			$interval_data_indexed[$eu['utimestamp']]['status'] = 4;
8038
8039			// Search the corresponding recovery event.
8040			for ($j = $i+1; isset($events_unknown[$j]); $j++) {
8041				$eu = $events_unknown[$j];
8042
8043				if ($eu['event_type'] != 'going_unknown' && substr ($eu['event_type'], 0, 5) == 'going') {
8044					$interval_data_indexed[$eu['utimestamp']]['data'] = 0;
8045					$interval_data_indexed[$eu['utimestamp']]['status'] = 6;
8046
8047					// Do not process read events again.
8048					$i = $j;
8049					break;
8050				}
8051			}
8052		}
8053	}
8054
8055	// Get the last event before inverval to know if graph start on unknown
8056	$prev_event = db_get_row_filter ('tevento',
8057		array ('id_agentmodule' => $id_agent_module,
8058			"utimestamp <= $datelimit",
8059			'order' => 'utimestamp DESC'));
8060	if (isset($prev_event['event_type']) && $prev_event['event_type'] == 'going_unknown') {
8061		$start_unknown = true;
8062	}
8063	else {
8064		$start_unknown = false;
8065	}
8066	//------------------------------------------------------------------
8067
8068	//-----------------Set limits of the interval-----------------------
8069	// Get previous data (This adds the first data if the begin of module data is after the begin time interval)
8070	$previous_data = modules_get_previous_data ($id_agent_module, $datelimit);
8071	if ($previous_data !== false ) {
8072		$previous_value = $previous_data['datos'];
8073		// if ((($previous_value > ($min_value - $percent)) && ($previous_value < ($min_value + $percent))) ||
8074		// 		(($previous_value > ($max_value - $percent)) && ($previous_value < ($max_value + $percent)))) {//2 when value is within the edges
8075		// 	$previous_known_status = 2;
8076		// }
8077		// else
8078		if (($previous_value >= ($min_value + $percent)) && ($previous_value <= ($max_value - $percent))) { //1 when value is OK
8079			$previous_known_status = 1;
8080		}
8081		elseif (($previous_value <= ($min_value - $percent)) || ($previous_value >= ($max_value + $percent))) { //3 when value is Wrong
8082			$previous_known_status = 3;
8083		}
8084	}
8085
8086	// If the starting of the graph is unknown we set it
8087	if ($start_unknown) {
8088		$interval_data_indexed[$datelimit]['data'] = 0;
8089		$interval_data_indexed[$datelimit]['status'] = 4;
8090	}
8091	else {
8092		if ($previous_data !== false ) {
8093			$interval_data_indexed[$datelimit]['data'] = $previous_data['datos'];
8094		}
8095		else { // If there are not data befor interval set unknown
8096			$interval_data_indexed[$datelimit]['data'] = 0;
8097			$interval_data_indexed[$datelimit]['status'] = 4;
8098			$previous_known_status = 1; // Assume the module was in normal status if there is no previous data.
8099		}
8100	}
8101
8102	// Get next data (This adds data before the interval of the report)
8103	$next_data = modules_get_next_data ($id_agent_module, $date);
8104
8105	if ($next_data !== false) {
8106		$interval_data_indexed[$date]['data'] = $previous_data['datos'];
8107	}
8108	else if (count ($interval_data_indexed) > 0) {
8109		// Propagate the last known data to the end of the interval (if there is no module data at the end point)
8110		ksort($interval_data_indexed);
8111		$last_data = end($interval_data_indexed);
8112		$interval_data_indexed[$date] = $last_data;
8113	}
8114
8115	//------------------------------------------------------------------
8116
8117	//--------Calculate planned downtime dates--------------------------
8118	$downtime_dates = reporting_get_planned_downtimes_intervals($id_agent_module, $datelimit, $date);
8119
8120	foreach ($downtime_dates as $downtime_date) {
8121		// Delete data of the planned downtime and put the last data on the upper limit
8122		$interval_data_indexed[$downtime_date['date_from']]['data'] = 0;
8123		$interval_data_indexed[$downtime_date['date_from']]['status'] = 5;
8124		$interval_data_indexed[$downtime_date['date_to']]['data'] = 0;
8125		$interval_data_indexed[$downtime_date['date_to']]['status'] = 4;
8126
8127		$last_downtime_data = false;
8128		foreach ($interval_data_indexed as $idi_timestamp => $idi) {
8129			if ($idi_timestamp != $downtime_date['date_from'] && $idi_timestamp != $downtime_date['date_to'] &&
8130					$idi_timestamp >= $downtime_date['date_from'] && $idi_timestamp <= $downtime_date['date_to']) {
8131				$last_downtime_data = $idi['data'];
8132				unset($interval_data_indexed[$idi_timestamp]);
8133			}
8134		}
8135
8136		// Set the last data of the interval as limit
8137		if ($last_downtime_data !== false) {
8138			$interval_data_indexed[$downtime_date['date_to']]['data'] = $last_downtime_data;
8139		}
8140	}
8141	//------------------------------------------------------------------
8142
8143	// Sort the array
8144	ksort($interval_data_indexed);
8145
8146	// We need more or equal two points
8147	if (count ($interval_data_indexed) < 2) {
8148		return false;
8149	}
8150
8151	//Get the percentage for the limits
8152	$diff = $max_value - $min_value;
8153
8154	// Get module type
8155	$id_module_type = db_get_value('id_tipo_modulo', 'tagente_modulo', 'id_agente_modulo', $id_agent_module);
8156	// If module is boolean don't create translation intervals (on the edge intervals)
8157	// if ($id_module_type == 2 or $id_module_type == 6 or $id_module_type == 9 or $id_module_type == 18) {
8158	//      $percent = 0;
8159	// }
8160	// else {
8161	//      // Getting 10% of $diff --> $percent = ($diff/100)*10, so...
8162	//      $percent = $diff / 10;
8163	// }
8164
8165	//Set initial conditions
8166	$first_data = array_shift ($interval_data);
8167	$previous_utimestamp = $date - $period;
8168
8169	$previous_value = $first_data ['datos'];
8170	$previous_status = 0;
8171
8172	if (isset($first_data['status'])) {
8173		// 4 for the Unknown value and 5 for planned downtime
8174		$previous_status = $first_data['status'];
8175	}
8176	// elseif ((($previous_value > ($min_value - $percent)) && ($previous_value < ($min_value + $percent))) ||
8177	// 		(($previous_value > ($max_value - $percent)) && ($previous_value < ($max_value + $percent)))) {//2 when value is within the edges
8178	// 	$previous_status = 2;
8179	// }
8180	elseif (($previous_value >= ($min_value + $percent)) && ($previous_value <= ($max_value - $percent))) { //1 when value is OK
8181		$previous_status = 1;
8182	}
8183	elseif (($previous_value <= ($min_value - $percent)) || ($previous_value >= ($max_value + $percent))) { //3 when value is Wrong
8184		$previous_status = 3;
8185	}
8186
8187	$data_colors = array();
8188	$i = 0;
8189
8190	foreach ($interval_data_indexed as $utimestamp => $data) {
8191		$change = false;
8192		$value = $data['data'];
8193		if (isset($data['status'])) {
8194			// Leaving unkown status.
8195			if ($data['status'] == 6) {
8196				$status = $previous_known_status;
8197			}
8198			// 4 unknown, 5 planned downtime.
8199			else {
8200				$status = $data['status'];
8201			}
8202		}
8203		// elseif ((($value > ($min_value - $percent)) && ($value < ($min_value + $percent))) ||
8204		// 		(($value > ($max_value - $percent)) && ($value < ($max_value + $percent)))) { //2 when value is within the edges
8205		// 	$status = 2;
8206		// }
8207		elseif (($value >= ($min_value + $percent)) && ($value <= ($max_value - $percent))) { //1 when value is OK
8208			$status = 1;
8209		}
8210		elseif (($value <= ($min_value - $percent)) || ($value >= ($max_value + $percent))) { //3 when value is Wrong
8211			$status = 3;
8212		}
8213
8214		if ($status != $previous_status) {
8215			$change = true;
8216			$data_colors[$i]['data'] = $previous_status;
8217			$data_colors[$i]['utimestamp'] = $utimestamp - $previous_utimestamp;
8218			$i++;
8219			$previous_status = $status;
8220			$previous_utimestamp = $utimestamp;
8221		}
8222
8223		// Save the last known status.
8224		if ($status <= 3) {
8225			$previous_known_status = $status;
8226		}
8227	}
8228	if ($change == false) {
8229		$data_colors[$i]['data'] = $previous_status;
8230		$data_colors[$i]['utimestamp'] = $date - $previous_utimestamp;
8231	}
8232
8233	return $data_colors;
8234}
8235
8236function reporting_get_stats_servers($tiny = true) {
8237	global $config;
8238
8239	$server_performance = servers_get_performance();
8240
8241	// Alerts table
8242	$table_srv = html_get_predefined_table();
8243
8244	$table_srv->style[0] = $table_srv->style[2] = 'text-align: right; padding: 5px;';
8245	$table_srv->style[1] = $table_srv->style[3] = 'text-align: left; padding: 5px;';
8246
8247	$tdata = array();
8248	$tdata[0] = html_print_image('images/module.png', true, array('title' => __('Total running modules'), 'width' => '25px'));
8249	$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_modules"]) . '</span>';
8250
8251	$tdata[2] = '<span class="med_data">' . format_numeric($server_performance ["total_modules_rate"], 2) . '</span>';
8252	$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8253
8254	$table_srv->rowclass[] = '';
8255	$table_srv->data[] = $tdata;
8256
8257	$tdata = array();
8258	$tdata[0] = '<hr style="border: 0; height: 1px; background: #DDD">';
8259	$table_srv->colspan[count($table_srv->data)][0] = 4;
8260	$table_srv->rowclass[] = '';
8261	$table_srv->data[] = $tdata;
8262
8263	$tdata = array();
8264	$tdata[0] = html_print_image('images/database.png', true, array('title' => __('Local modules'), 'width' => '25px'));
8265	$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_local_modules"]) . '</span>';
8266
8267	$tdata[2] = '<span class="med_data">' .
8268		format_numeric($server_performance ["local_modules_rate"], 2) . '</span>';
8269	$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8270
8271	$table_srv->rowclass[] = '';
8272	$table_srv->data[] = $tdata;
8273
8274	if ($tiny) {
8275		$tdata = array();
8276		$tdata[0] = html_print_image('images/network.png', true, array('title' => __('Remote modules'), 'width' => '25px'));
8277		$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_remote_modules"]) . '</span>';
8278
8279		$tdata[2] = '<span class="med_data">' . format_numeric($server_performance ["remote_modules_rate"], 2) . '</span>';
8280		$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8281
8282		$table_srv->rowclass[] = '';
8283		$table_srv->data[] = $tdata;
8284	}
8285	else {
8286		if (isset($server_performance ["total_network_modules"])) {
8287			$tdata = array();
8288			$tdata[0] = html_print_image('images/network.png', true, array('title' => __('Network modules'), 'width' => '25px'));
8289			$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_network_modules"]) . '</span>';
8290
8291			$tdata[2] = '<span class="med_data">' .
8292				format_numeric($server_performance["network_modules_rate"], 2) .
8293				'</span>';
8294			$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8295
8296			$table_srv->rowclass[] = '';
8297			$table_srv->data[] = $tdata;
8298		}
8299
8300		if (isset($server_performance ["total_plugin_modules"])) {
8301			$tdata = array();
8302			$tdata[0] = html_print_image('images/plugin.png', true, array('title' => __('Plugin modules'), 'width' => '25px'));
8303			$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_plugin_modules"]) . '</span>';
8304
8305			$tdata[2] = '<span class="med_data">' . format_numeric($server_performance ["plugin_modules_rate"], 2) . '</span>';
8306			$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8307
8308			$table_srv->rowclass[] = '';
8309			$table_srv->data[] = $tdata;
8310		}
8311
8312		if (isset($server_performance ["total_prediction_modules"])) {
8313			$tdata = array();
8314			$tdata[0] = html_print_image('images/chart_bar.png', true, array('title' => __('Prediction modules'), 'width' => '25px'));
8315			$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_prediction_modules"]) . '</span>';
8316
8317			$tdata[2] = '<span class="med_data">' . format_numeric($server_performance ["prediction_modules_rate"], 2) . '</span>';
8318			$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8319
8320			$table_srv->rowclass[] = '';
8321			$table_srv->data[] = $tdata;
8322		}
8323
8324		if (isset($server_performance ["total_wmi_modules"])) {
8325			$tdata = array();
8326			$tdata[0] = html_print_image('images/wmi.png', true, array('title' => __('WMI modules'), 'width' => '25px'));
8327			$tdata[1] = '<span class="big_data">' . format_numeric($server_performance ["total_wmi_modules"]) . '</span>';
8328
8329			$tdata[2] = '<span class="med_data">' . format_numeric($server_performance ["wmi_modules_rate"], 2) . '</span>';
8330			$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8331
8332			$table_srv->rowclass[] = '';
8333			$table_srv->data[] = $tdata;
8334		}
8335
8336		if (isset($server_performance ["total_web_modules"])) {
8337			$tdata = array();
8338			$tdata[0] = html_print_image('images/world.png', true, array('title' => __('Web modules'), 'width' => '25px'));
8339			$tdata[1] = '<span class="big_data">' .
8340				format_numeric($server_performance ["total_web_modules"]) .
8341				'</span>';
8342
8343			$tdata[2] = '<span class="med_data">' .
8344				format_numeric($server_performance ["web_modules_rate"], 2) .
8345				'</span>';
8346			$tdata[3] = html_print_image('images/module.png', true, array('title' => __('Ratio') . ': ' . __('Modules by second'), 'width' => '16px')) . '/sec </span>';
8347
8348			$table_srv->rowclass[] = '';
8349			$table_srv->data[] = $tdata;
8350		}
8351
8352		$tdata = array();
8353		$tdata[0] = '<hr style="border: 0; height: 1px; background: #DDD">';
8354		$table_srv->colspan[count($table_srv->data)][0] = 4;
8355		$table_srv->rowclass[] = '';
8356		$table_srv->data[] = $tdata;
8357
8358
8359		switch ($config["dbtype"]) {
8360			case "mysql":
8361				$system_events = db_get_value_sql(
8362					'SELECT SQL_NO_CACHE COUNT(id_evento)
8363					FROM tevento');
8364				break;
8365			case "postgresql":
8366			case "oracle":
8367				$system_events = db_get_value_sql(
8368					'SELECT COUNT(id_evento)
8369					FROM tevento');
8370				break;
8371		}
8372
8373
8374
8375		$tdata = array();
8376		$tdata[0] = html_print_image('images/lightning_go.png', true,
8377			array('title' => __('Total events'), 'width' => '25px'));
8378		$tdata[1] = '<span class="big_data">' .
8379			format_numeric($system_events) . '</span>';
8380
8381		$table_srv->colspan[count($table_srv->data)][1] = 3;
8382		$table_srv->rowclass[] = '';
8383		$table_srv->data[] = $tdata;
8384	}
8385
8386	$output = '<fieldset class="databox tactical_set">
8387				<legend>' .
8388					__('Server performance') .
8389				'</legend>' .
8390				html_print_table($table_srv, true) . '</fieldset>';
8391
8392	return $output;
8393}
8394
8395/**
8396 * Get all the template graphs a user can see.
8397 *
8398 * @param $id_user User id to check.
8399 * @param $only_names Wheter to return only graphs names in an associative array
8400 * or all the values.
8401 * @param $returnAllGroup Wheter to return graphs of group All or not.
8402 * @param $privileges Privileges to check in user group
8403 *
8404 * @return template graphs of a an user. Empty array if none.
8405 */
8406function reporting_template_graphs_get_user ($id_user = 0, $only_names = false, $returnAllGroup = true, $privileges = 'RR') {
8407	global $config;
8408
8409	if (!$id_user) {
8410		$id_user = $config['id_user'];
8411	}
8412
8413	$groups = users_get_groups ($id_user, $privileges, $returnAllGroup);
8414
8415	$all_templates = db_get_all_rows_in_table ('tgraph_template', 'name');
8416	if ($all_templates === false)
8417		return array ();
8418
8419	$templates = array ();
8420	foreach ($all_templates as $template) {
8421		if (!in_array($template['id_group'], array_keys($groups)))
8422			continue;
8423
8424		if ($template["id_user"] != $id_user && $template['private'])
8425			continue;
8426
8427		if ($template["id_group"] > 0)
8428			if (!isset($groups[$template["id_group"]])) {
8429				continue;
8430			}
8431
8432		if ($only_names) {
8433			$templates[$template['id_graph_template']] = $template['name'];
8434		}
8435		else {
8436			$templates[$template['id_graph_template']] = $template;
8437			$templatesCount = db_get_value_sql("SELECT COUNT(id_gs_template) FROM tgraph_source_template WHERE id_template = " . $template['id_graph_template']);
8438			$templates[$template['id_graph_template']]['graphs_template_count'] = $templatesCount;
8439		}
8440	}
8441
8442	return $templates;
8443}
8444
8445/**
8446 * Get a human readable representation of the planned downtime date.
8447 *
8448 * @param array $planned_downtime Planned downtime row.
8449 *
8450 * @return string Representation of the date.
8451 */
8452function reporting_format_planned_downtime_dates ($planned_downtime) {
8453	$dates = '';
8454
8455	if (!isset($planned_downtime) || !isset($planned_downtime['type_execution']))
8456		return '';
8457
8458	switch ($planned_downtime['type_execution']) {
8459		case 'once':
8460			$dates = date ("Y-m-d H:i", $planned_downtime['date_from']) .
8461				"&nbsp;" . __('to') . "&nbsp;".
8462				date ("Y-m-d H:i", $planned_downtime['date_to']);
8463			break;
8464		case 'periodically':
8465			if (!isset($planned_downtime['type_periodicity']))
8466				return '';
8467
8468			switch ($planned_downtime['type_periodicity']) {
8469				case 'weekly':
8470					$dates = __('Weekly:');
8471					$dates .= "&nbsp;";
8472					if ($planned_downtime['monday']) {
8473						$dates .= __('Mon');
8474						$dates .= "&nbsp;";
8475					}
8476					if ($planned_downtime['tuesday']) {
8477						$dates .= __('Tue');
8478						$dates .= "&nbsp;";
8479					}
8480					if ($planned_downtime['wednesday']) {
8481						$dates .= __('Wed');
8482						$dates .= "&nbsp;";
8483					}
8484					if ($planned_downtime['thursday']) {
8485						$dates .= __('Thu');
8486						$dates .= "&nbsp;";
8487					}
8488					if ($planned_downtime['friday']) {
8489						$dates .= __('Fri');
8490						$dates .= "&nbsp;";
8491					}
8492					if ($planned_downtime['saturday']) {
8493						$dates .= __('Sat');
8494						$dates .= "&nbsp;";
8495					}
8496					if ($planned_downtime['sunday']) {
8497						$dates .= __('Sun');
8498						$dates .= "&nbsp;";
8499					}
8500					$dates .= "&nbsp;(" . $planned_downtime['periodically_time_from'];
8501					$dates .= "-" . $planned_downtime['periodically_time_to'] . ")";
8502					break;
8503				case 'monthly':
8504					$dates = __('Monthly:') . "&nbsp;";
8505					$dates .= __('From day') . "&nbsp;" . $planned_downtime['periodically_day_from'];
8506					$dates .= "&nbsp;" . strtolower(__('To day')) . "&nbsp;";
8507					$dates .= $planned_downtime['periodically_day_to'];
8508					$dates .= "&nbsp;(" . $planned_downtime['periodically_time_from'];
8509					$dates .= "-" . $planned_downtime['periodically_time_to'] . ")";
8510					break;
8511			}
8512			break;
8513	}
8514
8515	return $dates;
8516}
8517
8518/**
8519 * Get real period in SLA subtracting worktime period.
8520 * Get if is working in the first point
8521 * Get time between first point and
8522 *
8523 * @param int Period to check the SLA compliance.
8524 * @param int Date_end date end the sla compliace interval
8525 * @param int Working Time start
8526 * @param int Working Time end
8527 *
8528 * @return array (int fixed SLA period, bool inside working time)
8529 * found
8530 */
8531function reporting_get_agentmodule_sla_day_period ($period, $date_end, $wt_start = "00:00:00", $wt_end = "23:59:59") {
8532
8533	$date_start = $date_end - $period;
8534	// Converts to timestamp
8535	$human_date_end = date ('H:i:s', $date_end);
8536	$human_date_start = date ('H:i:s', $date_start);
8537	// Store into an array the points
8538	// "s" start SLA interval point
8539	// "e" end SLA interval point
8540	// "f" start worktime interval point (from)
8541	// "t" end worktime interval point (to)
8542	$tp = array (
8543		"s" => strtotime($human_date_start),
8544		"e" => strtotime($human_date_end),
8545		"f" => strtotime($wt_start),
8546		"t" => strtotime($wt_end)
8547	);
8548
8549	asort ($tp);
8550	$order = "";
8551	foreach ($tp as $type => $time) {
8552		$order .= $type;
8553	}
8554
8555	$period_reduced = $period;
8556	$start_working = true;
8557	$datelimit_increased = 0;
8558
8559	//Special case. If $order = "seft" and start time == end time it should be treated like "esft"
8560	if (($period > 0) and ($human_date_end == $human_date_start) and ($order == "seft")) {
8561		$order = "esft";
8562	}
8563
8564	// Discriminates the cases depends what time point is higher than other
8565	switch ($order) {
8566
8567		case "setf":
8568		case "etfs":
8569		case "tfse":
8570		case "fset":
8571			// Default $period_reduced
8572			// Default $start_working
8573			// Default $datelimit_increased
8574			break;
8575		case "stef":
8576		case "tefs":
8577		case "fste":
8578			$period_reduced =  $period - ($tp["e"] - $tp["t"]);
8579			// Default $start_working
8580			// Default $datelimit_increased
8581			break;
8582		case "stfe":
8583		case "estf":
8584		case "tfes":
8585			$period_reduced = $period - ($tp["f"] -$tp["t"]);
8586			// Default $start_working
8587			// Default $datelimit_increased
8588			break;
8589		case "tsef":
8590		case "seft":
8591		case "ftse":
8592		case "efts":
8593			$period_reduced = -1;
8594			$start_working = false;
8595			// Default $datelimit_increased
8596			break;
8597		case "tsfe":
8598		case "etsf":
8599		case "sfet":
8600			$period_reduced = $period - ($tp["f"] - $tp["s"]);
8601			$start_working = false;
8602			$datelimit_increased = $tp["f"] - $tp["s"];
8603			break;
8604		case "efst":
8605			$period_reduced = $tp["t"] - $tp["s"];
8606			// Default $start_working
8607			// Default $datelimit_increased
8608			break;
8609		case "fest":
8610			$period_reduced = ($tp["t"] - $tp["s"]) + ($tp["e"] - $tp["f"]);
8611			// Default $start_working
8612			// Default $datelimit_increased
8613			break;
8614		case "tesf":
8615			$period_reduced = SECONDS_1DAY - ($tp["f"] - $tp["t"]);
8616			$start_working = false;
8617			$datelimit_increased = $tp["f"] - $tp["s"];
8618			break;
8619		case "sfte":
8620		case "esft":
8621			$period_reduced = $tp["t"] - $tp["f"];
8622			$start_working = false;
8623			$datelimit_increased = $tp["f"] - $tp["s"];
8624			break;
8625		case "ftes":
8626			$period_reduced = $tp["t"] - $tp["f"];
8627			$start_working = false;
8628			$datelimit_increased = $tp["f"] + SECONDS_1DAY - $tp["s"];
8629			break;
8630		case "fets":
8631			$period_reduced = $tp["e"] - $tp["f"];
8632			$start_working = false;
8633			$datelimit_increased = $tp["f"] + SECONDS_1DAY - $tp["s"];
8634			break;
8635		default:
8636			// Default $period_reduced
8637			// Default $start_working
8638			// Default $datelimit_increased
8639			break;
8640	}
8641
8642	return array ($period_reduced, $start_working, $datelimit_increased);
8643}
8644
8645/**
8646 * Get working time SLA in timestamp form. Get all items and discard previous not necessaries
8647 *
8648 * @param int Period to check the SLA compliance.
8649 * @param int Date_end date end the sla compliace interval
8650 * @param int Working Time start
8651 * @param int Working Time end
8652 *
8653 * @return array work time points
8654 * found
8655 */
8656function reporting_get_agentmodule_sla_working_timestamp ($period, $date_end, $wt_start = "00:00:00", $wt_end = "23:59:59") {
8657
8658	$date_previous_day = $date_end - SECONDS_1DAY;
8659	$wt = array ();
8660
8661	// Calculate posibles data points
8662	$relative_date_end = strtotime (date ('H:i:s', $date_end));
8663	$relative_00_00_00 = strtotime ("00:00:00");
8664	$relative_wt_start = strtotime($wt_start) - $relative_00_00_00;
8665	$relative_wt_end = strtotime($wt_end) - $relative_00_00_00;
8666
8667	$absolute_previous_00_00_00 = $date_previous_day - ($relative_date_end - $relative_00_00_00);
8668	$absolute_00_00_00 = $date_end - ($relative_date_end - $relative_00_00_00);
8669	array_push ($wt, $absolute_previous_00_00_00);
8670	if ($relative_wt_start < $relative_wt_end) {
8671		array_push ($wt, $absolute_previous_00_00_00 + $relative_wt_start);
8672		array_push ($wt, $absolute_previous_00_00_00 + $relative_wt_end);
8673		array_push ($wt, $absolute_00_00_00 + $relative_wt_start);
8674		array_push ($wt, $absolute_00_00_00 + $relative_wt_end);
8675	} else {
8676		array_push ($wt, $absolute_previous_00_00_00 + $relative_wt_end);
8677		array_push ($wt, $absolute_previous_00_00_00 + $relative_wt_start);
8678		array_push ($wt, $absolute_00_00_00 + $relative_wt_end);
8679		array_push ($wt, $absolute_00_00_00 + $relative_wt_start);
8680	}
8681	array_push ($wt, $absolute_00_00_00 + SECONDS_1DAY);
8682
8683	//Discard outside period time points
8684	$date_start = $date_end - $period;
8685
8686	$first_time = array_shift ($wt);
8687	while ($first_time < $date_start) {
8688		if (empty ($wt)) {
8689			return $wt;
8690		}
8691		$first_time = array_shift ($wt);
8692	}
8693	array_unshift ($wt, $first_time);
8694
8695	return $wt;
8696}
8697
8698?>
8699