<?php

/*
** SellaNMS
** $Id: prefs_template.php,v 1.19 2005/08/22 02:25:41 sella Exp $
** Copyright (c) 2001-2004 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

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

/* Main - Start */
$con = dbConnect();
$data = getFormData();

switch ($data['func']) {
	case 'view':
		switch ($data['action']) {
			case 'Select':
				handleViewSelect($con, $data);
				displayDefault($con);
				break;

			case 'Create':
				$data['view_id'] = 0;
				handleViewEdit($con, $data);
				break;

			case 'Delete':
				handleViewDelete($con, $data);
				break;

			case 'Edit':
				handleViewEdit($con, $data);
				break;

			default:
		}
		break;
	case'view_edit':
		handleViewEditCommit($con, $data);
		displayDefault($con);
		break;

	default:
		displayDefault($con);
}

function handleViewDelete($con, &$data) {
	printf("Not implemented yet..");
}

function handleViewEditCommit($con, &$data) {
	if (isset($data['view_id']) && $data['view_id'] > 0) { /* Updating an existing view. */
		/* Sanity Check */
		if (strlen($data['view']) < 1) {
			$data['view'] = sprintf('Unnamed %d', $data['view_id']);
		}
		/* Update ownership. */
		$sql = sprintf("UPDATE gui_view SET user = %d, name = '%s', description = '%s' WHERE id = %d", $data['owner'], $data['view'], $data['desc'], $data['view_id']);
		mysql_query($sql, $con);

		/* Select all channels. */
		$result = mysql_query('SELECT id FROM gui_channel', $con);
		if (mysql_num_rows($result) > 0) {
			/* Lock gui_channel_assoc. */
			mysql_query('LOCK TABLE gui_channel_assoc WRITE', $con);

			/* Delete old channels. */
			$sql = sprintf('DELETE FROM gui_channel_assoc WHERE view = %d', $data['view_id']);
			mysql_query($sql, $con);

			/* Add new channels. */
			$sql = 'INSERT INTO gui_channel_assoc (channel, view) VALUES ';
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$channel = sprintf('channel_%d', $row['id']);
				if (isset($data[$channel])) {
					$sql .= sprintf('(%d,%d),', $row['id'], $data['view_id']);
				}
			}
			/* Loose the last character. */
			$sql = substr($sql, 0, -1);

			/* Insert new channels into assoc */
			mysql_query($sql, $con);

			/* Lock gui_channel_assoc. */
			mysql_query('UNLOCK TABLES', $con);
		}
	} else { /* Creating a new view. */
		/* Lock the table. */
		mysql_query('LOCK TABLE gui_view WRITE', $con);

		$sql = sprintf("INSERT INTO gui_view (user, name, description) VALUES (%d,'%s','%s')", $data['owner'], $data['view'], $data['desc']);
		if (mysql_query($sql, $con) != false) {
			$view_id = mysql_insert_id();
		} else {
			$view_id = 0;
		}

		/* Unlock the table. */
		mysql_query('UNLOCK TABLES', $con);

		/* Select all channels. */
		$result = mysql_query('SELECT id FROM gui_channel', $con);
		if ($view_id > 0 && mysql_num_rows($result) > 0) {
			/* Lock gui_channel_assoc. */
			mysql_query('LOCK TABLE gui_channel_assoc WRITE', $con);

			/* Add new channels. */
			$sql = 'INSERT INTO gui_channel_assoc (channel, view) VALUES ';
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$channel = sprintf('channel_%d', $row['id']);
				if (isset($data[$channel])) {
					$sql .= sprintf('(%d,%d),', $row['id'], $view_id);
				}
			}
			/* Loose the last character. */
			$sql = substr($sql, 0, -1);

			/* Insert new channels into assoc */
			mysql_query($sql, $con);

			/* Lock gui_channel_assoc. */
			mysql_query('UNLOCK TABLES', $con);
		}
	}
}

/*
	$sql = sprintf('SELECT gui_channel.name AS channel FROM gui_channel, gui_channel_assoc WHERE gui_channel.id = gui_channel_assoc.channel AND gui_channel_assoc.view = %d', $_SESSION['view']);
	$result = mysql_query($sql, $con);
*/

function handleViewEdit($con, &$data) {
	$sql = sprintf('SELECT name, description, user FROM gui_view WHERE id = %d', $data['view_id']);
	$result = mysql_query($sql, $con);
	if (mysql_num_rows($result) > 0) {
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		$view = $row['name'];
		$desc = $row['description'];
		$owner = $row['user'];
	} else {
		$view = '';
		$desc = '';
		$owner = $_SESSION['user_id'];
	}
?>
		<TABLE ALIGN="center">
			<TR VALIGN="top">
				<TD>
					<FORM METHOD="get" TARGET="_self">
					<INPUT TYPE="hidden" NAME="func" VALUE="view_edit">
					<INPUT TYPE="hidden" NAME="view_id" VALUE="<?php printf('%d', $data['view_id']); ?>">
					<TABLE>
						<TR CLASS="tbltitle" ALIGN="center">
							<TD COLSPAN="2">&nbsp;Create/Edit View&nbsp;</TD>
						</TR>
						<TR ALIGN="left" CLASS="tblentry">
							<TD>&nbsp;Name&nbsp;</TD>
							<TD>&nbsp;<INPUT <?php printf('%s', (!isset($_SESSION['administrator']) && $owner < 1) ? 'DISABLED' : '');?> TYPE="text" NAME="view" VALUE="<?php printf('%s', $view); ?>" SIZE="36" MAXLENGTH="32">&nbsp;</TD>
						</TR>
						<TR ALIGN="left" CLASS="tblentry">
							<TD VALIGN="top">&nbsp;Desc&nbsp;</TD>
							<TD>&nbsp;<TEXTAREA <?php printf('%s', (!isset($_SESSION['administrator']) && $owner < 1) ? 'DISABLED' : '');?> NAME="desc" COLS=30 ROWS=6><?php printf('%s', $desc); ?></TEXTAREA>&nbsp;</TD>
						</TR>
						<TR ALIGN="left" CLASS="tblentry">
							<TD>&nbsp;Owner&nbsp;</TD>
<?php
	if (isset($_SESSION['administrator'])) {
		printf('<TD>&nbsp;<INPUT TYPE="radio" %s NAME="owner" VALUE="0">&nbsp;All Users&nbsp;&nbsp;<INPUT TYPE="radio" %s NAME="owner" VALUE="%d">&nbsp;%s&nbsp;</TD>', $owner < 1 ? 'CHECKED' : '', $owner > 0 ? 'CHECKED' : '', $owner, ($_SESSION['user_id'] == $owner || $owner < 1) ? $_SESSION['user'] : 'Original Owner');
	} else {
		printf('<TD>&nbsp;<INPUT TYPE="radio" %s %s NAME="owner" VALUE="0">&nbsp;All Users&nbsp;&nbsp;<INPUT TYPE="radio" %s %s NAME="owner" VALUE="%d">&nbsp;%s&nbsp;</TD>', $owner < 1 ? '' : 'DISABLED', $owner < 1 ? 'CHECKED' : '', $owner > 0 ? '': 'DISABLED', $owner > 0 ? 'CHECKED' : '', $owner, $_SESSION['user']);
	}
?>
						</TR>
						<TR ALIGN="left" CLASS="tblentry">
							<TD COLSPAN="2">&nbsp;Channels&nbsp;</TD>
						</TR>
<?php
	$sql = sprintf('select gui_channel.id AS channel_id, gui_channel.name AS channel, gui_channel_assoc.view AS view from gui_channel LEFT JOIN gui_channel_assoc ON (gui_channel.id = gui_channel_assoc.channel AND (gui_channel_assoc.view = %d OR gui_channel_assoc.view IS NULL))', isset($data['view_id']) ? $data['view_id'] : 0);
	$result = mysql_query($sql, $con);
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		printf('<TR ALIGN="left" CLASS="tblentry"><TD COLSPAN="2"><INPUT TYPE="checkbox" %s %s NAME="channel_%d" VALUE="%d">&nbsp;&nbsp;%s</TD></TR>', ($row['view'] == $data['view_id']) ? 'CHECKED' : '', (!isset($_SESSION['administrator']) && $owner < 1) ? 'DISABLED' : '', $row['channel_id'], $row['channel_id'], $row['channel']);
	}
?>
						<TR ALIGN="center">
<?php
	if (isset($_SESSION['administrator']) || $owner > 0) {
							printf('<TD COLSPAN="2"><INPUT TYPE="submit" NAME="action" VALUE="Commit">&nbsp;<INPUT TYPE="reset" VALUE="Reset"></TD>');
	} else {
							printf('<TD COLSPAN="2"><INPUT TYPE="submit" NAME="func" VALUE="Commit">&nbsp;<INPUT TYPE="reset" VALUE="Reset"></TD>');
	}
?>
						</TR>
					</TABLE>
					</FORM>
				</TD>
			</TR>
		</TABLE>
<?php
}

function handleViewSelect($con, &$data) {
	if ($data['event_summary'] == 1) { /* Enable summary. */
		$sql = sprintf("DELETE FROM gui_user_prefs WHERE var LIKE 'event_summary%%' AND user = %d", $_SESSION['user_id']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";

		$sql = sprintf("INSERT INTO gui_user_prefs (user, var, val) VALUES (%d, 'event_summary', '1')", $_SESSION['user_id']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";
		
		$sql = sprintf("INSERT INTO gui_user_prefs (user, var, val) VALUES (%d, 'event_summary_key', '%s')", $_SESSION['user_id'], $data['event_summary_key']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";

		$sql = sprintf("INSERT INTO gui_user_prefs (user, var, val) VALUES (%d, 'event_summary_pos', '%s')", $_SESSION['user_id'], $data['event_summary_pos']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";

		$sql = sprintf("INSERT INTO gui_user_prefs (user, var, val) VALUES (%d, 'event_summary_len', '%s')", $_SESSION['user_id'], $data['event_summary_len']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";

	} else { /* Disable Summary */
		$sql = sprintf("DELETE FROM gui_user_prefs WHERE var = 'event_summary' AND user = %d", $_SESSION['user_id']);
		if (!mysql_query($sql, $con)) echo "Failed - SQL: $sql<BR>";

		unset($_SESSION['event_summary']);
	}

	if (isset($_SESSION['view_id'])) {
		$sql = sprintf("UPDATE gui_user_prefs SET val = %d WHERE user = %d AND var = 'view_id'", $data['view_id'], $_SESSION['user_id']);
	} else {
		$sql = sprintf("INSERT INTO gui_user_prefs (user, var, val) VALUES (%d, 'view_id', '%s')", $_SESSION['user_id'], $data['view_id']);
	}

	if (mysql_query($sql, $con) != false) {
		$_SESSION['view_id'] = $data['view_id'];
		/* Force reload of prefs. */
		$_SESSION['gui_user_prefs_init'] = false;
	}

	/* Refresh our session variables. */
	registerUserPrefs($con);
}
function reloadHeader() {
	/* This is a second BODY, but it causes the header to reload and update the current view. */
	printf("\t<BODY onLoad=\"javascript:loadFrame('header', '../sella_nms.php?visible=1&reload=0');\"></BODY>\n");
}

function displayDefault($con) {
	reloadHeader();
	jsLoadFrame(true);

	if (isset($_SESSION['administrator'])) {
		$sql = 'SELECT gui_view.id AS id, gui_view.user AS user, gui_view.name AS name, gui_user.name AS username FROM gui_view LEFT JOIN gui_user ON (gui_view.user = gui_user.id) ORDER BY user, name';
	} else { /* Normal User. */
		$sql = sprintf('SELECT id, user, name FROM gui_view WHERE user = 0 OR user = %d ORDER BY user, name', $_SESSION['user_id']);
	}
	$result = mysql_query($sql, $con);
?>
		<TABLE ALIGN="center">
			<TR VALIGN="top">
				<TD>
					<FORM METHOD="get" TARGET="_self">
					<INPUT TYPE="hidden" NAME="func" VALUE="view">
					<TABLE>
						<TR CLASS="tbltitle" ALIGN="center">
							<TD>&nbsp;Available Views&nbsp;</TD>
						</TR>
						<TR CLASS="tblentry" ALIGN="right">
							<TD ALIGN="center">
								<SELECT NAME="view_id" SIZE="1" WIDTH=300 STYLE="width:20em">
<?php
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		if ($row['user'] == 0) { /* All users. */
			$marker = '';
		} else if ($row['user'] == $_SESSION['user_id']) { /* Your personal view. */
			$marker = '*';
		} else if (isset($_SESSION['administrator'])) { /* Another users view. */
			$marker = sprintf(' (%s)', $row['username']);
		}
		printf("<OPTION %sVALUE=\"%d\">%s%s</OPTION>\n", ($_SESSION['view_id'] == $row['id']) ? 'SELECTED ' : '', $row['id'], $row['name'], $marker);
	}
?>
								</SELECT>
							</TD>
						</TR>
						<TR CLASS="tblentry" ALIGN="left">
							<TD>&nbsp;<INPUT <?php printf('%s', ($_SESSION['event_summary'] == 1) ? 'CHECKED' : ''); ?> TYPE="checkbox" NAME="event_summary" VALUE="1">&nbsp;Enable Event Summary&nbsp;</TD>
						</TR>
<?php
	$sql = 'SELECT variable FROM element_data WHERE LENGTH(value) > 0 GROUP BY variable LIMIT 30';
	printf('<TR WRAP CLASS="tblentry" ALIGN="left">');
	$result = mysql_query($sql, $con);
	if ($result && mysql_num_rows($result) > 0) {
		printf("<TD>Summary Key: <SELECT NAME=\"event_summary_key\" SIZE=\"1\">");
		if (!isset($_SESSION['event_summary_key'])) {
			$_SESSION['event_summary_key'] = '.1.3.6.1.2.1.1.5.0';
		}
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			printf("<OPTION %sVALUE=\"%s\">%s</OPTION>\n", ($_SESSION['event_summary_key'] == $row['variable']) ? 'SELECTED ' : '', $row['variable'], $row['variable']);
		}
		printf("</SELECT></TD>\n");
	} else {
		printf('<TD>&nbsp;Summary Key: No Data</TD>');
	}

	printf("</TR>\n");
?>
						<TR CLASS="tblentry" ALIGN="left">
							<TD>&nbsp;Key Pos&nbsp;<INPUT TYPE="text" NAME="event_summary_pos" VALUE="<?php printf('%s', strlen($_SESSION['event_summary_pos']) > 0 ? $_SESSION['event_summary_pos'] : '1'); ?>" SIZE="5">&nbsp;Key Len&nbsp;<INPUT TYPE="text" NAME="event_summary_len" VALUE="<?php printf('%s', strlen($_SESSION['event_summary_len']) > 0 ? $_SESSION['event_summary_len'] : '4'); ?>" SIZE="5">&nbsp;</TD>
						</TR>
<?php
	$sql = sprintf('SELECT SUBSTRING(value FROM %d FOR %d) AS example, SUBSTRING(value FROM 1 FOR 45) AS original FROM element_data WHERE LENGTH(value) > 0 AND element_data.element > 2 AND variable = \'%s\' GROUP BY oid', $_SESSION['event_summary_pos'], $_SESSION['event_summary_len'], $_SESSION['event_summary_key']);
	printf('<TR WRAP CLASS="tblentry" ALIGN="left">');
	$result = mysql_query($sql, $con);
	if ($result && mysql_num_rows($result) > 0) {
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		printf('<TD>&nbsp;Example: %s <I>(full data: %s)</I></TD>', $row['example'], $row['original']);
	} else {
		printf('<TD>&nbsp;Example: No Data</TD>');
	}
	printf("</TR>\n");
?>
						<TR ALIGN="center">
							<TD><INPUT TYPE="submit" NAME="action" VALUE="Select">&nbsp;<INPUT TYPE="submit" NAME="action" VALUE="Create">&nbsp;<INPUT TYPE="submit" NAME="action" VALUE="Edit">&nbsp;<INPUT TYPE="submit" NAME="action" VALUE="Delete"></TD>
						</TR>
					</TABLE>
					</FORM>
				</TD>
			</TR>
		</TABLE>
<?php
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim600: fdm=marker
** vim: noet ts=3 sw=3
*/

?>
