From 12d47a5547a484b281ff65972bb42ac58eb3df43 Mon Sep 17 00:00:00 2001
From: Esteban Sanchez <esteban.sanchez@gmail.com>
Date: Fri, 27 Feb 2009 12:48:05 +0000
Subject: [PATCH] 2009-02-27  Esteban Sanchez  <estebans@artica.es>

	* godmode/groups/configure_group.php: Removed javascript console.log

	* godmode/reporting/map_builder.php: Fixed typo on file_exists()

	* include/functions.php: Added format_integer_round().

	* include/functions_db.php: Added fields to get_db_row(). Array values
	to make "IN" SQL statements were in wrong function. Added support for
	order in format_array_to_where_clause_sql().

	* include/functions_events.php: Added get_event(). Fixed
	print_event_type_img() which causes double printing in some cases.

	* operation/events/events.php: Added get_event_tooltip AJAX operation.
	Style correction by replacing $row with $event.



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@1495 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
---
 pandora_console/ChangeLog                     |  18 ++++
 .../godmode/groups/configure_group.php        |   1 -
 .../godmode/reporting/map_builder.php         |   2 +-
 pandora_console/include/functions.php         |  24 +++++
 pandora_console/include/functions_db.php      |  57 +++++++---
 pandora_console/include/functions_events.php  |  91 +++++++++++-----
 pandora_console/operation/events/events.php   | 100 ++++++++++++------
 7 files changed, 221 insertions(+), 72 deletions(-)

diff --git a/pandora_console/ChangeLog b/pandora_console/ChangeLog
index 5f5e8ff3ec..9bdb7ec438 100644
--- a/pandora_console/ChangeLog
+++ b/pandora_console/ChangeLog
@@ -1,3 +1,21 @@
+2009-02-27  Esteban Sanchez  <estebans@artica.es>
+
+	* godmode/groups/configure_group.php: Removed javascript console.log
+
+	* godmode/reporting/map_builder.php: Fixed typo on file_exists()
+
+	* include/functions.php: Added format_integer_round().
+
+	* include/functions_db.php: Added fields to get_db_row(). Array values
+	to make "IN" SQL statements were in wrong function. Added support for
+	order in format_array_to_where_clause_sql().
+
+	* include/functions_events.php: Added get_event(). Fixed
+	print_event_type_img() which causes double printing in some cases.
+
+	* operation/events/events.php: Added get_event_tooltip AJAX operation.
+	Style correction by replacing $row with $event.
+
 2009-02-26  Evi Vanoost  <vanooste@rcbi.rochester.edu>
 	
 	* godmode/setup/setup.php: Unchecked checkboxes don't transfer any value
diff --git a/pandora_console/godmode/groups/configure_group.php b/pandora_console/godmode/groups/configure_group.php
index 003fc0b64d..b0f0376057 100644
--- a/pandora_console/godmode/groups/configure_group.php
+++ b/pandora_console/godmode/groups/configure_group.php
@@ -111,7 +111,6 @@ echo '</form>';
 function icon_changed () {
 	var inputs = [];
 	var data = this.value;
-	console.log (this.value);
 	$('#icon_preview').fadeOut ('normal', function () {
 		$('#icon_preview').empty ();
 		if (data != "") {
diff --git a/pandora_console/godmode/reporting/map_builder.php b/pandora_console/godmode/reporting/map_builder.php
index 0875801376..7f60f275b3 100644
--- a/pandora_console/godmode/reporting/map_builder.php
+++ b/pandora_console/godmode/reporting/map_builder.php
@@ -117,7 +117,7 @@ if ($update_layout) {
 
 if ($get_background_info) {
 	$file = (string) get_parameter ('background');
-	if (file_exist ('images/console/background/'.$file)){
+	if (file_exists ('images/console/background/'.$file)){
 		$info = getimagesize ('images/console/background/'.$file);
 		$info['width'] = $info[0];
 		$info['height'] = $info[1];
diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php
index d3625e1c5e..5da7d46c84 100644
--- a/pandora_console/include/functions.php
+++ b/pandora_console/include/functions.php
@@ -298,6 +298,30 @@ function format_for_graph ($number , $decimals = 1, $dec_point = ".", $thousands
 	return format_numeric ($number, $decimals). $shorts[$pos]; //This will actually do the rounding and the decimals
 }
 
+/**
+ * Rounds an integer to a multiple of 5.
+ *
+ * Example:
+<code>
+echo format_integer_round (18);
+// Will return 20
+
+echo format_integer_round (21);
+// Will return 25
+
+echo format_integer_round (25, 10);
+// Will return 30
+</code>
+ *
+ * @param int Number to be rounded.
+ * @param int Rounder number, default value is 5.
+ *
+ * @param Number rounded to a multiple of rounder
+ */
+function format_integer_round ($number, $rounder = 5) {
+	return (int) ($number / $rounder + 0.5) * $rounder;
+}
+
 /** 
  * INTERNAL: Use print_timestamp for output Get a human readable string of 
  * the difference between current time and given timestamp.
diff --git a/pandora_console/include/functions_db.php b/pandora_console/include/functions_db.php
index bf7fc0148b..e2881fdeaa 100644
--- a/pandora_console/include/functions_db.php
+++ b/pandora_console/include/functions_db.php
@@ -1525,14 +1525,25 @@ function get_db_row_sql ($sql) {
  * 
  * @return mixed The first row of a database query or false.
  */
-function get_db_row ($table, $field_search, $condition) {
-	
-	if (is_int ($condition)) {
-		$sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = %d LIMIT 1", $table, $field_search, $condition);
-	} else if (is_float ($condition) || is_double ($condition)) {
-		$sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = %f LIMIT 1", $table, $field_search, $condition);
+function get_db_row ($table, $field_search, $condition, $fields = false) {
+	if (empty ($fields)) {
+		$fields = '*';
 	} else {
-		$sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = '%s' LIMIT 1", $table, $field_search, $condition);
+		if (is_array ($fields))
+			$fields = implode (',', $fields);
+		else if (! is_string ($fields))
+			return false;
+	}
+		
+	if (is_int ($condition)) {
+		$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %d LIMIT 1",
+			$fields, $table, $field_search, $condition);
+	} else if (is_float ($condition) || is_double ($condition)) {
+		$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %f LIMIT 1",
+			$fields, $table, $field_search, $condition);
+	} else {
+		$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = '%s' LIMIT 1", 
+			$fields, $table, $field_search, $condition);
 	}
 	$result = get_db_all_rows_sql ($sql);
 		
@@ -1887,10 +1898,8 @@ function format_array_to_update_sql ($values) {
 			$sql = sprintf ("`%s` = NULL", $field);
 		} elseif (is_int ($value) || is_bool ($value)) {
 			$sql = sprintf ("`%s` = %d", $field, $value);
-		} else if (is_float ($value) || is_double ($value)) {
+		} elseif (is_float ($value) || is_double ($value)) {
 			$sql = sprintf ("`%s` = %f", $field, $value);
-		} else if (is_array ($value)) {
-			$sql = sprintf ('`%s` IN ("%s")', $field, implode ('", "', $value));
 		} else {
 			$sql = sprintf ("`%s` = '%s'", $field, $value);
 		}
@@ -1920,7 +1929,22 @@ echo $sql;
  *
  * @param array Values to be formatted in an array indexed by the field name.
  * There are special parameters such as 'limit' and 'offset' that will be used
- * as LIMIT and OFFSET clauses respectively.
+ * as ORDER, LIMIT and OFFSET clauses respectively. Since LIMIT and OFFSET are
+ * numerics, ORDER can receive a field name or a SQL function and a the ASC or
+ * DESC clause. Examples:
+<code>
+$values = array ();
+$values['value'] = 10;
+$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
+// SELECT * FROM table WHERE VALUE = 10
+
+$values = array ();
+$values['value'] = 10;
+$values['order'] = 'name DESC';
+$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
+// SELECT * FROM table WHERE VALUE = 10 ORDER BY name DESC
+
+</code>
  * @param string Join operator. AND by default.
  * @param string A prefix to be added to the string. It's useful when limit and
  * offset could be given to avoid this cases:
@@ -1958,6 +1982,7 @@ function format_array_to_where_clause_sql ($values, $join = 'AND', $prefix = fal
 	$query = '';
 	$limit = '';
 	$offset = '';
+	$order = '';
 	if (isset ($values['limit'])) {
 		$limit = sprintf (' LIMIT %d', $values['limit']);
 		unset ($values['limit']);
@@ -1967,6 +1992,12 @@ function format_array_to_where_clause_sql ($values, $join = 'AND', $prefix = fal
 		$offset = sprintf (' OFFSET %d', $values['offset']);
 		unset ($values['offset']);
 	}
+	
+	if (isset ($values['order'])) {
+		$order = sprintf (' ORDER BY %s', $values['order']);
+		unset ($values['order']);
+	}
+	
 	$i = 1;
 	$max = count ($values);
 	foreach ($values as $field => $value) {
@@ -1984,6 +2015,8 @@ function format_array_to_where_clause_sql ($values, $join = 'AND', $prefix = fal
 			$query .= sprintf ("%s = %d", $field, $value);
 		} else if (is_float ($value) || is_double ($value)) {
 			$query .= sprintf ("%s = %f", $field, $value);
+		} elseif (is_array ($value)) {
+			$query .= sprintf ('%s IN ("%s")', $field, implode ('", "', $value));
 		} else {
 			$query .= sprintf ("%s = '%s'", $field, $value);
 		}
@@ -1994,7 +2027,7 @@ function format_array_to_where_clause_sql ($values, $join = 'AND', $prefix = fal
 		$i++;
 	}
 	
-	return (! empty ($query) ? $prefix: '').$query.$limit.$offset;
+	return (! empty ($query) ? $prefix: '').$query.$order.$limit.$offset;
 }
 
 /** 
diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php
index cdd18bb9da..335b5a928c 100644
--- a/pandora_console/include/functions_events.php
+++ b/pandora_console/include/functions_events.php
@@ -21,6 +21,17 @@ function get_events ($filter = false, $fields = false) {
 	return get_db_all_rows_filter ('tevento', $filter, $fields);
 }
 
+function get_event ($id, $fields = false) {
+	if (empty ($id))
+		return false;
+	global $config;
+	
+	$event = get_db_row ('tevento', 'id_evento', $id, $fields);
+	if (! give_acl ($config['id_user'], $event['id_grupo'], 'IR'))
+		return false;
+	return $event;
+}
+
 /**
  * Delete events in a transaction
  *
@@ -280,32 +291,60 @@ function print_events_table ($filter = "", $limit = 10, $width = 440, $return =
  * @return string HTML with img 
  */
 function print_event_type_img ($type, $return = false) {
+	$output = '';
+	
 	switch ($type) {
-		case "alert_recovered": 
-			return print_image ("images/error.png", $return, array ("title" => __('Alert recovered')));
-		case "alert_manual_validation": 
-			return print_image ("images/eye.png", $return, array ("title" => __('Alert manually validated')));
-		case "going_up_warning":
-			return print_image ("images/b_yellow.png", $return, array ("title" => __('Going from critical to warning')));
-		case "going_down_critical":
-		case "going_up_critical": //This is to be backwards compatible
-			return print_image ("images/b_red.png", $return, array ("title" => __('Going down to critical state')));
-		case "going_up_normal":
-		case "going_down_normal": //This is to be backwards compatible
-			return print_image ("images/b_green.png", $return, array ("title" => __('Going up to normal state')));
-		case "going_down_warning":
-			return print_image ("images/b_yellow.png", $return, array ("title" => __('Going down from normal to warning')));
-		case "alert_fired":
-			return print_image ("images/bell.png", $return, array ("title" => __('Alert fired')));
-		case "system";
-			return print_image ("images/cog.png", $return, array ("title" => __('SYSTEM')));
-		case "recon_host_detected";
-			return print_image ("images/network.png", $return, array ("title" => __('Recon server detected a new host')));
-		case "new_agent";
-			return print_image ("images/wand.png", $return, array ("title" => __('New agent created')));
-		case "unknown": 
-		default:
-			return print_image ("images/err.png", $return, array ("title" => __('Unknown type:').': '.$type));
-	}	
+	case "alert_recovered": 
+		$output .= print_image ("images/error.png", true,
+			array ("title" => __('Alert recovered')));
+		break;
+	case "alert_manual_validation": 
+		$output .= print_image ("images/eye.png", true,
+			array ("title" => __('Alert manually validated')));
+		break;
+	case "going_up_warning":
+		$output .= print_image ("images/b_yellow.png", true,
+			array ("title" => __('Going from critical to warning')));
+		break;
+	case "going_down_critical":
+	case "going_up_critical": //This is to be backwards compatible
+		$output .= print_image ("images/b_red.png", true,
+			array ("title" => __('Going down to critical state')));
+		break;
+	case "going_up_normal":
+	case "going_down_normal": //This is to be backwards compatible
+		$output .= print_image ("images/b_green.png", true,
+			array ("title" => __('Going up to normal state')));
+		break;
+	case "going_down_warning":
+		$output .= print_image ("images/b_yellow.png", true,
+			array ("title" => __('Going down from normal to warning')));
+		break;
+	case "alert_fired":
+		$output .= print_image ("images/bell.png", true,
+			array ("title" => __('Alert fired')));
+		break;
+	case "system";
+		$output .= print_image ("images/cog.png", true,
+			array ("title" => __('SYSTEM')));
+		break;
+	case "recon_host_detected";
+		$output .= print_image ("images/network.png", true,
+			array ("title" => __('Recon server detected a new host')));
+		break;
+	case "new_agent";
+		$output .= print_image ("images/wand.png", true,
+			array ("title" => __('New agent created')));
+		break;
+	case "unknown": 
+	default:
+		$output .= print_image ("images/err.png", true,
+			array ("title" => __('Unknown type:').': '.$type));
+		break;
+	}
+	
+	if ($return)
+		return $output;
+	echo $output;
 }
 ?>
diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php
index a4ec3f598f..07024e3a27 100644
--- a/pandora_console/operation/events/events.php
+++ b/pandora_console/operation/events/events.php
@@ -29,6 +29,42 @@ if (! give_acl ($config["id_user"], 0, "IR")) {
 	return;
 }
 
+if (defined ('AJAX')) {
+	$get_event_tooltip = (bool) get_parameter ('get_event_tooltip');
+	
+	if ($get_event_tooltip) {
+		$id = (int) get_parameter ('id');
+		$event = get_event ($id);
+		if ($event === false)
+			return;
+		
+		echo '<h3>'.__('Event').'</h3>';
+		echo '<strong>'.__('Type').': </strong><br />';
+		
+		print_event_type_img ($event["event_type"]);
+		echo ' ';
+		if ($event["event_type"] == "system") {
+			echo __('System');
+		} elseif ($event["id_agente"] > 0) {
+			// Agent name
+			echo get_agent_name ($event["id_agente"]);
+		} else {
+			echo __('Alert').__('SNMP');
+		}
+		echo '<br />';
+		echo '<strong>'.__('Timestamp').': </strong><br />';
+		print_timestamp ($event['utimestamp']);
+		
+		echo '<br />';
+		echo '<strong>'.__('Description').': </strong><br />';
+		echo $event['evento'];
+		
+		return;
+	}
+	
+	return;
+}
+
 $delete = (bool) get_parameter ("delete");
 $validate = (bool) get_parameter ("validate");
 //Process deletion (pass array or single value)
@@ -318,60 +354,60 @@ $table->head[9] = print_checkbox ("allbox", "1", false, true);
 $table->align[9] = 'center';
 
 //Arrange data. We already did ACL's in the query
-foreach ($result as $row) {
+foreach ($result as $event) {
 	$data = array ();
 	
 	//First pass along the class of this row
-	$table->rowclass[] = get_priority_class ($row["criticity"]);
+	$table->rowclass[] = get_priority_class ($event["criticity"]);
 	
 	// Colored box
-	if ($row["estado"] == 0) {
-		$data[0] = print_image ("images/pixel_red.png", true, array ("width" => 20, "height" => 20, "title" => get_priority_name ($row["criticity"])));
+	if ($event["estado"] == 0) {
+		$data[0] = print_image ("images/pixel_red.png", true, array ("width" => 20, "height" => 20, "title" => get_priority_name ($event["criticity"])));
 	} else {
-		$data[0] = print_image ("images/pixel_green.png", true, array ("width" => 20, "height" => 20, "title" => get_priority_name ($row["criticity"])));
+		$data[0] = print_image ("images/pixel_green.png", true, array ("width" => 20, "height" => 20, "title" => get_priority_name ($event["criticity"])));
 	}
 	
-	$data[1] = print_event_type_img ($row["event_type"], true);
+	$data[1] = print_event_type_img ($event["event_type"], true);
 	
 	// Event description
-	$data[2] = '<span title="'.$row["evento"].'" class="f9">';
-	$data[2] .= '<a href="'.$url.'&amp;group_rep=0&amp;id_agent='.$row["id_agente"].'&amp;pure='.$config["pure"].'&amp;search='.rawurlencode ($row["evento"]).'">';
-	if (strlen ($row["evento"]) > 50) {
-		$data[2] .= mb_substr ($row["evento"], 0, 50)."...";
+	$data[2] = '<span title="'.$event["evento"].'" class="f9">';
+	$data[2] .= '<a href="'.$url.'&amp;group_rep=0&amp;id_agent='.$event["id_agente"].'&amp;pure='.$config["pure"].'&amp;search='.rawurlencode ($event["evento"]).'">';
+	if (strlen ($event["evento"]) > 50) {
+		$data[2] .= mb_substr ($event["evento"], 0, 50)."...";
 	} else {
-		$data[2] .= $row["evento"];
+		$data[2] .= $event["evento"];
 	}
 	$data[2] .= '</a></span>';
 
-	if ($row["event_type"] == "system") {
+	if ($event["event_type"] == "system") {
 		$data[3] = __('System');
-	} elseif ($row["id_agente"] > 0) {
+	} elseif ($event["id_agente"] > 0) {
 		// Agent name
-		$data[3] = print_agent_name ($row["id_agente"], true);
+		$data[3] = print_agent_name ($event["id_agente"], true);
 	} else {
 		$data[3] = __('Alert').__('SNMP');
 	}
 	
 	$data[4] = '';
-	if ($row["id_agentmodule"] != 0) {
-		$data[4] .= '<a href="index.php?sec=estado&amp;sec2=operation/agentes/ver_agente&amp;id_agente='.$row["id_agente"].'&amp;tab=data">';
+	if ($event["id_agentmodule"] != 0) {
+		$data[4] .= '<a href="index.php?sec=estado&amp;sec2=operation/agentes/ver_agente&amp;id_agente='.$event["id_agente"].'&amp;tab=data">';
 		$data[4] .= print_image ("images/bricks.png", true, array ("border" => 0, "title" => __('Go to data overview')));
 		$data[4] .= '</a>&nbsp;';
 	}
-	if ($row["id_alert_am"] != 0) {
-		$data[4] .= '<a href="index.php?sec=estado&amp;sec2=operation/agentes/ver_agente&amp;id_agente='.$row["id_agente"].'&amp;tab=alert">';
+	if ($event["id_alert_am"] != 0) {
+		$data[4] .= '<a href="index.php?sec=estado&amp;sec2=operation/agentes/ver_agente&amp;id_agente='.$event["id_agente"].'&amp;tab=alert">';
 		$data[4] .= print_image ("images/bell.png", true, array ("border" => 0, "title" => __('Go to alert overview')));
 		$data[4] .= '</a>';
 	}
 	
-	$data[5] = print_group_icon ($row["id_grupo"], true);
+	$data[5] = print_group_icon ($event["id_grupo"], true);
 
 	if ($group_rep == 1) {
-		$data[6] = $row["event_rep"];	
+		$data[6] = $event["event_rep"];	
 	} else {
-		if (!empty ($row["estado"])) {
-			if ($row["id_usuario"] != '0' && $row["id_usuario"] != ''){
-			  $data[6] = '<a href="index.php?sec=usuario&amp;sec2=operation/user/user_edit&amp;ver='.$row["id_usuario"].'" title="'.dame_nombre_real ($row["id_usuario"]).'">'.mb_substr ($row["id_usuario"],0,8).'</a>';
+		if (!empty ($event["estado"])) {
+			if ($event["id_usuario"] != '0' && $event["id_usuario"] != ''){
+			  $data[6] = '<a href="index.php?sec=usuario&amp;sec2=operation/user/user_edit&amp;ver='.$event["id_usuario"].'" title="'.dame_nombre_real ($event["id_usuario"]).'">'.mb_substr ($event["id_usuario"],0,8).'</a>';
 			} else {
 			  $data[6] = __('System');
 			}
@@ -383,34 +419,34 @@ foreach ($result as $row) {
 	//Time	
 	
 	if ($group_rep == 1) {
-		$data[7] = print_timestamp ($row['timestamp_rep'], true);
+		$data[7] = print_timestamp ($event['timestamp_rep'], true);
 	} else {
-		$data[7] = print_timestamp ($row["timestamp"], true);
+		$data[7] = print_timestamp ($event["timestamp"], true);
 	}
 	
 	//Actions
 	$data[8] = '';
 	// Validate event
-	if (($row["estado"] == 0) and (give_acl ($config["id_user"], $row["id_grupo"], "IW") == 1)) {
-		$data[8] .= '<a href="'.$url.'&amp;validate=1&amp;eventid='.$row["id_evento"].'&amp;pure='.$config["pure"].'">';
+	if (($event["estado"] == 0) and (give_acl ($config["id_user"], $event["id_grupo"], "IW") == 1)) {
+		$data[8] .= '<a href="'.$url.'&amp;validate=1&amp;eventid='.$event["id_evento"].'&amp;pure='.$config["pure"].'">';
 		$data[8] .= print_image ("images/ok.png", true, array ("border" => 0, "title" => __('Validate event')));
 		$data[8] .= '</a>';
 	}
 	// Delete event
-	if (give_acl ($config["id_user"], $row["id_grupo"], "IM") == 1) {
-		$data[8] .= '<a href="'.$url.'&amp;delete=1&amp;eventid='.$row["id_evento"].'&amp;pure='.$config["pure"].'">';
+	if (give_acl ($config["id_user"], $event["id_grupo"], "IM") == 1) {
+		$data[8] .= '<a href="'.$url.'&amp;delete=1&amp;eventid='.$event["id_evento"].'&amp;pure='.$config["pure"].'">';
 		$data[8] .= print_image ("images/cross.png", true, array ("border" => 0, "title" => __('Delete event')));
 		$data[8] .= '</a>';
 	}
 	// Create incident from this event			
-	if (give_acl ($config["id_user"], $row["id_grupo"], "IW") == 1) {
-		$data[8] .= '<a href="index.php?sec=incidencias&amp;sec2=operation/incidents/incident_detail&amp;insert_form&amp;from_event='.$row["id_evento"].'">';
+	if (give_acl ($config["id_user"], $event["id_grupo"], "IW") == 1) {
+		$data[8] .= '<a href="index.php?sec=incidencias&amp;sec2=operation/incidents/incident_detail&amp;insert_form&amp;from_event='.$event["id_evento"].'">';
 		$data[8] .= print_image ("images/page_lightning.png", true, array ("border" => 0, "title" => __('Create incident from event')));
 		$data[8] .= '</a>';
 	}
 	
 	//Checkbox
-	$data[9] = print_checkbox_extended ("eventid[]", $row["id_evento"], false, false, false, 'class="chk"', true);
+	$data[9] = print_checkbox_extended ("eventid[]", $event["id_evento"], false, false, false, 'class="chk"', true);
 	
 	array_push ($table->data, $data);
 }