<?php /* ToughLog */
$CVS[] =
'$Id$';

/* Messure time */
#$microtime = microtime();

require(".htconfig.php");
$pg_connect_param =
	 ($dbname?"dbname=$dbname":"")
	.($host?" host=$host":"")
	.($port?" port=$port":"")
	.($user?" user=$user":"")
	.($password?" password=$password":"")
;
$dbr = @pg_connect($pg_connect_param);
if ($dbr < 1) {
	printf(_("Connect to database '%s' failed."), $dbname);
	exit;
}

if (!function_exists("pg_escape_string")) {
	function pg_escape_string($p) {
		return $p;
	}
}

$EXECTIME = array();

function pg_exec_time( $dbh, $sql, $name) {
	global $EXECTIME;
	$t1 = microtime();
	$res = @pg_exec($dbh, $sql);
	#$res = 1;
	list($usec2, $sec2) = explode(" ", microtime()); 
	list($usec1, $sec1) = explode(" ", $t1); 
	$s = ((double)$sec2 + (double)$usec2) - ((double)$sec1 + (double)$usec1);
	$EXECTIME[] = array("name" => $name, "time" => $s, "sql" => $sql);
	return $res;
}

require("default.php");

function initparam($key, $default, $get, $nextlink = NULL) {
	$return = isset($get[$key]) ? $get[$key] : $default[$key];
	/* do some validation here... */
	if (is_array($nextlink) && ($return != $default[$key])) {
		$nextlink[$key] = $return;
	}
	return $return;
}


reset($_GET);
while (list($var,$value) = each($_GET)) {
	if (!array_search($var, $defaultparam, !true)) {
		printf(_("Bail out. '%s' is not a valid input parameter."), $var);
		exit;
	}
}

$linkparam = array();

/* ServerName */
$sn = initparam("sn", $defaultparam, $_GET, &$linkparam);
/* Path */
$pa = initparam("pa", $defaultparam, $_GET, &$linkparam);
/* Query */
$qu = initparam("qu", $defaultparam, $_GET, &$linkparam);
/* Absolute/Relative time */
$ar = initparam("ar", $defaultparam, $_GET, &$linkparam);
/* Interval */
$iv = initparam("iv", $defaultparam, $_GET);
/* From time */
$fr = initparam("fr", $defaultparam, $_GET);
/* To time */
$to = initparam("to", $defaultparam, $_GET);
/* Refresh */
$rf = initparam("rf", $defaultparam, $_GET, &$linkparam);
if ($ar == "re") {
	/* Relative time */
	if ($iv != $defaultparam[iv]) {
		$linkparam[iv] = $iv;
	}
} else {
	/* Absolute time */
	$linkparam[fr] = $fr;
	$linkparam[to] = $to;
	$rf = $defaultparam[rf];
	$linkparam[rf] = $rf;
}
/* Rows */
$ro = initparam("ro", $defaultparam, $_GET, &$linkparam);
/* Messure method */
$ms = initparam("ms", $defaultparam, $_GET, &$linkparam);
/* Directory levels */
$dl = initparam("dl", $defaultparam, $_GET, &$linkparam);
/* ForMat : ht(ml), cs(v) */
$fm = initparam("fm", $defaultparam, $_GET, &$linkparam);
$fd = initparam("fd", $defaultparam, $_GET, &$linkparam);
$td = initparam("td", $defaultparam, $_GET, &$linkparam);
/* Call function */
$fu = initparam("fu", $defaultparam, $_GET, &$linkparam);
/* Include Images */
$ii = initparam("ii", $defaultparam, $_GET, &$linkparam);
/* SubDir */
$sd = initparam("sd", $defaultparam, $_GET, &$linkparam);
/* Sub Path */
$sp = initparam("sp", $defaultparam, $_GET, &$linkparam);
/* Came From */
$cf = initparam("cf", $defaultparam, $_GET, &$linkparam);
/* Went To */
$wt = initparam("wt", $defaultparam, $_GET, &$linkparam);
/* SQL */
$sq = initparam("sq", $defaultparam, $_GET, &$linkparam);

/* sn = ServerName (example.com) */
if ($sn) {
	$sql = "SELECT hostnameid FROM hostname WHERE hostname='$sn'";
	$res = @pg_exec($dbr, $sql);
	if ($res > 0) {
		list($si) = pg_fetch_row($res, 0);
	}
}

#if (strlen(trim($dl)) > 0) {
#	$fu = "dl";
#}

/*
 * Variable init done
 */

/*
 * All functions require a time interval.
 */
$funcparam = array(
	"pf" => array(
		"name" => _("Popular files"),
		"require" => array(
		),
		"optional" => array(
			"sn"
		)
	),
	"dl" => array(
		"name" => _("Dir level"),
		"require" => array(
		),
		"optional" => array(
			"sn"
		)
	),
	"cf" => array(
		"name" => _("Came from"),
		"require" => array(
			"sn", /* HostName */
			"pa", /* Path */
			"qu"  /* Query */
		)
	),
	"wt" => array(
		"name" => _("Went to"),
		"require" => array(
			"sn", /* HostName */
			"pa", /* Path */
			"qu"  /* Query */
		)
	)
);

function joinparam($param, $extra = array(), $encode = true) {
	$return = "";
	if (is_array($extra) && count($extra)) {
		reset($extra);
		while (list($key,$value) = each($extra)) {
			$param[$key] = $value;
		}
	}
	reset($param);
	ksort($param);
	while (list($key,$value) = each($param)) {
		if ($return) {
			$return .= $encode ? "&amp;" : "&";
		}
		$return .= rawurlencode($key)."=".rawurlencode($value);
	}
	if ($return) {
		$return = "?".$return;
	}
	return $return;
}

function hostpathquery($url) {
	if (preg_match("|^([^/]+)([^?]+)(.*)$|", $url, $match)) {
		$res = array( $match[1], $match[2], $match[3]);
	} else {
		print("<h1>Error: function hostpathquery() regexp wrong: '$url'</h1>");
	}
	return $res;
}

/*
 * SQL section
 */

function print_pg_error($dbh, $res, $sql) {
	printf("<p>"._("Bail out: %d. Can not exec SQL:")."\n", $res);
	print("<pre>$sql\n");
	if (preg_match("/character ([0-9]+)$/", pg_last_error($dbh), $match)) {
		$pos = $match[1];
		if ($pos > 1) {
			$pos -= 1;
		}
		printf("%".$pos.".s_-^-_", " ");
	}
	print("</pre>\n");
	printf(pg_last_error($dbh));
	print("</p>\n");
}

function where_hitdatetime() {
	global $ar, $iv, $fr, $to;
	if ($ar == "re") {
		$where = "hitDateTime>('NOW'::TIMESTAMP WITH TIME ZONE-'$iv MIN'::INTERVAL)";
		$where .= " AND hitDateTime<('NOW'::TIMESTAMP WITH TIME ZONE)";
	} else {
		$where = "(hitDateTime>='$fr'::TIMESTAMP WITH TIME ZONE AND hitDateTime<='$to'::TIMESTAMP WITH TIME ZONE)";
	}
	return $where;
}

$trclass = array("even","odd");
$sym_in = "-&gt;";
$sym_out = "-&gt;";

function agenewest($dbh) {
	$sql = "SELECT 'NOW'-hitDateTime, TO_CHAR('NOW'-hitDateTime, 'HH24:MI:SS') AS \"Age of newest hit:\" FROM httplog ORDER BY hitDateTime DESC LIMIT 1";
	$res = @pg_exec_time($dbh, $sql, "pi");
	list($delay1,$delay2) = pg_fetch_row($res,0);
	return $delay1;
}

function q_total($dbh) {
	global $ms, $ii;
	if ($ms == "fs") {
		$ms_field = "sessionid";
	} else {
		$ms_field = "httplogid";
	}
	$where = where_hitdatetime();
	if ($ii == "f") {
		$where .= " AND contenttypeid IN (SELECT contenttypeid FROM contenttype WHERE canlink='t')";
	}
	$where .= " AND statusid!=404";
	$sql = "select count($ms_field) from (select $ms_field from httplog $where group by $ms_field) as foo";
	$res = @pg_exec_time($dbh, $sql, "tl");
	list($count) = pg_fetch_array($res);
	return $count;
}

function q_popularfile($dbh, $si) {
	global $ro, $dl, $ms, $ii, $cf, $wt;
	function select_as($arr) {
		while (list($key,$val) = each($arr)) {
			$res[] = "($val) AS $key";
		}
		return $res;
	}
	function from_($arr) {
		while (list($key,$val) = each($arr)) {
			$res[] = "$val $key";
		}
		return $res;
	}
	$sql[] = array();
	switch ($ms) {
		case "fs":
			$sql[select][count] = "COUNT(DISTINCT h.sessionid)";
			break;
		case "ht":
			$sql[select][count] = "COUNT(h.httpLogid)"; 
			break;
		default:
	}
	if ($dl == 0) {
		$sql[select][paqu] = "(hostname || path || query)";
	} else {
		$sql[select][paqu] = "hostname || substring(path from '^((/[^/]+){1,$dl})')"; 
	}
	$sql[from][h] = "httplog";
	$sql[from][hn] = "hostname";
	$sql[from][pa] = "path";
	if ($dl==0) {
		$sql[from][qu] = "query";
	}
	$sql[where][] = where_hitdatetime();
	# if FDIM-session
	if ($ms == "fs") {
		# if NOT Include images
		if ($ii == "f") {
			$sql[where][] = "h.contenttypeid IN (SELECT contenttypeid FROM contenttype WHERE canlink='t')";
		}
		$sql[where][] = "h.statusid!=404";
	}
	if ($cf) {
		$sql[from][rf] = "referer";
		$sql[where][] = "h.refererid = rf.refererid";
		if ($dl==0) {
			$sql[where][] = "rf.hostnameid=hn.hostnameid AND rf.pathid=pa.pathid AND rf.queryid=qu.queryid";
		} else {
			$sql[where][] = "rf.hostnameid=hn.hostnameid AND rf.pathid=pa.pathid";
		}
		list($sn,$pa,$qu) = hostpathquery($cf);
		$esc_sn = pg_escape_string($sn);
		$esc_pa = pg_escape_string($pa);
		$esc_qu = pg_escape_string($qu);
		$sql[where][] = "h.hostid = (SELECT hostnameid FROM hostname WHERE hostname='$esc_sn')";
		if ($dl == 0) {
			$sql[where][] = "h.pathid  = (SELECT pathid FROM path WHERE path = '$esc_pa')";
			$sql[where][] = "h.queryid = (SELECT queryid FROM query WHERE query='$esc_qu')";
		} else {
			$sql[where][] = "h.pathid IN (SELECT pathid FROM path WHERE path LIKE '$esc_pa/%' OR path='$esc_pa')";
		}
	} elseif ($wt) {
		list($sn,$pa,$qu) = hostpathquery($wt);
		$esc_sn = pg_escape_string($sn);
		$esc_pa = pg_escape_string($pa);
		$esc_qu = pg_escape_string($qu);
		$sql[where][] = "h.refererid IN (SELECT refererid FROM referer rf WHERE rf.hostnameid=(SELECT hostnameid FROM hostname WHERE hostname='$esc_sn') ".($dl==0 
		? "AND rf.pathid=(SELECT pathid FROM path WHERE path ='$esc_pa') AND rf.queryid=(SELECT queryid FROM query WHERE query ='$esc_qu')"
		: "AND rf.pathid IN (SELECT pathid FROM path WHERE path LIKE '$esc_pa/%' OR path = '$esc_pa')"
		)." ) ";
		if ($dl==0) {
			$sql[where][] = "h.servernameid=hn.hostnameid AND h.pathid=pa.pathid AND h.queryid=qu.queryid";
		} else {
			$sql[where][] = "h.servernameid=hn.hostnameid AND h.pathid=pa.pathid";
		}
	} else {
		$sql[where][] = "h.hostid=hn.hostnameid";
		$sql[where][] = "h.pathid=pa.pathid";
		if ($dl==0) {
			$sql[where][] = "h.queryid=qu.queryid";
		}
	}
	if ($si) {
		$sql[where][] = "h.servernameid=$si";
		$sql[where][] = "h.pathid=pa.pathid";
	}
	$sql[groupby][] = "paqu";
	$sql[orderby][] = "count DESC";
	if ($ro) {
		$sql[limit] = $ro;
	}
	$SQL = "SELECT ".join(", ", select_as($sql[select]));
	$SQL .= " FROM ".join(", ", from_($sql[from]));
	if ($sql[where]) {
		$SQL .= " WHERE (".join(") AND (", $sql[where]).")";
	}
	if ($sql[groupby]) {
		$SQL .= " GROUP BY ".join(", ", $sql[groupby]);
	}
	if ($sql[orderby]) {
		$SQL .= " ORDER BY ".join(", ", $sql[orderby]);
	}
	if ($sql[limit]) {
		$SQL .= " LIMIT ".$sql[limit];
	}
	#echo "<p>$SQL</p>"; flush();
	$res = @pg_exec_time($dbh, $SQL, "pf1");
	if ($res < 1) {
		printf(_("Bail out: %d. Can not exec SQL:<br> %s<p>\n"), $res, $SQL);
		printf(pg_last_error($dbh));
		exit;
	}
	return $res;
}

function ht_popularfile($res) {
	global $ar, $iv, $fr, $to, $funcparam, $linkparam, $trclass, $sym_in, $sym_out;
	if (pg_numrows($res) < 1)
		return;
	$printhead = true;
	printf("<table summary=\"Result\">\n");
	printf("<caption>Popular files - ");
	if ($ar == "re") {
		printf(_("Most visited pages within %d minutes"), $iv);
	} else {
		printf(_("Most visited pages between %s and %s"), $fr, $to);
	}
	printf("</caption>\n");
	while ($row = pg_fetch_array($res)) {
		$camefromparam = $linkparam;
		$camefromparam[fu] = "cf";
		$wenttoparam = $linkparam;
		$wenttoparam[fu] = "wt";
		if ($printhead) {
			printf("<thead>\n<tr>\n");
			printf(" <th>%s</th>\n", $funcparam[cf][name]);
			printf(" <th>%s</th>\n", _("Count"));
			printf(" <th title=\"%s\">%s</th>\n", _("Uniform Resource Location"), _("URL"));
			printf(" <th>%s</th>\n", $funcparam[wt][name]);
			printf("</tr>\n</thead>\n<tbody>\n");
			$printhead = false;
		}
		if (preg_match("|^([^/]+)([^?]+)(.*)$|", $row[paqu], $match)) {
			$camefromparam[sn] = $match[1];
			$camefromparam[pa] = $match[2];
			$camefromparam[qu] = $match[3];
			$wenttoparam[sn] = $match[1];
			$wenttoparam[pa] = $match[2];
			$wenttoparam[qu] = $match[3];
		}
		printf("<tr class=\"%s\">\n", $trclass[++$tr%2]);
		printf(" <td class=\"camefrom\"><a href=\"%s\">%s</a></td>\n", joinparam($camefromparam), $sym_in);
		printf(" <td class=\"count\">%s</td>\n", $row[count]);
		printf(" <td class=\"url\"><a href=\"http://%s\">%s</a></td>\n", $row[hostname].$row[paqu], $row[hostname].$row[paqu]);
		printf(" <td class=\"wentto\"><a href=\"%s\">%s</a></td>\n", joinparam($wenttoparam), $sym_out);
		printf("</tr>\n");
	}
	printf("</tbody>\n</table>\n");
	pg_freeresult($res);
	$res = 0;
	return $res;
}

function q_camefrom($dbh) {
/*
 * sn = example.com
 * pa = index.php
 * qu = ?a=1
 */
 	global $sn, $pa, $qu, $ro, $dl;
 	$select = "SELECT COUNT(h.refererid) AS \"Count\", hn.hostname ||";
	if ($dl == 0) {
		$select .= " pa.path || qu.query";
	} else {
		$select .= " substring((pa.path || qu.query) from '^((/[^/]+){1,$dl})')";
	}
	$select .= " AS \"RefererHost\"";
	$from = "FROM httplog h, hostname hn, referer rf, path pa";
	if ($dl == 0) {
		$from .= ", query qu";
	}
	$where = where_hitdatetime();
	$where .= " and h.refererid = rf.refererid";
	$where .= " and rf.hostnameid = hn.hostnameid";
	$where .= " and rf.pathid = pa.pathid";
	if ($dl == 0) {
		$where .= " and rf.queryid = qu.queryid";
	}
	#$where .= " and h.servernameid = (select hostnameid from hostname where hostname='".pg_escape_string($sn)."')";
	$where .= " and h.hostid = (select hostnameid from hostname where hostname='".pg_escape_string($sn)."')";
	if ($dl == 0) {
		$where .= " and h.pathid  = (select pathid from path where path = '".pg_escape_string($pa)."')";
		$where .= " and h.queryid = (select queryid from query where query='".pg_escape_string($qu)."')";
	} else {
		$where .= " and h.pathid in (select pathid from path where path ~ '^".pg_escape_string($pa)."')";
	}
	$groupby = "GROUP BY \"RefererHost\"";
	$orderby = "ORDER BY \"Count\" DESC, \"RefererHost\" ASC";
	if ($ro) {
		$limit = "LIMIT $ro";
	}
	$sql = "$select $from $where $groupby $orderby $limit";
	$res = @pg_exec_time($dbh, $sql, "cf");
	if (!$res) {
		printf("<h2>%s</h2>", pg_last_error($dbh));
	}
	return $res;
}

function q_wentto($dbh) {
/*
 * sn = example.com
 * pa = index.php
 * qu = ?a=1
 */
 	global $sn, $pa, $qu, $ro, $ii;
 	$select = "SELECT COUNT(h.sessionid) AS \"Count\", hn.hostname || pa.path || qu.query AS \"PathQuery\"";
	$from = "FROM httplog h, hostname hn, path pa, query qu";
	$where = where_hitdatetime();
	$where .= " and h.hostid = hn.hostnameid";
	$where .= " and h.pathid = pa.pathid";
	$where .= " and h.queryid = qu.queryid";
	$where .= " and h.refererid = (
		select refererid from referer rf where
			rf.hostnameid=(select hostnameid from hostname where hostname='".pg_escape_string($sn)."')
			AND rf.pathid=(select pathid from path where path ='".pg_escape_string($pa)."')
			AND rf.queryid=(select queryid from query where query ='".pg_escape_string($qu)."')
			)";
	#$where .= " and h.servernameid = (select hostnameid from hostname where hostname='".pg_escape_string($sn)."')";
	$where .= " and h.hostid = (select hostnameid from hostname where hostname='".pg_escape_string($sn)."')";
	if ($ii == "f") {
		$where .= " and h.contenttypeid in (select contenttypeid from contenttype where canlink='t')";
	}
	$groupby = "GROUP BY \"PathQuery\"";
	$orderby = "ORDER BY \"Count\" DESC, \"PathQuery\" ASC";
	if ($ro) {
		$limit = "LIMIT $ro";
	}
	$sql = "$select $from $where $groupby $orderby $limit";
	#printf("<p><tt>$sql</tt></p>");
	$res = @pg_exec_time($dbh, $sql, "wt");
	if (!$res) {
		printf("<h2>Error: %s</h2>", pg_last_error($dbh));
	}
	return $res;
}

function ht_camefrom($res) {
}

function ht_generic($res) {
	global $trclass, $fu, $funcparam, $ar, $iv, $fr, $to, $linkparam, $cf, $wt;
	printf("<table summary=\"Generic dump\">\n");
	if ($cf) {
		$title = "Went to '$cf'";
	} elseif ($wt) {
		$title = "Came from '$wt'";
	} else {
		$title = "Pop files";
	}
	printf("<caption>%s", $title);
	if ($ar == "re") {
		printf(_(" - within %d minutes"), $iv);
	} else {
		printf(_(" - between %s and %s"), $fr, $to);
	}
	printf(" - %d rows</caption>\n", pg_numrows($res));
	printf("<thead>\n<tr>\n");
	print("<th>From</th>\n");
	print("<th>Count</th>\n");
	print("<th>URL</th>\n");
	print("<th>To</th>\n");
	printf("</tr>\n</thead>\n<tbody>\n");
	while ($row = pg_fetch_array($res)) {
		printf("<tr class=\"%s\">\n", $trclass[++$tr%2]);
		$cf_href = "<a href=\"".joinparam($linkparam,array("cf"=>$row[paqu],"wt"=>""))."\"> -&gt; </a>";
		print("<td>".( $row[paqu] ? $cf_href : " - ")."</td>\n");
		print("<td>$row[count]</td>\n");
		$url = $row[paqu];
		if (strlen($url)>80) {
			$url = substr($url,0,76)."...";
		}
		print("<td><a href=\"http://$row[paqu]\" title=\"$row[paqu]\">$url</a></td>\n");
		print("<td><a href=\"".joinparam($linkparam,array("wt"=>$row[paqu],"cf"=>""))."\"> -&gt; </a></td>\n");
		printf("</tr>\n");
	}
	printf("</tbody>\n</table>\n");
	pg_freeresult($res);
}

/* CSV - Generic output */
function cs_generic($res) {
	global $fd, $td;
	for ($i=0; $i<pg_numfields($res); $i++) {
		if ($i) {
			print($fd);
		}
		print($td.pg_fieldname($res,$i).$td);
	}
	print("\n");
	while ($row = pg_fetch_row($res)) {
		$n = 0;
		while (list($key, $value) = each($row)) {
			# If it NOT integer or float then quote
			$quote = !preg_match("/^[0-9.]+$/", $value);
			if ($n) {
				print($fd); # Field Delimiter
			}
			# Convert " -> ""
			$value = str_replace($td, $td.$td, $value);
			print( ($quote?$td:"").$value.($quote?$td:"") );
			$n++;
		}
		print("\n");
	}
	pg_freeresult($res);
	exit;
}

function q_dirlevel_old($dbh) {
	global $ro, $dl, $sn, $si, $sd, $sp;
	$sql = "SELECT pathid, substring(path, '^((/[^/]+){0,$dl}(/|$))') as \"niveau\"";
	$sql .= " into temp table niveaudir";
	$sql .= " from path";
	$where = "";
	if (strlen($sd)) {
		$where .= " length(substring(path, '^($sd)'))>0";
	}
	if (strlen($sp)) {
		if ($where) {
			$where .= " and ";
		}
		$where .= "length(substring(path, '($sp)'))>0";
	}
	if ($where) {
		$sql .= " where $where";
	}
	$res = @pg_exec_time($dbh, $sql, "dl2");
	if ($res < 1) {
		print_pg_error($dbh, $res, $sql);
		exit;
	}
	$select = "SELECT distinct sessionid,";
	$select .= " extract(year from hitDateTime) || '-' || extract(month from hitDateTime) as \"yearmonth\",";
	$select .= " nd.niveau";
	$into = "INTO TEMP distinct_session";
	$from = "FROM niveaudir nd, httplog h";
	$where = " WHERE ";
	$where .= where_hitdatetime();
	$where .= " AND h.pathid=nd.pathid";
	#$where .= " and httplog.servernameid=$si";
	$where .= " AND h.hostid=(SELECT hostnameid FROM hostname WHERE hostname='$sn')";
	$where .= " AND h.statusid!=404";
	$where .= " AND h.contenttypeid IN (SELECT contenttypeid FROM contenttype WHERE canlink='t')";
	/*
	if (strlen($sd)) {
		$where .= " and length(substring(nd.niveau, '^($sd)'))>0";
	}
	*/
	if (strlen($sp)) {
		$where .= " and length(substring(nd.niveau, '($sp)'))>0";
	}
	$sql = "$select $into $from $where";
	$res = @pg_exec_time($dbh, $sql, "dl3");
	if ($res < 1) {
		print_pg_error($dbh, $res, $sql);
		exit;
	}
	$select = "SELECT";
	$select .= " count(sessionid), yearmonth, niveau AS paqu";
	$from = "FROM distinct_session";
	$groupby = "GROUP BY yearmonth, niveau";
	$orderby = "ORDER BY count DESC, niveau, yearmonth";
	$limit = "LIMIT $ro";
	$sql = "$select $from $groupby $orderby $limit";
	$res = pg_exec_time($dbh, $sql, "dl4");
	if ($res < 1) {
		print_pg_error($dbh, $res, $sql);
		exit;
	}
	#$sql = "DROP TABLE niveaudir";
	#$res2 = @pg_exec_time($dbh, $sql, "dl5");
	#$sql = "DROP TABLE distinct_session";
	#$res2 = @pg_exec_time($dbh, $sql, "dl5");
	return $res;
}

function q_dirlevel($dbh) {
	global $dl,$ro;
	$sql = "
select 
	count(ses) as \"count\",
	path
from (
	select
		h.sessionid as \"ses\",
		pa.path
	from
		httplog h,
		path pa,
		pathlevel pl
	where
		pa.slashcount = ${dl}
		".where_hitdatetime()."
		and h.pathid = pl.pathid 
		and pl.levelid = pa.pathid
	group by
		h.sessionid,
		pa.path
) as \"foo\"
group by
	path
order by
	count desc
limit
	${ro}
";
	echo "<h3>$sql</h3>";
}

if ($fm == "ht") {
?><!DOCTYPE HTML PUBLIC "ISO/IEC 15445:2000//DTD HTML//EN">
<!--
<?php foreach($CVS as $cvs) printf("$cvs\n"); ?>
-->
<html><head><title>
ToughLog<?php
	if ($funcparam[$fu][name]) {
		printf(" - %s", $funcparam[$fu][name]);
	}
	if ($linkparam[ro]) {
		printf(_(" - %d rows"), $linkparam[ro]);
	}
	if ($sn) {
		printf(" - %s", $sn.$pa.$qu);
	}
	if ($rf) {
		printf(" - "._("Refresh %d"), $rf);
	}
	printf(" - Age of newest hit %s", agenewest($dbr));
	#printf(date(" - Y-m-d H:i:s"));
?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
	if ($rf) {
		printf("<meta http-equiv=\"refresh\" content=\"%d\">\n", $rf);
	}
?>
<link rel="stylesheet" title="Default" href="default.css" type="text/css" media="all">
<link rel="stylesheet" title="Alternative" href="alternative.css" type="text/css" media="all">
</head><body>
<h1 id="toughlogname">ToughLog</h1>
<?php

#if ($_GET) print_r($_GET);
#print("<p class=\"totalcount\">".q_total($dbr)."</p>");

if ($sn) {
	printf("<h3 id=\"detailsabout\">Details about: <a href=\"http://%s%s%s\">%s%s%s</a></h3>\n", $sn, $pa, $qu, $sn, $pa, $qu);
}
} # End-Of-HTML header section

/* CSV - Comma Seperated Values */
if ($fm == "cs") {
	function row2csv($row) {
		global $fd, $td;
		foreach ($row as $r) {
			$row2[] = $td.$r.$td;
		}
		return implode($fd, $row2)."\n";
	}
	header("Content-Type: application/vnd.ms-excel");
	header("Content-Disposition: attachment; filename=\"".date("Y-m-d_H:i:s")."_$fu.csv\"");
	header("Pragma: no-cache");
	header("Expires: 0");

	print(row2csv(array("ToughLog",   "CSV format")));
	print(row2csv(array("Date",       date("Y-m-d H:i:s"))));
	print(row2csv(array("RequestURL", "http://".$_SERVER["HTTP_HOST"].$PHP_SELF.joinparam($linkparam,0,false) )));
	print(row2csv(array("Function",   $funcparam[$fu][name]." (".$fu.")" )));
	print("\n");
	/* Force output and let the user type a filename while we find the data */
	flush();
}

/*
 ************************************************************************
 * Main section								*
 ************************************************************************
 */

if (isset($_GET)) {
	switch ($fu) {
		case "pf":
			$res = q_popularfile($dbr, $si);
			if ($fm == "ht") {
				#ht_popularfile($res);
				ht_generic($res);
			} elseif ($fm == "cs") {
				cs_generic($res);
			}
			break;
		case "cf":
			$res = q_camefrom($dbr);
			if ($fm == "ht") {
				#ht_camefrom($res);
				ht_generic($res);
			} elseif ($fm == "cs") {
				cs_generic($res);
			}
			break;
		case "wt":
			$res = q_wentto($dbr);
			ht_generic($res);
			break;
		case "dl":
			$res = q_dirlevel($dbr);
			exit;
			if ($fm == "ht") {
				ht_generic($res);
			} elseif ($fm == "cs") {
				cs_generic($res);
			}
			break;
	}
}

pg_close($dbr);

if ($sq=="t" && count($EXECTIME)) {
	printf("<table summary=\"SQL\" id=\"sqldebug\">\n");
	printf("<caption>SQL Debug</caption>\n");
	printf("<thead><tr>\n");
	$row = $EXECTIME[0];
	while (list($head) = each($row)) {
		print("<th>$head</th>\n");
	}
	printf("</tr></thead>\n<tbody>\n");
	reset($EXECTIME);
	foreach ($EXECTIME as $block) {
		printf("<tr class=\"%s\">\n", $trclass[++$tr%2]);
		while (list(,$data) = each($block)) {
			print("<td><tt>$data</tt></td>\n");
		}
		print("</tr>\n");
	}
	print("</tbody></table>\n");
}

function valueselected( $selected, $default ) {
	$return = "value=\"$default\"";
	if ($selected == $default) {
		$return .= " selected";
	}
	return $return;
}

print("<div class=\"clickoption\">\n");
printf("<p id=\"homelink\" title=\"%s\"><a href=\"./\">%s</a></p>\n",
	_("Go home"),
	_("Home")
	);
printf("<p id=\"csvlink\" title=\"%s\"><a href=\"%s\">CSV</a></p>\n",
	_("Export as CSV - Comma Separated Values"),
	joinparam($linkparam,array("fm"=>"cs"))
	);

printf("<p id=\"bookmarkthis\" title=\"%s\"><a href=\"%s\">%s</a></p>\n",
	_("For later retrieval, click and bookmark this short link."),
	joinparam($linkparam),
	_("Short link."));
print("<p><a href=\"#ctrl-1\">Control</a></p>\n");
print("</div>\n");

?>

<form action="" method="get" accept-charset="utf-8" class="control" id="ctrl-1">
<input type="hidden" name="sq" value="<?=$sq?>">
<input type="hidden" name="fu" value="<?=$fu?>">
<input type="hidden" name="sn" value="<?=$sn?>">
<input type="hidden" name="pa" value="<?=$pa?>">
<input type="hidden" name="qu" value="<?=$qu?>">
<input type="hidden" name="cf" value="<?=$cf?>">
<input type="hidden" name="wt" value="<?=$wt?>">
<div id="periode">
<p class="subhead" id="head-periode" title="<?=_("Specify period")?>">Periode</p>
<input type="radio" name="ar" value="ab" class="radio" id="abs"<?=($ar=="ab"?" checked":"")?>/> 
<span><?=_("Absolute date and time")?></span>
<br/>
<span class="label" id="from-label" title="Start time"><?=_("From:")?></span>
<input type="text" name="fr" value="<?=$fr?>" class="text-date" id="input-fr" title="<?=_("Enter ISO-8601 date and time")?>"/>
<br/>
<span class="label" id="to-label"><?=_("To:")?></span>
<input type="text" name="to" value="<?=$to?>" class="text-date" id="input-to"/>
<br/>
<input type="radio" name="ar" value="re" class="radio" id="rel"<?=($ar=="re"?" checked":"")?> />
<span><?=_("Relative date and time from now")?></span>
<br/>
<span class="label" id="intervallabel"><?=_("Interval")?>:</span>
<select name="iv" id="interval">
<option <?=valueselected($iv,1)?>><?=_("1 minute")?></option>
<option <?=valueselected($iv,10)?>><?=_("10 minutes")?></option>
<option <?=valueselected($iv,30)?>><?=_("30 minutes")?></option>
<option <?=valueselected($iv,60)?>><?=_("1 hour")?></option>
<option <?=valueselected($iv,120)?>><?=_("2 hours")?></option>
<option <?=valueselected($iv,360)?>><?=_("6 hours")?></option>
<option <?=valueselected($iv,720)?>><?=_("12 hours")?></option>
<option <?=valueselected($iv,1440)?>><?=_("24 hours")?></option>
</select>
<!--
<input type="submit" name="b2" value="5" class="half" id="rows-half"/>
<input type="submit" name="b3" value="20" class="double" id="rows-double"/>
<br/>
-->
<span><?=_("Auto refresh")?></span>
<select name="rf" title="<?=_("Only active with relative time")?>">
<option <?=valueselected($rf,0)?>><?=_("Off")?></option>
<option <?=valueselected($rf,10)?>><?=_("10 seconds")?></option>
<option <?=valueselected($rf,30)?>><?=_("30 seconds")?></option>
<option <?=valueselected($rf,60)?>><?=_("1 minute")?></option>
<option <?=valueselected($rf,120)?>><?=_("2 minutes")?></option>
</select>
<br/>
<span class="label" id="rows-label"><?=_("Rows:")?></span>
<input type="text" name="ro" value="<?=$ro?>" size="6" class="number" id="rows-input"/>
<a href="<?=joinparam($linkparam,array("ro"=>($ro>2?intval($ro/2):1)))?>"><?=($ro>2?intval($ro/2):1)?></a>
<a href="<?=joinparam($linkparam,array("ro"=>$ro*2))?>"><?=$ro*2?></a>
</div>
<div id="messure">
<p class="subhead" id="head-messure">Messure</p>
<input type="radio" name="ms" value="fs" class="radio" id="fdimses"<?=($ms=="fs"?" checked":"")?> />
<span><?=_("FDIM sessions")?></span>
<br/>
<!--
<input type="radio" name="ms" value="fu" class="radio" id="fdimusr"/>
<span><?=_("FDIM uniq visitors")?></span>
<br/>
-->
<input type="radio" name="ms" value="ht" class="radio" id="hits"<?=($ms=="ht"?" checked":"")?> />
<span><?=_("Hits")?></span>
</div>
<div id="presentation">
<p class="subhead" id="head-presentation"><?=_("Presentation")?></p>
<span class="label" id="dirlevel-label"><?=_("Directory levels")?></span>
<input type="text" name="dl" value="<?=$dl?>" class="presentation" id="dirlevel"
title="<?=_("Number of directory levels")?>"/>
<br/>
<!--
<h3>Sort by</h3>
<input type="radio" name="so" value="co" class="radio" id="sort-count" checked />
<span><?=_("Count")?></span>
<br/>
<input type="radio" name="so" value="ur" class="radio" id="sort-url"/>
<span title="<?=_("Uniform Resource Location")?>"><?=_("URL")?></span>
-->
</div>
<div id="limitations">
<p class="subhead" id="head-limitations"><?=_("Limitations")?></p>
<span><?=_("Sub-dir")?></span>
<input type="text" name="sd" value="<?=$sd?>" class="text" id="subdir"
title="<?=_("Start of the directory path")?>"/>
<br/>
<span><?=_("Sub-path")?></span>
<input type="text" name="sp" value="<?=$sp?>" class="text" id="substring"
title="<?=_("Partial text of the directory path")?>"/>
<br/>
<!--
<input type="checkbox" name="rb" value="t" class="checkbox" id="robots" checked disabled/>
<span title="<?=_("Not implemented yet")?>"><?=_("Include robots")?></span>
<br/>
-->
<input type="checkbox" name="ii" value="t" class="checkbox" id="clickable"<?=($ii=="t"?" checked":"")?> />
<span><?=_("Include images and PDF files.")?></span>
<br/>
</div>
<div id="output">
<p class="subhead" id="outputcl"><?=_("Output")?></p>
<span class="label" id="outformat"><?=_("Format")?>:</span>
<select name="fm" id="format">
<option <?=valueselected($fm,"ht")?>><?=_("HTML")?></option>
<option <?=valueselected($fm,"cs")?>><?=_("CSV")?></option>
</select>
<br/>
<input type="submit" name="b1" value="<?=_("Submit")?>"/>
</div>
</form>

<?php #phpinfo(INFO_VARIABLES) ?>

<!--
<div class="banner" id="banner-top"><img src="vmesa.png" alt="Banner top"/></div>
<div class="banner" id="banner-bottom"><img src="vmesa.png" alt="Banner bottom"/></div>
-->
<div class="w3ref"><a href="http://validator.w3.org/check/referer">ISO/IEC 15445</a></div>
<?php
if ($microtime) {
	list($usec2, $sec2) = explode(" ", microtime()); 
	list($usec1, $sec1) = explode(" ", $microtime); 
	$s = ((double)$sec2 + (double)$usec2) - ((double)$sec1 + (double)$usec1);
        echo "\n<!-- Load and execute time: $s sec. -->\n";
}
?>
</body></html>
