#!/usr/bin/perl
#
# Part of the Escher Database
#
# Searches the database for entries that match the passed data, and 
# returns a sorted list of them, on a template.
#
# Parameters:
#	field=value	Any number of these can be passed, 
#			only items in the database that match
#			all fields (case insensitive) will be
#			displayed.
#	keyword=value	Does a keyword search of the whole database. 
#			this and field=value are mutually exclusive.
#	icons=num	Max number of icons to display. If there are
#			more matches, icons are turned off. Default=40
#                       Icons are only displayed to trusted hosts, anyway.
#	sort=-1,1,0	-1=reverse sort, 1=normal sort, 0=unsorted (default)
#	sortkey=field	Field in the database to sort by. Default is 
#			to sort by the rating field.
#	format=value	Selects a format to display matches in.
#			formats are defined below. Optional.
#	template=file	Template to use. Must be in same directory as
#			this script, and can contain a ~list~ tag that
#			is expanded to the formatted list of matches, and a
#			~num~ tag that is replaced with the number of 
#			matches. Also, any of the parameters above
#			can be made into tags and will show up on the 
#			template. (Default template is ./default.template.
#	quickgroup=group This will turn on sorting, look up all pictures in
#			the group, and display them on group.template.
#			(spaces changed to _'s)
#			A handy fast way to look up a group.

# Set this to the location of the files that are required below
BEGIN { push(@INC,'../include/') }

# Find the image or html file for a picture in the passed subdirectory,
# and return the extention of the file. Return undef if it isn't found.
sub FindPicture { my ($dir,$id)=@_;
        if (-e "$dir/$id.gif") { return '.gif' }
        elsif (-e "$dir/$id.jpg") { return '.jpg' }
        elsif (-e "$dir/$id.jpeg") { return '.jpeg' }
        elsif (-e "./$id.html") { return '.html' }
}

# Initialization.
use Db;
require 'cgi-lib.pl';
require 'mce.conf'; # our config file.

print &PrintHeader;
&ReadParse;

Db::load($dbloc);

# Copy the %in array to a new array, for backup (used in filling out the 
# template.)
foreach $key (keys(%in)) {
	$in_full{$key}=$in{$key};
}
# Parse the fields and delete them from %in.
$keyword=delete $in{keyword}	if $in{keyword} ne undef;
$icons=40;
$icons=delete $in{icons}	if $in{icons} ne undef;
$sort=0;
$sort=delete $in{sort}		if $in{sort} ne undef;
$sortkey='rating';
$sortkey=delete $in{sortkey}	if $in{sortkey} ne undef;
$format='default';
$format=delete $in{format}	if $in{format} ne undef;
$template='default';
$template=delete $in{template}	if $in{template} ne undef;
if ($in{quickgroup}) {
	$template=$in{quickgroup};
	$template=~tr/[ |\]+/_/;
	$in{group}=$in{quickgroup};
	$sort=1;
	delete $in{quickgroup}
}

# Search the db.
if ($keyword) { # full text search by keyword
	@matches=Db::keysearch($keyword);
}
else { # field-based search.
	@matches=Db::search(%in);
}

if (($sort ne '0') && $sortkey) { # Sort the db.
	@matches= sort {	$sort * 
				($Db::db{$a}{$sortkey} <=>
				 $Db::db{$b}{$sortkey});
			}
			@matches
}

# Generate the text that fills in the ~list~ tag of the template.
$format_string=$format_array{$format};
$list=$format_headers{$format};
if ($#matches > $icons) { # let them turn icons on easily.
	# re-encode query string.
	$collect='';
	foreach $key (keys(%in_full)) {
		if ($key ne 'icons') {
			$_=$in_full{$key};
			tr/ /+/;
			s/[^+A-Za-z0-9:]/sprintf("%%%02x",unpack("C",$&))/eg;
			$collect.="$key=$_&";
		}
	}
	$list.="<p>(You may prefer to view this page with icons <a href=\"mcesearch.cgi?$collect\icons=100000\">turned on</a>.)</p>";
}
foreach $match (@matches) {
	$_=$format_string;

	if (($#matches <= $icons) && (lc($Db::db{$match}{medium}) ne "ascii art")) {
		s/~icon~/<IMG SRC="$icon_dir$match.icon.gif" ALT="">/ig;
	}

        s/~id~/$match/ig;
        s/~url~/$show?$match/ig;

	foreach $field (@Db::db_fields) {
		s/~$field~/$Db::db{$match}{$field}/ig;
	}

	$list.="$_\n";
}
$list.=$format_footers{$format};

# Fill out the template and return to user.
$template=~s/\.\.//g; # crack prevention.
$template=~s/\///g; # crack prevention.
$template="$template_dir/$template.template";
$num=$#matches+1;
$num='no' if $num eq 0;
$num="There are $num matches." if $num ne 1;
$num="There is one match." if $num eq 1;
open (T,"<$template") || exit print "Error: unable to open template ($template)!\n";
while (<T>) {
	s/~list~/$list/ig;
	s/~num~/$num/ig;
	s/~(.*?)~/$in_full{$1}/ig;
	print $_;
}
close T;
&PrintFooter;
