<?php
/*
$Id: state.php 579 2014-05-17 21:23:44Z bhockney $
(C) 2003-2014 by Bob Hockney <zeus@ix.netcom.com>

state maintainence for webfwlog

This code is distributed under the terms of GNU GPL
*/

// Get state from saved session data if it exists

if (isset($config["session_save_path"]))
	session_save_path("{$config["session_save_path"]}");

session_name("webfwlog_sessid");
session_start();

if(!isset($_SESSION["sessiontest"])) { 
	if (isset($_GET["sessiontest"])) {
		if ($config["debug"]) include "include/debug.php";
		die("Cookies must be enabled or session IDs must be propagated transparently in order to use webfwlog");
	} else {
		$_SESSION["sessiontest"] = 1;
			$loc = "sessiontest=1&original_request=".urlencode("{$_SERVER["QUERY_STRING"]}");
			if (ini_get("session.use_trans_sid")) $loc = "$loc&" . SID;
			header("location: $self?$loc"); 
	}
} else {
	if (isset($_GET["original_request"])) {
		$loc = "";
		if ($_GET["original_request"]) $loc = "?{$_GET["original_request"]}";
		if (ini_get("session.use_trans_sid")) {
			if ($loc) {$loc = "$loc&";} else {$loc = "?";}
			$loc = "$loc" . SID;
		}
		$loc = "$self$loc";
		header("location: $loc");
	}
}
	
if ($config["db"] == "pgsql") {
	$link = db("open", "$database");
	$result = db("exists", "SELECT version() AS version", $link);

	$pg_version = array();
	$row = 0;
	$dbver = db("nextrow", $result);
	if (preg_match("/^ *PostgreSQL ([^ ]+) .*$/", "{$dbver["version"]}", $pgver))
		$pg_version = explode('.', "{$pgver[1]}", 3);	
	if ($pg_version[0] < 7 or ($pg_version[0] == 7 and $pg_version[1] < 1))
		die("PostgresSQL >= 7.1 is required\n");

	if (db("exists", "SELECT count(*) from pg_catalog.pg_namespace", $link)) {
		$config["have_namespace"] = 1;
		foreach (preg_split("/ +/","{$config["pgsql_data_table"]}") as $v)
			$data_t[] = "$data_d.$v";
		$reports = "{$config["pgsql_wfwl_schema"]}.reports";
		$hostnames = "{$config["pgsql_wfwl_schema"]}.hostnames";
		$services = "{$config["pgsql_wfwl_schema"]}.services";
		$webfwlog_aton = "{$config["pgsql_wfwl_schema"]}.webfwlog_aton";
		$webfwlog_ntoa = "{$config["pgsql_wfwl_schema"]}.webfwlog_ntoa";
	} else {
		$config["have_namespace"] = 0;
		$data_d = "";
		foreach (preg_split("/ +/","{$config["pgsql_data_table"]}") as $v)
			$data_t[] = "$v";
		$reports = "reports";
		$hostnames = "hostnames";
		$services = "services";
		$webfwlog_aton = "webfwlog_aton";
		$webfwlog_ntoa = "webfwlog_ntoa";
	}

	$inet_aton="$webfwlog_aton";
	$inet_ntoa="$webfwlog_ntoa";

} else if ($config["db"] == "mysql") {
	if (extension_loaded("mysqli")) {
		$config["mysql_close"] = "mysqli_close";
		$config["mysql_fetch_assoc"] = "mysqli_fetch_assoc";
		$config["mysql_fetch_row"] = "mysqli_fetch_row";
		$config["mysql_num_rows"] = "mysqli_num_rows";
		$config["mysql_connect"] = "mysqli_connect";
		$config["mysql_error"] = "mysqli_error";
		$config["mysql_query"] = "mysqli_query";
		$config["mysql_ext"] = "mysqli";
	} else {
		$config["mysql_close"] = "mysql_close";
		$config["mysql_fetch_assoc"] = "mysql_fetch_assoc";
		$config["mysql_fetch_row"] = "mysql_fetch_row";
		$config["mysql_num_rows"] = "mysql_num_rows";
		$config["mysql_connect"] = "mysql_connect";
		$config["mysql_error"] = "mysql_error";
		$config["mysql_query"] = "mysql_query";
		$config["mysql_ext"] = "mysql";
	}
	$link = db("open", "$database");
	$result = db("exists", "SELECT version() AS version", $link);
	$my_version = array();
	$dbver = db("nextrow", $result);
	if ($dbver)
		$my_version = explode('.', "{$dbver["version"]}", 3);

	if ($my_version[0] < 3 or
		(  $my_version[0] == 3 and $my_version[1] < 23) or
		(  $my_version[0] == 3 and $my_version[1] == 23 and $my_version[2] < 52)) {
			die("MySQL >= 3.23.52 is required\n"); 
	} else if ($my_version[0] == 4 and $my_version[1] == 0  and $my_version[2] < 12) {
			die("MySQL 4.0.xx >= 4.0.12 is required\n");
	} else if ($my_version[0] == 4 and $my_version[1] == 1  and $my_version[2] <  7) {
			die("MySQL 4.1.xx >= 4.1.7 is required\n");
	} else if ($my_version[0] == 5 and $my_version[1] == 0  and $my_version[2] < 15) {
			die("MySQL 5.0.xx >= 5.0.15 is required\n");
	} else if ($my_version[0] == 5 and $my_version[1] == 1  and $my_version[2] < 23) {
			die("MySQL 5.1.xx >= 5.1.23 is required\n");
	} else if ($my_version[0] == 5 and $my_version[1] == 5  and $my_version[2] < 8)
			die("MySQL 5.5.xx >= 5.5.8 is required\n");

	if ($my_version[0] >= 4)
		$config["have_cast"] = 1;

	if ($my_version[0] < 4 or $my_version[0] == 4 and $my_version[1] == 0) {
		$config['cast_char'] = "char";
	} else {
		$config['cast_char'] = "char(32)";
	}

	if ($config["mysql_ext"] == "mysqli")
		$config["mysql_escape_string"] = "mysqli_real_escape_string";
	else if ($version_php[0] > 4 or ($version_php[0] == 4 and $version_php[1] >= 3)) {
		$config["mysql_escape_string"] = "mysql_real_escape_string";
	} else {
		$config["mysql_escape_string"] = "mysql_escape_string";
	}

	if ($my_version[0] >= 5) {
		$result = db("statement", "SELECT routine_schema from INFORMATION_SCHEMA.routines where routine_name = 'wfwl_inet_pton'", $link);
		$routine_schema = db("nextrow", $result);
		if ($routine_schema) {
			$wfwl_db = "{$routine_schema["routine_schema"]}";
			$inet_pton="$wfwl_db.wfwl_inet_pton";
			$inet_ntop="$wfwl_db.wfwl_inet_ntop";
			$inet_contains="$wfwl_db.wfwl_inet_contains";
		} else {
			$inet_pton="wfwl_inet_pton";
			$inet_ntop="wfwl_inet_ntop";
			$inet_contains="wfwl_inet_contains";
		}
	}
}

$config["have_hostnames"] = 0;
$config["have_services"]  = 0;

if ($config["db"] <> "none")
	db("init_webfwlog", "", $link);

if (isset($_SESSION["fwlog"])) {
	$STATE = $_SESSION["fwlog"];
	unset ($STATE["action"]);
} else {
	$STATE = array();
}

if (get_magic_quotes_gpc()) {
   $_POST = array_map('stripslashes_deep', $_POST);
   $_GET = array_map('stripslashes_deep', $_GET);
}

// Combine input in order of precedence
$FWLOG = $_POST + $STATE;

if ($_POST) {
	// Clear parameters if new value is null
	foreach ($FWLOG as $param => $value) {
		if (!isset($_POST["$param"]) or $_POST["$param"] == "") {
			unset ($FWLOG["$param"]);
		}
	}
}

$options = array();
if (isset($_SESSION["opts"]))
	$options = $_SESSION["opts"];

if (isset($_POST["report_order"])) {
	$options["report_order"] = "{$_POST["report_order"]}";
} else {
	if (isset($options["report_order"])) {
		$FWLOG["report_order"] = "{$options["report_order"]}";
	} else {
		$FWLOG["report_order"] = "{$config["report_order"]}";
	}
}

if ($_POST)
	$level = 0;

// If running report from link, use those settings
if (isset($_GET["report"])) {
	$rownum = 0;
	$result = db("nextrow", db("statement", "SELECT definition FROM $reports WHERE code ='"
		.db("escape", "{$_GET['report']}", $link)."'", $link));
	if ($result["definition"]) {
		unset($_SESSION["fwlog_get"]);
		unset($FWLOG);
		$FWLOG = unserialize($result["definition"]);
		$FWLOG["report"] = $_GET["report"];
	} else {
		die ("<p>Report <strong>" . htmlspecialchars("{$_GET['report']}", ENT_QUOTES)
			. "</strong> not defined!<br></p>");
	}
}

if (isset($FWLOG["data_tables"])) {
	$ut = $FWLOG["data_tables"];
	foreach ($ut as $k => $v) {
		if (! $v) unset($ut[$k]);
	}
	if (count($ut) == 0) {
		unset ($FWLOG["data_tables"]);
	} else {
		$FWLOG["data_tables"] = $ut;
		$FWLOG["data_table"] = trim(implode(" ", $FWLOG["data_tables"]));
	}
}

if (isset($FWLOG["action"]) and "{$FWLOG["action"]}" == "Resolve Hosts")
	unset($FWLOG["reporttype"]);

require 'include/orders.php';

// Save state in session data -- not from GET
$_SESSION["fwlog"] = $FWLOG;

$state_get = array();

if ($_GET) {

    if (isset($_GET["keep_source"]) or isset($_GET["restore"])) {
		unset ($FWLOG["data_source"]);
		unset ($FWLOG["data_table"]);
		unset ($FWLOG["syslog_file"]);

		if (isset($_GET["keep_source"])) {
			$source_state = array();
			if (isset($_GET["data_source"]))
				$source_state["data_source"] = "{$_GET["data_source"]}";
			if (isset($_GET["data_table"]))
				$source_state["data_tables"] = explode (" ","{$_GET["data_table"]}");
			if (isset($_GET["syslog_file"]))
				$source_state["syslog_file"] = "{$_GET["syslog_file"]}";
			$_SESSION["fwlog_source"] = $source_state; 
		}

		if (isset($_GET["restore"]) and isset($_SESSION["fwlog_source"]))
			$FWLOG = $_SESSION["fwlog_source"] + $FWLOG;

		$FWLOG = $_GET + $FWLOG ;

	} else {
		if (!isset($_GET["level"]) or $_GET["level"] == "") {
			$_GET["level"] = 0;
		}

		if (isset($_SESSION["fwlog_get"])) {
			$state_get = $_SESSION["fwlog_get"];
		}

		if (isset($_GET["drilldown"])) {
			unset ($_GET["drilldown"]);
			$level = $_GET["level"] + 1;
			$state_get[$_GET["level"]] = $_GET;
		} else {
			$level = $_GET["level"];
		}

		// run through get levels in order to get current state of things
		$l = 0;
		while ($l <= $level - 1) {
			$old_get = $state_get[$l];
			unset($old_get["reporttype"]);
			$FWLOG = $old_get + $FWLOG ;
			foreach ($FWLOG as $param => $value) {
				if (isset($old_get["$param"]) and $old_get["$param"] == "") {
					unset ($FWLOG["$param"]);
				}
			}
			$FWLOG = sortit ($FWLOG);
			$l = $l + 1;
		}
		// Use parameters from GET first

		$FWLOG = $_GET + $FWLOG ;

		// Clear parameters if new value is null
		foreach ($FWLOG as $param => $value) {
			if (isset($_GET["$param"]) and $_GET["$param"] == "" ) {
				unset ($FWLOG["$param"]);
			}
		}
		require 'include/orders.php';
		$_SESSION["fwlog_get"] = $state_get;
	}	
}

if (isset($_GET["show_select_data_source"])) {
	$options["show_select_data_source"] = "{$_GET["show_select_data_source"]}";
} else {
	if (!isset($FWLOG["show_select_data_source"])) {
		$FWLOG["show_select_data_source"] = "{$config["show_select_data_source"]}";
	}
}

$FWLOG["syslog_dir"] = $config["syslog_dir"] . "/";

if (!isset($FWLOG["syslog_file"]))
	$FWLOG["syslog_file"] = "{$config["syslog_filespec"]}";

if (!isset($FWLOG['data_table']) and isset($FWLOG["ulog_table"])) {
	$FWLOG["data_table"] = $FWLOG["ulog_table"];
	unset ($FWLOG["ulog_table"]);
}

if (!isset($FWLOG["data_tables"]) and isset($FWLOG["data_table"]))
	$FWLOG["data_tables"] = preg_split("/ +/", "{$FWLOG["data_table"]}");

if (isset($FWLOG["data_table"])) {
	$data_t = array();
	foreach (preg_split("/ +/","{$FWLOG["data_table"]}") as $v) {
		if (! $v) continue;
		if ("$data_d" == "") {
			$data_t[] = "$v";
		} else {	
			$data_t[] = "$data_d.$v";
		}
	}
}

if (isset($FWLOG["data_source"]) and $FWLOG["data_source"] == "ulogd")
	$FWLOG["data_source"] = "db";

if (isset($FWLOG["update_all"])) // removed
	unset ($FWLOG["update_all"]);

if (isset($FWLOG["show_sql"])) {
	$FWLOG["be_verbose"] = "{$FWLOG["show_sql"]}"; // show_sql is deprecated
	unset ($FWLOG["show_sql"]);
}

// Remove leading 'AND' or 'OR' if present
if (isset($FWLOG["w_extra"]))
	$FWLOG["w_extra"] = preg_replace('/^\s*(AND|OR)\s+(.*)$/i','\\2',"{$FWLOG["w_extra"]}");

if (isset($config["allow_raw_sql"]) and $config["allow_raw_sql"] and isset($FWLOG["c_extra_value"])) {
	$c_extra_split["key"] = preg_replace("/^(.+) +[Aa][Ss] +['\"`]?[^'\"`]*['\"`]? *\$/","\\1","{$FWLOG["c_extra_value"]}");
	$c_extra_split["label"] = preg_replace("/^.+ +[Aa][Ss] +['\"`]?([^'\"`]*)['\"`]? *\$/","\\1","{$FWLOG["c_extra_value"]}");
	$shortnames["extra"] = "{$c_extra_split["label"]}";
	$longnames["extra"] = "{$FWLOG["c_extra_value"]}";
}

$FWLOG = $options + $FWLOG;
$_SESSION["opts"] = $options;

db("close", $link);

// vim:set ts=4:

?>
