#!/usr/local/bin/perl
# show.cgi
# Output some file for the browser

require './file-lib.pl';
&ReadParse();
use POSIX;
$p = $ENV{'PATH_INFO'};
if ($in{'type'}) {
	# Use the supplied content type
	$type = $in{'type'};
	}
else {
	# Try to guess type from filename
	if ($p =~ /\.([^\.\/]+)$/) {
		$ext = lc($1);
		&get_miniserv_config(\%miniserv);
		open(MIME, $miniserv{'mimetypes'});
		while(<MIME>) {
			s/#.*//g;
			if (/(\S+)\s+(.*)/) {
				foreach $e (split(/\s+/, $2)) {
					if ($ext eq $e) {
						$type = $1;
						last;
						}
					}
				}
			}
		close(MIME);
		}
	if (!$type) {
		# No idea .. use the 'file' command
		if (`file "$p"` =~ /text|script/) {
			$type = "text/plain";
			}
		else {
			$type = "application/unknown";
			}
		}
	}

# Dump the file
&switch_acl_uid();
if (!&can_access($p)) {
	print "Content-type: text/plain\n\n";
	$err = &text('view_eaccess', $p)."\n";
	print "Content-length: ",length($err),"\n";
	print $err;
	}
elsif (!open(FILE, $p)) {
	print "Content-type: text/plain\n\n";
	$err = &text('view_eopen', $p, $!)."\n";
	print "Content-length: ",length($err),"\n";
	print $err;
	}
else {
	@st = stat($p);
	print "Content-length: $st[7]\n";
	print "Content-type: $type\n\n";
	if ($type =~ /^text\/html/i && !$in{'edit'}) {
		while(read(FILE, $buf, 1024)) {
			$data .= $buf;
			}
		print &filter_javascript($data);
		}
	else {
		while(read(FILE, $buf, 1024)) {
			print $buf;
			}
		}
	close(FILE);
	}

