#!/usr/local/bin/perl
#
# Gallery software
#
# $Id: script.cgi,v 1.6 1997/08/15 11:26:07 jna Exp jna $
#
# $Log: script.cgi,v $
# Revision 1.6  1997/08/15 11:26:07  jna
# Thumbnails are now .JPG , not .GIF. .GIFs were nearly the same
# size as the original image (pointless!)
#
# Revision 1.5  1997/08/09 09:46:15  jna
# BugFix: MAXPAGE was hardcoded to 10, and was affecting searchlib
#
# Revision 1.4  1997/07/15 07:53:46  jna
# Now has full regexp search facility, and error messages in the
# proper places. Minor fixes to table display routines and bounds
# checking added in
#
# Revision 1.3  1997/07/15 02:43:28  jna
# Pre-Search facility release (saftey copy)
#
# Revision 1.2  1997/07/13 07:32:46  jna
# Another revsion
#
# Revision 1.1  1997/07/02 23:32:28  jna
# Initial revision
#
#
#
# John Adams <jna@retina.net>
require "gallery.cfg";
require "search-lib.pl";

# activate CGI.pm
use CGI;
$query = new CGI;

print $query->header;

&get_masterlist;

# If the script comes in with a url in the form:
# /cgi-bin/script.cgi/page1
# be smart and use that to determine staring page (overidden by page=) though. 
if ($ENV{'PATH_INFO'} =~ /^\/page/ )
{
    $PG=$' + 0;

    # validate page.
    if ($PG > $MAXPAGE) { $PG = $MAXPAGE };
    if ($PG < 1) { $PG = 1 };  

    # also set the form vars if we're starting fresh
    if (! $query->param)
    {
 	$query->param("page",$PG);
    }
}

if ($query->param)
{
    # decode and nuke search variables, if any
    $searchtext = $query->param("stext");
    $query->delete("stext");
    
    # minor options decoding here (has to be done before header display
    # so we know which header to show)
    
    @OPTLIST = $query->param("options");
    
    #$opt_s = $opt_u = $opt_d = $opt_t = 1;
    $opt_u = $opt_d = $opt_t = 1;
    
    for ($i=0; $i < @OPTLIST;$i++)
    {
	if ($OPTLIST[$i] eq "S") { $opt_s=1; }
	if ($OPTLIST[$i] eq "U") { $opt_u=1; }
	if ($OPTLIST[$i] eq "D") { $opt_d=1; }
	if ($OPTLIST[$i] eq "W") { $opt_w=1; $target="TARGET=\"AG_PIXWINDOW\""}
	if ($OPTLIST[$i] eq "T") { $opt_t=1; $opt_msg="<BR>(Click on a thumbnail to see the full image)"; }
    }

	# Sometimes users are permanently stupid...
	if (($opt_d == 0) && ($opt_t == 0))
	{
	    # I'm not using this error right now, as I am silently 
	    # fixing the user's mistake and moving forward.
	    $ermsg = "<BLOCKQUOTE> Neither thumbnails or descriptions were selected for display. <BR>I'm ignoring your options.</BLOCKQUOTE>";

	    # turn on the descriptions so we get SOME output.
	    $query->param("options","D");
	    $query->param("options","S");
	    $query->param("options","U");
	    $query->param("options","T");
	}

	# Future: attempt to get Page ID from PATH_INFO, but this will require
        #         that we use absolute links for all HREFs and IMGs

	# get the page ID to display or default to page one if we're lost.
	$PG=$query->param("page");
	$PG = $PG + 0;
	if ($PG eq "") { $PG=1 };
}

# validate page.
if ($PG > $MAXPAGE) { $PG = $MAXPAGE };
if ($PG < 1) { $PG = 1 };

# show the hedaer
&header;

# check if there is work to do
if ($query->param)
{
	# do it!
	if ($opt_u) {
	    &generate_table;
	}
	else
	{
	    &generate_list;
	}
}
else
{
    # No idea what to do here, just give them the 1st list
    &generate_list;
}

&footer;

sub generate_list
{


    if (! -f "$ROOT/$PG/thelist")
    {
	print "Sorry, no images on this page (yet!).<BR>Come back in a day or two.<P>\n";
	return;
    }

    if ($searchtext ne "")
    {
	# a search, let the engine return the results for us

	@IMAGES =  &search($searchtext);

	if ($matches == 0)
	{
	    print "Sorry, There are no matches to your query.<BR>Try fewer keywords or using a simpler pattern.<P>\n";
	    return;
	}
	
	$count = $#IMAGES + 1;
    } 
    else
    {

	# not a search, construct the list from a file.
	$count = 0;
	open (thelist,"<$ROOT/$PG/thelist");
	while(<thelist>)
	{
	    $IMAGES[$count++] = $_;
	}
	close (thelist);
    }

    print "<UL>\n";

    for ($num = 0; $num < $count; $num++)
    {
	$_ = $IMAGES[$num];

	# prep names and alter extensions
	chop;

	($file,$caption) = split(/\:/);

	# get file size and download time
	($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat("$ROOT/$PG/$file");
	$ksize=sprintf("%.1d",$size/1024);

	# this divisor is for 28.8 BPS
	$sec=sprintf("%.2d",($size/2400));

	# build the caption
	if ($searchtext ne "")
	{
	    $caption = "<A HREF=\"$DISPURL/$file\" $target> $caption </A>";
	}
	else
	{
	    $caption = "<A HREF=\"$DISPURL/$PG/$file\" $target> $caption </A>";
	}


	if ($opt_s)
	{
	    $caption = "$caption <FONT SIZE=\"-1\">($ksize k) $sec s @ 28.8</FONT>";
	}
    
	# display a thumbnail (if available), otherwise show a failure
	# image
	$thumb = $file;
	$thumb =~ s/\.jpg/-sm\.jpg/i;

	# if we see a /, this is SEARCH output, and has page id attached. 
	# otherwise we need to provide that.
	if (! ($thumb =~ s/\//\/Thumbnails\//))
	{
	    $thumb = "$PG/Thumbnails/$thumb";
	}
	
	if (! -f "$ROOT/$thumb")
	{
	    $thumb="$ROOTURL/navelements/na.gif";
	}

	print "\n<LI> $caption ";
	if ($opt_t)
	{
	  if ($searchtext ne "")
	  {
	      print qq{<BR><A HREF="$DISPURL/$file" $target><IMG SRC="$thumb" WIDTH=100 HEIGHT=100 ALT="$thumbf" ALIGN=TOP $target></A>\n};
	      #print qq{<BR><A HREF="$DISPURL/$file" $target><IMG SRC="$thumb" ALT="$thumbf" ALIGN=TOP $target></A>\n};
	  }
	  else
	  {
	      print qq{<BR><A HREF="$DISPURL/$PG/$file" $target><IMG SRC="$thumb" WIDTH=100 HEIGHT=100 ALT="$thumbf" ALIGN=TOP $target></A>\n};
	      #print qq{<BR><A HREF="$DISPURL/$PG/$file" $target><IMG SRC="$thumb" ALT="$thumbf" ALIGN=TOP $target></A>\n};
	  }
	}
    }

    print "\n</UL>\n";
	
}

sub generate_table
{

# build a grid of images from a page list file (thelist) in the approiate page
# directory 

print "<TABLE>\n";

$count=0;

if (! -f "$ROOT/$PG/thelist")
{
    print "Sorry, no images on this page (yet!).<BR>Come back in a day or two.<P>\n";
    return;
}

if ($searchtext ne "")
{
    # a search, let the engine return the results for us

    @IMAGES =  &search($searchtext);

    if ($matches == 0)
    {
	print "Sorry, There are no matches to your query.<BR>Try fewer keywords or using a simpler pattern.<P>\n";
	return;
    }

    $icount = $#IMAGES + 1;
} 
else
{
    
    # not a search, construct the list from a file.
    $icount = 0;
    open (thelist,"<$ROOT/$PG/thelist");
    while(<thelist>)
    {
	$IMAGES[$icount++] = $_;
    }
    close (thelist);
}

for ($num = 0; $num < $icount; $num++)
{
    $_ = $IMAGES[$num];

    # prep names and alter extensions
    chop;

    ($file,$caption) = split(/\:/);

    # get file size and download time
    $f = $file;
    if (! ($f =~ /\// ))
    {
	$f = "$PG/$f";
    }

    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat("$ROOT/$f");
    $ksize=sprintf("%.1d",$size/1024);
    $sec=sprintf("%.2d",($size/2400));

    # build the caption
    if (!$opt_d)
    {
	$caption="";
    }

    if ($opt_s)
	{
	    $captionlist[$count] = "$caption<BR><FONT SIZE=\"-1\">($ksize k)<BR>$sec s @ 28.8</FONT>";
	}
    else
    {
	$captionlist[$count] = "$caption<BR>";
    }
    
    # display a thumbnail (if available), otherwise show a failure
    # image
    $thumb = $file;
    $thumb =~ s/\.jpg/-sm\.jpg/i;
    
    # if we see a /, this is SEARCH output, and has page id attached. 
    # otherwise we need to provide that.
    if (! ($thumb =~ s/\//\/Thumbnails\//))
    {
	$thumb = "$PG/Thumbnails/$thumb";
    }
    
    if (! -f "$ROOT/$thumb")
    {
	$thumb="$ROOTURL/navelements/na.gif";
    }
    
    if ($count > 4)
    {
	print "</TR><TR>\n";
	$count =0;
	
	# dump captions..
	for ($i=0;$i<5;$i++)
	{
    print <<ZZEOFZZ;
    <!-- Captions -->
	<TD VALIGN=TOP>
		    <SMALL>
	$captionlist[$i]
	</SMALL>
	</TD>
ZZEOFZZ
}
  print "</TR><TR>\n";
  # correct our mis-assumption
  if ($opt_s) 
  {
      $captionlist[0] = "$caption<BR><FONT SIZE=\"-1\">($ksize k)<BR>$sec s @ 28.8</FONT>";
  }
  else
  {
      $captionlist[0] = "$caption";
  }


}
# dump an entry for this image
    print "	<!-- Images -->\n<TD VALIGN=TOP WIDTH=25%>\n";

	if ($opt_t)
	{
	  if ($searchtext ne "")
	  {
	      print qq{<BR><A HREF="$DISPURL/$file" $target><IMG SRC="$thumb" WIDTH=100 HEIGHT=100 ALT="$thumbf" ALIGN=TOP $target></A>\n};
	      #print qq{<BR><A HREF="$DISPURL/$file" $target><IMG SRC="$thumb" ALT="$thumbf" ALIGN=TOP $target></A>\n};
	  }
	  else
	  {
	      print qq{<BR><A HREF="$DISPURL/$PG/$file" $target><IMG SRC="$thumb" WIDTH=100 HEIGHT=100 ALT="$thumbf" ALIGN=TOP $target></A>\n};
	      #print qq{<BR><A HREF="$DISPURL/$PG/$file" $target><IMG SRC="$thumb" ALT="$thumbf" ALIGN=TOP $target></A>\n};
	  }
      }

    print "</TD>\n";

    $count++;
}


# dump remaining captions

print "</TR><TR>\n";
      for ($i=0;$i<$count;$i++)
      {
print <<ZZEOFZZ;
	<!-- Captions -->
	<TD VALIGN=TOP>
	<SMALL>
	$captionlist[$i]
	</SMALL>
	</TD>
ZZEOFZZ
}

print "</TR>\n";

# close the html
print "</TABLE>\n";

close(thelist);

}

sub header
{
    local $p;

    $p = "page $PG, " . $secid{$PG};
    if ($searchtext ne "")
    {
	$p="Search Results";
    }
    
print <<ZZEOFZZ

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML>
<HEAD>

<TITLE>Nathan's Photo Gallery - $p</TITLE>

</HEAD>

<BODY BGCOLOR="#000000" TEXT=#FFFFFF LINK=#00DD00 ALINK=#FFFFFF VLINK=#FFFFFF> 

<!--IMG SRC="navelements/2.0banner.jpg" ALT="Nathan's gallery [banner]" ALIGN=TOP WIDTH="500" HEIGHT="81" -->
<h1>Nathan's Omnipresent Pictures</h1>
<HR WIDTH=100% ALIGN=LEFT>
<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=2  NOSHADE)
<TR>
	<TD BGCOLOR="660000">
	<I>Options</I>
	</TD>
</TR>

<TR>
	<TD>
	<FORM METHOD=GET ACTION="$ROOTURL/script.cgi">
	<TABLE>

ZZEOFZZ
;
print "<TR><TD ALIGN=RIGHT>Regexp Search:</TD><TD>" . $query->textfield(-name=>'stext',                                  -length=>10) . $query->submit("Start Search") . "</TD></TR>";


print <<ZZEOFZZ


		<TR>
	        <TD ALIGN=RIGHT VALIGN=CENTER>
		Page: 
		</TD>
		<TD VALIGN=CENTER>
ZZEOFZZ
;

print $query->popup_menu(-name=>'page',
                         -default=>'1',
                         -values=>\@secval,
                         -labels=>\%secid);

print $query->submit('Show');

print <<ZZEOFZZ
		</TD>
		</TR>
		<TR>
		<TD ALIGN=RIGHT VALIGN=TOP>
			Show:
		</TD>
		<TD>
ZZEOFZZ
;

%labels = ('D'=>'Descriptions',
           'T'=>'Thumbnails',
           'S'=>'File Sizes',
           'U'=>'with Tables',
           'W'=>'Open in Alt. Window');

print $query->checkbox_group(-name=>'options',
                      -values=>['D','T','S','U','W'],
                      -defaults=>['D','T','S','U'],
                      -labels=>\%labels);

print <<ZZEOFZZ

                <BR>
                <FONT SIZE="-2">You must click SHOW after changing any of these options for them to take effect.</FONT>



		</TD>
		</TR>

	</TABLE>
	</TD>
	<TR>
		<TD>
		<HR WIDTH=500 ALIGN=LEFT>
		</TD>
	</TR>
        <TR>
	<TD BGCOLOR="660000">
ZZEOFZZ
;

# Show a description file if we're not doing a search.
if ($searchtext ne "")
{
	print "	<I>Search: Returning matches for <B> $searchtext </B> in the image database $opt_msg </I><BR></TD></TR><TR><TD>\n";
}
else
{
    if (-f "$ROOT/$PG/descr")
    {
	# cat a description file if one is available.
	print "	<I>Images Available on Page $PG, \"$secid{$PG}\" $opt_msg </I><BR></TD></TR><TR><TD>\n";
	open (HEAD,"<$ROOT/$PG/descr");
	while(<HEAD>) { print $_; };
	close (HEAD);
    }
}

print "</TD>\n\n</TR>\n</TABLE>\n</FORM>\n";

}


sub footer
{

print <<ZZEOFZZ;

<TABLE>
<TR>
<TD WIDTH=500>
 <FONT SIZE="-2"> All images Copyright &copy;1996-2002 Nathan J. Mehl. 
 Permission is granted to people appearing in these pictures to take 
 copies. Everyone else, please ask before you steal them!
Images archived and presented by <A HREF=\"http://www.retina.net/~jna/autogallery\">AutoGallery 2.0</a>
 </FONT>
</TD>
</TR>
</TABLE>

<HR WIDTH=500 ALIGN=LEFT>

</BODY>
</HTML>

ZZEOFZZ

}

sub get_masterlist
{
    local $section,$title,$i,MLIST;

    # get a listing of all of the directories we have to serve for
    open(MLIST,"<masterlist") || die "No Master Directory File (masterlist)";

    $i = 0;
    $MAXPAGE=0;
    while(<MLIST>)
    {
	if (($_  ne "") && (! /^\#/))
	{
	    ($section,$title) = split(/:/);
	    $secid{$section} = $title;
	    if ($section > $MAXPAGE) { $MAXPAGE=$section; }
	    $secval[$i++] = $section;
	}
    }
    close(MLIST);

}




