<?php
	require_once('../config/config.php');
	require_once('../libs/dgsutil/cgi.php');
	require_once('../libs/dgsutil/misc.php');
	require_once('../libs/util.php');

	/* Start Main */
	$db = dbConnect();
	$form = getFormData();

	switch ($form['action']) {
		case 'clear':
			clearEvent($db, $form);
			break;
	}

	switch ($form['func']) {
		case 'sum_event':
			displaySumEvents($db, $form);
			break;
		default:
			if ($_SESSION['event_summary']) {
				displaySummary($db);
			} else {
				displayEvents($db);
			}
	}

	function displaySumEvents($db, $form) {
		global $config, $event_state, $event_title, $event_new_color, $event_ack_color;
		jsLoadFrame(false);

		/* Check if the browser module is available. */
		reset($config['modules']);
		$browser = false;
		while (list($desc, $module) = each($config['modules'])) {
			if ($module == 'browser') {
				$browser = true;
				$browser_file = moduleFile($module);
				break;
			}
		}

		/* Build SQL statement for state. */
		for ($i = count($event_state); list(, $s) = each($event_state); $i--) {
			$state_sql .= sprintf("gui_event.state = '%s'", $s);
			if ($i > 1) {
				$state_sql .= sprintf(" OR ");
			}
		}

		/* Build SQL statement for channel. */
		$channels = getChannels($db);
		if (empty($channels)) {
			$channel_sql = '';
		} else {
			for ($i = count($channels); list(, $channel) = each($channels); $i--) {
				$channel_sql .= sprintf("gui_event.channel = '%s'", $channel);
				if ($i > 1) {
					$channel_sql .= sprintf(" OR ");
				}
			}
			$channel_sql = sprintf('AND (%s)', $channel_sql);
		}

		/* NOTE: Do not remove 'gui_event.brief' from GROUP BY. If you don't want to see two events for a element, interface, ip set, then change your policy. */ 
		$sql = sprintf('SELECT MIN(UNIX_TIMESTAMP(gui_event.timestamp)) AS stamp, gui_event.id AS event_id, SUBSTRING(ned2.value FROM 1 FOR 4) AS grouping, gui_event.source AS source, gui_event.state AS state, gui_event.acknowleged AS acknowleged, gui_event.element AS element_id, gui_event.interface AS interface_id, gui_event.ip AS ip_id, ned1.value AS element, neid1.value AS ifDescr, neid2.value AS ifAlias, gui_event.brief AS brief FROM gui_event LEFT JOIN element_data AS ned1 ON (gui_event.element = ned1.element AND (ned1.variable = \'.1.3.6.1.2.1.1.5.0\' OR ned1.variable IS NULL)) LEFT JOIN element_data AS ned2 ON (gui_event.element = ned2.element) LEFT JOIN interface_data AS neid1 ON (neid1.interface = gui_event.interface AND (neid1.variable = \'.1.3.6.1.2.1.2.2.1.2\' OR neid1.variable IS NULL)) LEFT JOIN interface_data AS neid2 ON (neid2.interface = gui_event.interface AND (neid2.variable = \'.1.3.6.1.2.1.31.1.1.1.18\' OR neid2.variable IS NULL)) WHERE (ned2.variable = \'%s\' AND SUBSTRING(ned2.value FROM %d FOR %d) = \'%s\') AND (%s) %s GROUP BY element_id, interface_id, ip_id, brief, neid1.variable, neid2.variable ORDER BY acknowleged, timestamp DESC', $_SESSION['event_summary_key'], $_SESSION['event_summary_pos'], $_SESSION['event_summary_len'], $form['group'], $state_sql, $channel_sql);
		//echo "SQL: $sql<BR>";
		if (($result = mysql_query($sql, $db)) == false || ($event_count = mysql_num_rows($result)) < 1) {
			printf("<TABLE CELLSPACING=\"1\" CELLPADDING=\"0\" BORDER=\"0\" WIDTH=\"100%%\">\n<TR CLASS=\"tbltitle\">\n<TD NOWRAP>%s: %d</TD>\n</TR>\n</TABLE>\n", $event_title, $event_count);
		} else {
?>
<TABLE CELLSPACING="1" CELLPADDING="0" BORDER="0" WIDTH="100%">
	<TR CLASS="tbltitle">
		<TD COLSPAN="4"><TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%"><TR CLASS="tbltitle">
			<TD NOWRAP>&nbsp;<?php printf('%s: %d', $event_title, $event_count); ?></TD>
			<TD ALIGN="right"><B>[<A CLASS="tbltitle" TARGET="_self" HREF="?func=summary&rand=<?php printf('%d', rand(0, getrandmax())); ?>">Return to Summary</A>] [<A CLASS="tbltitle" TARGET="_blank" HREF="?">Snapshot</A>]</B> &nbsp; <?php printf('Last Update: %s', date($config['dateFormat'], currentDbTime($db))); ?></TD>
		</TR></TABLE></TD>
	</TR>

	<TR CLASS="tblhdr">
		<TD NOWRAP>&nbsp;Time Stamp&nbsp;</TD>
		<TD COLSPAN="2" NOWRAP>&nbsp;Element&nbsp;</TD>
		<TD WIDTH="100%" NOWRAP>&nbsp;Event</TD>
	</TR>
<?php
			$x = 0;
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				if ($row['acknowleged'] < 1) {
					$event_color = $event_new_color[$event_state[0]][++$x % count($event_new_color[$event_state[0]])];
				} else {
					$event_color = $event_ack_color[$event_state[0]][++$x % count($event_ack_color[$event_state[0]])];
				}
				printf("<TR CLASS=\"%s\">\n", $event_color);
				printf("<TD NOWRAP>&nbsp;%s&nbsp;</TD>\n", date($config['dateFormat'], $row['stamp']));
				if ($browser) {
					printf("<TD NOWRAP>&nbsp;<A HREF=\"javascript:loadFrame('body', '%s?function=Display&router=%d&rand=%d');\">%s</A>&nbsp;</TD>\n", $browser_file, $row['element_id'], rand(0, getrandmax()), ($row['element_id'] != 2) ? $row['element'] : $row['source']); //HERE
					printf("<TD NOWRAP>&nbsp;<A HREF=\"javascript:loadFrame('body', '%s?function=Display&router=%d&interface=%d&rand=%d');\">%s</A>&nbsp;</TD>\n", $browser_file, $row['element_id'], $row['interface_id'], rand(0, getrandmax()), $row['ifDescr']);
				} else {
					printf("<TD NOWRAP>&nbsp;%s&nbsp;</TD>\n", ($row['element_id'] != 2 ? $row['element'] : $row['source']));
					printf("<TD NOWRAP>&nbsp;%s&nbsp;</TD>\n", $row['ifDescr']);
				}
				printf("<TD NOWRAP>&nbsp;<A HREF=\"../detail/eventdetail_template.php?id=%d&listing=%s&func=%s&group=%s\">%s</A></TD>\n", $row['event_id'], $_SERVER['PHP_SELF'], $form['func'], $form['group'], $row['brief']);
				print("</TR>\n");
				if (strlen($row['ifAlias']) > 0)  {
					printf("<TR CLASS=\"%s\">\n", $event_color);
					printf("<TD COLSPAN=\"4\" NOWRAP>&nbsp;%s</TD>\n", $row['ifAlias']);
					print("</TR>\n");
				}
			}
			printf("</TABLE>\n");
		}
	}

	function displaySummary($db) {
		global $config, $event_state, $event_title, $event_new_color;

		/* Build SQL statement for state. */
		for ($i = count($event_state); list(, $s) = each($event_state); $i--) {
			$state_sql .= sprintf("gui_event.state = '%s'", $s);
			if ($i > 1) {
				$state_sql .= sprintf(" OR ");
			}
		}

		/* Build SQL statement for channel. */
		$channels = getChannels($db);
		if (empty($channels)) {
			$channel_sql = '';
		} else {
			for ($i = count($channels); list(, $channel) = each($channels); $i--) {
				$channel_sql .= sprintf("gui_event.channel = '%s'", $channel);
				if ($i > 1) {
					$channel_sql .= sprintf(" OR ");
				}
			}
			$channel_sql = sprintf('AND (%s)', $channel_sql);
		}

		/* Create temporary table, since I can't figure out how to do all of this in one select. :) */
		$tmp_table = sprintf('event_%s_%s_%d', $event_state[0], isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : 'user', rand(0,getrandmax()));

		$sql = sprintf("CREATE TEMPORARY TABLE %s SELECT gui_event.timestamp, SUBSTRING(element_data.value FROM %lu FOR %lu) AS grouping, gui_event.acknowleged AS acknowleged, element_data.value AS element_name, interface_data.value AS interface_name, gui_event.source AS source, gui_event.brief AS last_event FROM gui_event LEFT JOIN element_data ON (element_data.element = gui_event.element AND (%s) %s) LEFT JOIN interface_data ON (interface_data.interface = gui_event.interface AND interface_data.variable = '%s') WHERE element_data.variable = '%s' GROUP BY element, interface, ip, brief ORDER BY grouping, gui_event.timestamp DESC", $tmp_table, $_SESSION['event_summary_pos'], $_SESSION['event_summary_len'], $state_sql, $channel_sql, '.1.3.6.1.2.1.2.2.1.2', $_SESSION['event_summary_key']);
		//echo "SQL: $sql<BR>\n";
		if (($result = mysql_query($sql, $db)) == false) {
			die("FIXME: Temporary table collision. If this ever happens, I'll be supprised.");
		}

		/* Total events. */
		$sql = sprintf("SELECT COUNT(timestamp) AS event_count FROM %s", $tmp_table);
		if (($result = mysql_query($sql, $db)) != false && mysql_num_rows($result) > 0) {
			$row = mysql_fetch_array($result, MYSQL_ASSOC);
			$event_count = $row['event_count'];
			mysql_free_result($result);
		} else {
			$event_count = 0;
		}

		/* Total event deltas. */
		$sql = sprintf("SELECT COUNT(timestamp) AS event_delta FROM %s WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(timestamp) < %d", $tmp_table, isset($_SESSION['event_delta']) ? $_SESSION['event_delta'] : 300);
		if (($result = mysql_query($sql, $db)) != false && mysql_num_rows($result) > 0) {
			$row = mysql_fetch_array($result, MYSQL_ASSOC);
			$event_delta = $row['event_delta'];
			mysql_free_result($result);
		} else {
			$event_delta = 0;
		}

		/* Group event deltas. */
		$sql = sprintf("SELECT grouping, COUNT(timestamp) AS event_delta FROM %s WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(timestamp) < %d GROUP BY grouping", $tmp_table, isset($_SESSION['event_delta']) ? $_SESSION['event_delta'] : 300);
		if (($result = mysql_query($sql, $db)) != false && mysql_num_rows($result) > 0) {
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$delta_counts[$row['grouping']] = $row['event_delta'];
			}
			mysql_free_result($result);
		} else {
			$delta_counts = array();
		}

		/* Select summary data for display. */
		$sql = sprintf('SELECT MAX(UNIX_TIMESTAMP(timestamp)) AS stamp, grouping, COUNT(grouping) AS events, SUM(acknowleged) AS acknowleged, element_name, interface_name, last_event FROM %s GROUP BY grouping', $tmp_table);
		if (($result = mysql_query($sql, $db)) == false || ($group_count = mysql_num_rows($result)) < 1) {
			printf("<TABLE CELLSPACING=\"1\" CELLPADDING=\"0\" BORDER=\"0\" WIDTH=\"100%%\">\n<TR CLASS=\"tbltitle\">\n<TD NOWRAP>%s: %d&nbsp;&nbsp;Groups: %d New: %d</TD>\n</TR>\n</TABLE>\n", $event_title, $event_count, $group_count, $event_delta);
		} else {
?>
<TABLE CELLSPACING="1" CELLPADDING="0" BORDER="0" WIDTH="100%">
	<TR CLASS="tbltitle">
		<TD COLSPAN="8"><TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%"><TR CLASS="tbltitle">
			<TD NOWRAP>&nbsp;<?php printf('%s: %d&nbsp;&nbsp;Groups: %d New: %d', $event_title, $event_count, $group_count, $event_delta); ?></TD>
			<TD ALIGN="right"><B>[<A CLASS="tbltitle" TARGET="_blank" HREF="?">Snapshot</A>]</B> &nbsp; <?php printf('Last Update: %s', date($config['dateFormat'], currentDbTime($db))); ?></TD>
		</TR></TABLE></TD>
	</TR>

	<TR CLASS="tblhdr">
		<TD NOWRAP>&nbsp;Time Stamp&nbsp;</TD>
		<TD NOWRAP>&nbsp;Group&nbsp;</TD>
		<TD NOWRAP>&nbsp;Events&nbsp;</TD>
		<TD NOWRAP>&nbsp;New&nbsp;</TD>
		<TD NOWRAP>&nbsp;Acked&nbsp;</TD>
		<TD COLSPAN="3" WIDTH="100%" NOWRAP>&nbsp;Last Event</TD>
	</TR>
<?php
			$x = 0;
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$event_color = $event_new_color[$event_state[0]][++$x % count($event_new_color[$event_state[0]])];
				printf("<TR CLASS=\"%s\">\n", $event_color);
				printf("<TD NOWRAP>&nbsp;%s&nbsp;</TD>\n", date($config['dateFormat'], $row['stamp']));
				printf("<TD ALIGN=\"left\" NOWRAP>&nbsp;<A HREF=\"?func=sum_event&group=%s&rand=%d\">%s</A>&nbsp;</TD>\n", htmlentities($row['grouping']), rand(0, getrandmax()), $row['grouping']);
				printf("<TD ALIGN=\"center\" NOWRAP>&nbsp;%d&nbsp;</TD>\n", $row['events']);
				printf("<TD ALIGN=\"center\" NOWRAP>&nbsp;%d&nbsp;</TD>\n", isset($delta_counts[$row['grouping']]) ? $delta_counts[$row['grouping']] : 0);
				printf("<TD ALIGN=\"center\" NOWRAP>&nbsp;%d&nbsp;</TD>\n", $row['acknowleged']);
				printf("<TD NOWRAP>&nbsp;<A HREF=\"?func=sum_event&group=%s&rand=%d\">&nbsp;%s&nbsp;</A></TD>\n", htmlentities($row['grouping']), rand(0, getrandmax()), $row['element_name']);
				printf("<TD NOWRAP>&nbsp;<A HREF=\"?func=sum_event&group=%s&rand=%d\">&nbsp;%s&nbsp;</A></TD>\n", htmlentities($row['grouping']), rand(0, getrandmax()), $row['interface_name']);
				printf("<TD WIDTH=\"100%%\" NOWRAP>&nbsp;<A HREF=\"?func=sum_event&group=%s&rand=%d\">&nbsp;%s</A></TD>\n", htmlentities($row['grouping']), rand(0, getrandmax()), $row['last_event']);
			}
		}
		printf("</TR>\n</TABLE>\n");

		/* Free temporary table. */
		$sql = sprintf("DROP TABLE %s", $tmp_table);
		$result = mysql_query($sql, $db);
	}

	function getChannels($db) {
		$sql = sprintf("SELECT gui_channel.name AS channel FROM gui_channel LEFT JOIN gui_channel_assoc ON (gui_channel.id = gui_channel_assoc.channel) WHERE gui_channel_assoc.view = %lu", $_SESSION['view_id']);
		if (($result = mysql_query($sql, $db)) != false && mysql_num_rows($result) > 0) {
			while ($row = mysql_fetch_array($result)) {
				$channels[] = $row['channel'];
			}
			reset($channels);
		}

		return $channels;
	}
			
	function clearEvent($db, $form) {
		$sql = sprintf("DELETE FROM gui_event WHERE element = %d AND interface = %d AND ip = %d AND channel = '%s' AND state = '%s'", $form['element'], $form['interface'], $form['ip'], $form['channel'], $form['state']);
		$result = mysql_query($sql, $db);

		$sql = sprintf("INSERT INTO gui_history SET element = %d, interface = %d, ip = %d, channel = '%s', state = 'informational', brief = 'Event Cleared', detail = 'Event cleared by %s'", $form['element'], $form['interface'], $form['ip'], $form['channel'], isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : 'user');
		$result = mysql_query($sql, $db);
	}

	function displayEvents($db) {
		global $event_title, $event_state, $event_new_color, $event_ack_color, $config;
		jsLoadFrame(false);

		reset($event_state);
		$sql = sprintf("SELECT gui_event.acknowleged AS ack, gui_event.id AS event_id, gui_event.source AS source, gui_event.state AS state, gui_event.element AS element_id, gui_event.interface AS interface_id, interface_data.variable AS variable, MIN(UNIX_TIMESTAMP(gui_event.timestamp)) AS stamp, element_data.value AS element, interface_data.value AS interface_data, gui_event.channel AS channel, gui_event.brief AS brief FROM gui_event LEFT JOIN element_data ON ( element_data.element = gui_event.element AND element_data.variable = '.1.3.6.1.2.1.1.5.0' ) LEFT JOIN interface_data ON ( interface_data.interface = gui_event.interface AND ( interface_data.variable = '.1.3.6.1.2.1.2.2.1.2' OR interface_data.variable = '.1.3.6.1.2.1.31.1.1.1.18' ) ) WHERE (");
		for ($i = count($event_state); list(, $s) = each($event_state); $i--) {
			$sql .= sprintf("gui_event.state = '%s'", $s);
			if ($i > 1) {
				$sql .= sprintf(" OR ");
			}
		}

		$channels = getChannels($db);

		/* Add channels to sql. */
		if (count($channels) > 0) {
			$sql .= ') AND (';

			$num_rows = count($channels);
			reset($channels);
			for ($x = 0; $x < $num_rows; $x++) {
				if ($x + 1 < $num_rows) {
					$sql .= sprintf("channel = '%s' OR ", $channels[$x]);
				} else {
					$sql .= sprintf("channel = '%s'", $channels[$x]);
				}
			}
		}
		
		/* NOTE: Do not remove 'gui_event.brief' from GROUP BY. If you don't want to see two events for a element, interface, ip set, then change your policy. */ 
		$sql .= sprintf(") AND gui_event.element IS NOT NULL GROUP BY gui_event.ip, gui_event.interface, gui_event.element, brief, variable ORDER BY gui_event.acknowleged, gui_event.timestamp DESC, gui_event.element, gui_event.interface, gui_event.ip, interface_data.variable");

		$data = array();
//		echo "SQL: $sql<BR>";
		$result = mysql_query($sql, $db);
		for ($id = 0; $row = mysql_fetch_array($result); $id++) {
			if (!isset($data[$row['event_id']])) {
				$data[$row['event_id']]['order'] = $id;
				$data[$row['event_id']]['acknowleged'] = $row['ack'];

				$data[$row['event_id']]['event_id'] = $row['event_id'];
				$data[$row['event_id']]['element_id'] = $row['element_id'];
				$data[$row['event_id']]['interface_id'] = $row['interface_id'];

				$data[$row['event_id']]['timestamp'] = $row['stamp'];
				$data[$row['event_id']]['element'] = $row['element'];
				$data[$row['event_id']]['source'] = $row['source'];

				$data[$row['event_id']]['channel'] = $row['channel'];
				$data[$row['event_id']]['state'] = $row['state'];
				$data[$row['event_id']]['brief'] = $row['brief'];
			}
			if ($row['variable'] == '.1.3.6.1.2.1.2.2.1.2') {
				$data[$row['event_id']]['interface_name'] = $row['interface_data'];
			} else if ($row['variable'] == '.1.3.6.1.2.1.31.1.1.1.18') {
				$data[$row['event_id']]['interface_desc'] = $row['interface_data'];
			}
		}

		/* Check if the browser module is available. */
		reset($config['modules']);
		$browser = false;
		while (list($desc, $module) = each($config['modules'])) {
			if ($module == 'browser') {
				$browser = true;
				$browser_file = moduleFile($module);
				break;
			}
		}

	?>
<TABLE CELLSPACING="1" CELLPADDING="0" BORDER="0" WIDTH="100%">
	<TR CLASS="tbltitle">
		<TD COLSPAN="4"><TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%"><TR CLASS="tbltitle">
			<TD NOWRAP>&nbsp;<?php printf('%s: %d', $event_title, count($data)); ?></TD>
			<TD ALIGN="right"><B>[<A CLASS="tbltitle" TARGET="_blank" HREF="?">Snapshot</A>]</B> &nbsp; <?php printf('Last Update: %s', date($config['dateFormat'], currentDbTime($db))); ?></TD>
		</TR></TABLE></TD>
	</TR>

	<TR CLASS="tblhdr">
		<TD NOWRAP>&nbsp;Time Stamp&nbsp;</TD>
		<TD COLSPAN="2" NOWRAP>&nbsp;Element&nbsp;</TD>
		<TD WIDTH="100%" NOWRAP>&nbsp;Event&nbsp;</TD>
	</TR>

	<?php for ($c = 0; list($i,) = each($data); $c = ($c == 0) ? 1 : 0) { ?>
	<TR CLASS="<?php printf('%s', ($data[$i]['acknowleged'] == 1) ? $event_ack_color[$data[$i]['state']][$c] : $event_new_color[$data[$i]['state']][$c]); ?>">
		<TD NOWRAP>
			<?php
				$night_fever = date($config['dateFormat'], $data[$i]['timestamp']);
				printf('%s', $night_fever);
			?>
		</TD>
		<TD NOWRAP><?php if ($browser) printf('<A HREF="javascript:loadFrame(\'body\', \'%s?function=Display&router=%d&rand=%d\');">%s</A>&nbsp;', $browser_file, $data[$i]['element_id'], rand(0, getrandmax()), ($data[$i]['element_id'] != 2) ? $data[$i]['element'] : $data[$i]['source']); else printf('%s', $data[$i]['element']); ?></TD>
		<TD NOWRAP>
			<?php if (($data[$i]['interface_name'])) {
				if ($browser) printf('<A HREF="javascript:loadFrame(\'body\', \'%s?function=Display&router=%d&interface=%d&rand=%d\');">%s</A>&nbsp;', $browser_file, $data[$i]['element_id'], $data[$i]['interface_id'], rand(0, getrandmax()), $data[$i]['interface_name']); else printf('%s', $data[$i]['interface_name']);
			} else { ?>
			&nbsp;
			<?php } ?>
		</TD>
		<TD NOWRAP><A HREF="../detail/eventdetail_template.php?<?php printf('id=%d&listing=%s', $data[$i]['event_id'], $_SERVER['PHP_SELF']); ?>"><?php printf('%s', $data[$i]['brief']); ?></A></TD>
	</TR>

	<?php if (isset($data[$i]['interface_desc']) && strcmp($data[$i]['interface_desc'], '')) { ?>
	<TR CLASS="<?php printf('%s', ($data[$i]['acknowleged'] == 1) ? $event_ack_color[$data[$i]['state']][$c] : $event_new_color[$data[$i]['state']][$c]); ?>">
		<TD NOWRAP>
			&nbsp;
		</TD>
		<TD COLSPAN="3" NOWRAP>
			<?php printf('%s', $data[$i]['interface_desc']); ?>
		</TD>
	</TR>
	<?php } ?>

	<?php } ?>
</TABLE>
<?php } ?>
