#!/usr/bin/perl
#This was found on some website and doctored by Flash

$filepath = "/www/htdocs";
$indexFile = "/www/cgi-bin/searchindex.txt";

use CGI;
$query = new CGI;

chdir($filepath);

$target = $query->param('target');
if ($target eq "") {
	&header;
	&form;
	&footer;
	exit 0;
}
$rule = $query->param('rule');

# Simple HTML flusher
$target =~ s/\<.*?\>//g;
# Case insensitive
$target =~ tr/A-Z/a-z/;
# If it's not a letter, it's whitespace
$target =~ s/[^a-z]/ /g;

@words = split(/ /, $target);
if (open(IN, $indexFile)) {
	while ($line = <IN>) {
		my($wordCount, $score);
		if ($line =~ /^(\S+) /) {
			$filename = $1;
		} else {
			next;
		}
		for $w (@words) {
			if ($line =~ /(\d+):$w/)
			{ 
				$score += $1;
				$wordCount ++;
			}
		}
		if ($rule eq "and") {
			if ($wordCount == int(@words)) {
				push @files, "$score:$filename";
			}	
		} elsif ($wordCount > 0) {
			push @files, "$score:$filename";
		}
	}
}

&header;
if (!int(@files)) {
	print "Sorry, no pages were found.\n";
} else {
	print "The following pages were found:\n";
}
print "<ul>\n";

@files = sort {$b <=> $a} @files;

for $n (@files) {
	my($score, $file) = split(/:/, $n);
	# skip hidden web stats pages
	if ($file =~ /\/analog/) {
		next;
	}
	$title = "";
	$data = "";
	if (open(IN, "$filepath$file")) {
		while ($line = <IN>) {
			$data .= $line;
			if ($data =~ /<title>\s*(.*)\s*\<\/title>/i) {
				$title = $1;
				last;
			}
		} 
		close(IN);
	}

        # stop the index.shtml bit being returned in the urls
        if($file=~/(.+)\/index\..*?html/)
        {
                $file=$1;  
        }

	if ($title eq "") {
		$title = "$file";
	}
	print "<li>$score matches: <a href=\"$file\">$title<\/a>\n";
}
print "</ul><BR>\n";
&form;
&footer;

sub header
{
	print "Content-type: text/html\n\n";
	# read in my template here
	open TEMPLATE, "/www/htdocs/includes/cgi-header.shtml" or die;
	while (my $line = <TEMPLATE>) 	
	{
		print $line;
	}
	close TEMPLATE;
	print "<BR><CENTER><H6>Gorge search results\n";
	print "</H6><BR></CENTER></CENTER><BR>";
}

sub footer
{
	#print the end of my template stuff here
	open TEMPLATE, "/www/htdocs/includes/gorge-footer.shtml" or die;
	while (my $line = <TEMPLATE>) 	
	{
 		print $line;
	}
	close TEMPLATE;
	#print"</TD> </TR> </TABLE> </BODY> </HTML>";
}

sub form
{
	print <<EOM
<form action="/cgi-bin/search.pl" method="GET">
Search for pages containing
<select name="rule">
<option value="and">all
<option value="any">any
</select>
of these words: 
<input name="target">
<input type="submit" value="Go!">
</form>
<p>
EOM
;
}
