<?php

$tigurl = $_SERVER["tig_url"];
$tigtitle = $_SERVER["tig_title"];
$tigwelcome = $_SERVER["tig_welcome"];
$tigskiplist = split(" ", $_SERVER["tig_skiplist"]);

if (!$tigurl || !$tigwelcome || !$tigtitle || !$tigskiplist) {
	print("<html>\n<head>\n<title>tig error</title>\n</head>\n<body>\n");
	print "tig configuration missing or invalid.\n";
	print("</body>\n</html>\n");
	exit();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title><?php print("$tigtitle"); ?></title>
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" title="tig" type="text/css" href="/tig/tig.css" />
</head>
<body>
<div id="mainpage">
<?php

$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$query = addslashes(rawurldecode($_SERVER["QUERY_STRING"]));
$uri = addslashes(rawurldecode($_SERVER["REQUEST_URI"]));
$myname = basename($_SERVER["PHP_SELF"]);
$self = $_SERVER["PHP_SELF"];


/* for broken UA workarounds :( */
if (stristr($_SERVER[HTTP_USER_AGENT], "MSIE 6.")) $ie6=1;

/* strip of the script name from the uri, if any */
$uri = preg_replace("/^\/[^?]*\?/", "", $uri);

/* resolve any ".", ".." or soft links */
$uri = str_replace($root, "", realpath($root . $uri));

/* if a query is present, the user has requested an image, if not, its just a dir */
if ($query) {
	#print("DEBUG: query is present.<br />\n");
	$mypath = dirname(realpath($root . "/" . $uri));
        $myimage = realpath($root . "/" . $uri);
} else {
	$mypath = realpath($root . "/" . $uri);
}


#print("DEBUG: query: ->$query<-<br />\n");
#print("DEBUG: uri: ->$uri<-<br />\n");
#print("DEBUG: root: ->$root<-<br />\n");
#print("DEBUG: mypath is: ->$mypath<-<br />\n");
#print("DEBUG: the image is: ->$myimage<-<br />\n");
#print("DEBUG: myname: ->$myname<-<br />\n");
#print("DEBUG: self: ->$self<-<br />\n");
#print("<pre style=\"text-align: left;\">");
#print_r($_SERVER);
#print_r($_GET);
#print("</pre>)";


/* sanity checking */
if (!$mypath || 
    !is_dir($mypath) || 
    strncmp($root, $mypath . "/", strlen($root)) ||
    ($query && !$myimage) || 
    ($myimage && !is_file($myimage))) 
{
	print("<p style=\"font-size: 1.2cm; font-weight: bold;\">Suddenly the Dungeon collapses!! - You die...</p>\n");
	print("</div>\n</body>\n</html>\n");
	exit();
}


/* open the dir and create a sorted listing of all files and dirs */
$entrys = array();
$dirs = 0;
$images = 0;

chdir($mypath);
$d = opendir(".");

while ($entry = readdir($d)) {
	if ($entry[0] == "." || $entry == $myname || in_array($entry, $tigskiplist)) continue;
	$entrys["$entry"] = is_dir($entry);
	if (is_dir($entry)) {
		$dirs++;
	} else {
		$images++;
	}
}

closedir($d);

/* XXX: FIXME: support custon sorting of dirs here */
#ksort($entrys, SORT_NUMERIC);
ksort($entrys, SORT_STRING);


/* print the location (or the welcometext, if we are at the root) */
print("<div class=\"location\">");
if ($uri != "") {
	print("<a href=\"/\">$tigurl</a> &gt; ");
	foreach(explode("/", dirname(preg_replace("/^\/[^\/]*\?/", "", $uri))) as $dir) {
		if ($dir) {
			$tmp = preg_replace('/_/', ' ', $dir);
			print("<a href=\"/" . tigencode($parent . $dir) . "/\">$tmp</a> &gt; ");
			$parent = $parent . $dir . "/";
		}
	}
	print(basename($uri));
} else {
	print($tigwelcome);
}


/* are we viewing an image? */
if ($query) {

	$image = basename($uri);
	$dir = dirname($uri);

	if ( $dir != "/" ) {
		$dir = $dir . "/";
	}

	/* link to the fullsize image if it exists. fallback to the regular one otherwise */
	$fullsize = $dir . ".fullsize/" . $image;
	if (!is_readable(".fullsize/" . $image)) $fullsize = $uri;

	#print("DEBUG: the image is: ->$image<-<br />\n");
	#print("DEBUG: the path is: ->$dir<-<br />\n");
	#print("DEBUG: the fullsize image is: ->$fullsize<-<br />\n");
	#print("DEBUG: the uri is: ->$uri<-<br />\n");

	/* figure out who we are, and who is before and after us */
	$i = 0;
	foreach ($entrys as $entry => $isdir) {
		if ($isdir) continue;
		$i++;
		if ($entry == $image) {
			$number = $i;
			$prev = $prevtmp;
			$getnext = 1;
		} elseif ($getnext == 1) {
			$next = $entry;
			$getnext = 0;
		}
		$prevtmp = $entry;
	}

	/* print the page */
	print(" (#$number of $images)<br />\n");

	/* this is the div opened before the if-statement */
	print("</div>\n");

	nav($dir, $prev, $next);
	if ( preg_match('/\.avi$/i', $fullsize) ) {
		print("<a href=\"" . tigencode($fullsize) . "\"><embed src=\"" . tigencode($uri) . "\" alt=\"$image\" /></a><br />\n");
	} else {
		print("<a href=\"" . tigencode($fullsize) . "\"><img src=\"" . tigencode($uri) . "\" alt=\"$image\" /></a><br />\n");
	}
	nav($dir, $prev, $next);


/* ok, then we print an index. print all of the directories */
} else {

	/* this is the div opened before the if-statement */
	print("</div>\n");

	if ($uri != "/") print("<div class=\"nav\"><a href=\"..\">[up one level]</a><br />&nbsp;</div>\n");


	if ($dirs) {
		if (1) print("<center><table class=\"table\"><tr><td>\n");
		print("<div class=\"dirs\">\n");
		foreach ($entrys as $entry => $isdir) {
			if ($isdir) {
				$tmp = preg_replace('/_/', ' ', $entry);
				print("<img class=\"dirimg\" src=\"/tig/folder.gif\" alt=\"[DIR]\" /><a href=\"" . tigencode($entry) . "/\">$tmp</a><br />\n");
			}
		}
		print("</div>\n");
		if (1) print("</td></tr></table></center>\n");
	}

	if ($ie6 && $dirs && $images) print("<div id=\"pad20\">&nbsp;</div>\n");

	if ($images) {
		if ($ie6) print("<center><table class=\"table\"><tr><td>\n");
		print("<div class=\"images\">\n");

		if (is_readable("thumbs/thumbs.jpg")) {
			$sprites=2;
			$tx = 0;
			$ty = 0;
		} elseif (is_readable("thumbs/thumbs0.jpg")) {
			$sprites=1;
			$tf = 0;
			$ti = 0;
		}

		foreach ($entrys as $entry => $isdir) {
			if (!$isdir) {
				/* create a pretty name for printing */
				$tmp = preg_replace('/(.*)\.(.*)/', '${1}', $entry);
				$tmp = preg_replace('/_/', ' ', $tmp);

				if ($sprites == 1) {
					print("<div class=\"tn\"><div class=\"tni\" style=\"background-image: url(thumbs/thumbs" . $tf . ".jpg); background-position: 0px -" . $ti * 120 . "px;\"><a href=\"" . $self . "?" . tigencode($uri . "/" . $entry) . "\"><img src=\"/tig/trans.gif\" alt=\"\"></div><br />$tmp</a></div>\n");
					$ti = $ti + 1;
					if ( $ti == 100 ) {
						$ti = 0;
						$tf = $tf + 100;
					} 
				} elseif ($sprites == 2) {
					print("<div class=\"tn\"><div class=\"tni\" style=\"background-image: url(thumbs/thumbs.jpg); background-position: -" . $tx * 160 . "px -" . $ty * 120 . "px;\"><a href=\"" . $self . "?" . tigencode($uri . "/" . $entry) . "\"><img src=\"/tig/trans.gif\" alt=\"\"></div><br />$tmp</a></div>\n");
					$tx = $tx + 1;
					if ( $tx == 10 ) {
						$tx = 0;
						$ty = $ty + 1;
					} 
				} else {
					$thumb = preg_replace('/(.*)\.(.*)/', 'thumbs/${1}.jpg', $entry);
					if (!is_readable($thumb)) $thumb = "/tig/no_thumb.png";
					print("<div class=\"tn\"><a href=\"" . $self . "?" . tigencode($uri . "/" . $entry) . "\"><img src=\"" . tigencode($thumb) . "\" alt=\"$tmp\" /><br />$tmp</a></div>\n");
				}
			}
		}
		print("<div class=\"clear\"></div>");
		print("</div>\n");
		if ($ie6) print("</td></tr></table></center>\n");
	}

	if (!$images && !$dirs) print("<div class=\"images\"><br />Sorry, this dir is empty.<br /><br /></div>\n");

	if ($uri != "/") print("<div class=\"nav\"><a href=\"..\">[up one level]</a><br /></div>\n");
}
?>
</div>
</body>
</html>


<?php
function nav($dir, $prev, $next) {

	print("<div=\"nav\">\n");
	if ($prev) {
		print("[ <a href=\"?" . tigencode($dir . $prev) . "\">previous image</a> ] ");
	} else {
		print("[ previous image ] ");
	}
	print(" [ <a href=\"" . tigencode($dir) . "\">back to thumbnails</a> ] ");
	if ($next) {
		print(" [ <a href=\"?" . tigencode($dir . $next) . "\">next image</a> ]<br />\n");
	} else {
		print(" [ next image ]<br />\n");
	}
	print("</div>\n");

}

function tigencode($string) {

	$string = str_replace("å", "%e5", $string);
	$string = str_replace("ä", "%e4", $string);
	$string = str_replace("ö", "%f6", $string);
	$string = str_replace("Å", "%c5", $string);
	$string = str_replace("Ä", "%c4", $string);
	$string = str_replace("Ö", "%d6", $string);
	$string = str_replace("?", "%3f", $string);

	return($string);
}
?>
