#!/s/std/bin/perl
# $Id: script.cgi,v 1.12 1998/09/29 10:08:25 jna Exp $#
#
# AutoGallery, The Automated Web Image Catalog System
#
# Written by John Adams, 10/97 
# Copyright 1998, Retina Communications Group
# Permission granted to use this code in any fashion provided
# that this notice is retained and any alterations are
# labeled as such. It is requested, but not required, that
# you share extensions/changes to this package with us so that we
# can incorporate them into new versions.
#
# $Log: script.cgi,v $
# Revision 1.12  1998/09/29 10:08:25  jna
# see the CHANGES file. final 2.2 release
#
# Revision 1.11  1998/09/28 22:28:33  jna
# Large number of bugfixes, ALT tag cleanup
#
# Revision 1.10  1998/04/08 06:46:27  jna
# Fix to make gallery options persistant between displays as
# well as a micro caption editor
#
# Revision 1.9  1998/04/08 05:09:46  jna
# Minor bugfixes.
#
# Revision 1.8  1997/10/03 07:33:11  jna
# Frames support, limits on # of items returned in a search (defaults to 50)
# added.
#
# Revision 1.7  1997/08/18 22:43:55  jna
# Final check-in before starting frames work
#
# 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";
require "section-lib.pl";
require "layout.pl";
require "sizer.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. 
    $searchtext = $query->param("stext");
    $query->delete("stext");

    $querystring = $ENV{'QUERY_STRING'};
    # minor options decoding here (has to be done before header display
    # so we know which header to show)
    
    @OPTLIST = $query->param("options");
    $ope_d = $opt_e = $opt_f = $opt_s = $opt_t = $opt_u = $opt_v = $opt_w = 0;

    $ftarget="O";

    for ($i=0; $i < @OPTLIST;$i++)
    {
	if ($OPTLIST[$i] eq "D") { $opt_d=1; }
	if ($OPTLIST[$i] eq "E") { $opt_e=1; } # edit option, it's hidden.
	if ($OPTLIST[$i] eq "F") { $opt_f=1; $ft="TARGET=F_INDEX"; $ftarget = $query->param("frame_sec"); }
	if ($OPTLIST[$i] eq "S") { $opt_s=1; }
	if ($OPTLIST[$i] eq "T") { $opt_t=1; $opt_msg="<BR>(Click on a thumbnail to see the full image)"; }
	if ($OPTLIST[$i] eq "U") { $opt_u=1; }
	if ($OPTLIST[$i] eq "V") { $opt_v=1; }
	if ($OPTLIST[$i] eq "W") { $opt_w=1; $target="TARGET=\"AG_PIXWINDOW\""}
    }

    # option V is special, it has nothing to do with the display of images, it's for showing
    # a category display with thumbnails, a completely new behaviour. 

    if ($opt_v)
    {
	# punt all the options and restart 
	$opt_e = $opt_f = $opt_s = $opt_w = 0;
	$opt_d = $opt_t = $opt_u = $opt_v = 1;
        @x[0] = "T"; @x[1] = "U"; @x[2] = "D";
	$query->param("options",@x);

	$opt_msg="<BR>(Click on a thumbnail to select a section.)";
    }

    # 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");
    }
    
    # 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;

	if ($count > 50)
	{
	    print "There are $#IMAGES matches to your query.<BR> Only returning the first 50. Narrow your search to see more.<P>\n";
	    $count = 50;
	}
	else
	{
	    $e="matches";
	    if ($count > 1) { $ss="s"; $e="match"; }
	    print "$count picture$ss $e your query:<BR>";
	}
    } 
    else
    {

	# not a search, construct the list from a file.
	$count = 0;
	open (thelist,"<$ROOT/$PG/thelist");
	while(<thelist>)
	{
	    chop;

	    if (! /^\#/)
		{
		    $IMAGES[$count++] = $_;
		}
	}
	close (thelist);
    }

    print "<UL>\n";

    for ($num = 0; $num < $count; $num++)
    {
	# prep names and alter extensions
	$_ = $IMAGES[$num];

	($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);
	$rdate=localtime($ctime);

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

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


	if ($opt_s)
	{
	    $caption = "$caption <FONT SIZE=\"-1\">($ksize k) $sec s @ 28.8 on $rdate</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";
	    ($x,$y) = &imgsize("$ROOT/navelements/na.gif");
	} else {
	    $thumb="$ROOTURL/$thumb";
	    ($x,$y) = &imgsize("$ROOT/$thumb");
	}

	print "\n<LI> $caption ";
	if ($opt_t)
	{
	  if ($searchtext ne "")
	  {
	      print qq{<BR><A HREF="$DISPURL/$file?$querystring" $target><IMG SRC="$thumb" WIDTH=$x HEIGHT=$y ALT="[Thumbnail]" ALIGN=BOTTOM $target></A>\n};
	  }
	  else
	  {
	      print qq{<BR><A HREF="$DISPURL/$PG/$file?$querystring" $target><IMG SRC="$thumb" WIDTH=$x HEIGHT=$y ALT="[Thumbnail]" ALIGN=BOTTOM $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;

# searches and section overview use approx. the same code. 
if (($searchtext ne "") || ($opt_v))
{
    if ($opt_v)
    {
        @IMAGES =  &section_view();
    }
    else
    {
	# 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.
    if (! -f "$ROOT/$PG/thelist")
    {
	print "Sorry, no images on this page (yet!).<BR>Come back in a day or two.<P>\n";
	return;
    }

    $icount = 0;
    open (thelist,"<$ROOT/$PG/thelist");
    while(<thelist>)
    {
	    if (! /^\#/)
		{
		    $IMAGES[$icount++] = $_;
		}
    }
    close (thelist);
}

if ($opt_e)
{
    print "<FORM METHOD=POST ACTION=showcaps.cgi>\n";
}

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

    # prep names and alter extensions
    chop;

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

    # is this an edit? make the form header
    if ($opt_e)
    {
	$caption="<INPUT TYPE=TEXT SIZE=20 NAME=\"cap-$file\" VALUE=\"$caption\">";
    }

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

    # only stat if we have to.
    if ($opt_s)
    {
	($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));
	$rdate=localtime($ctime);
    }

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

    if ($opt_s)
    {
      $captionlist[$count] = "$caption<BR><FONT SIZE=\"-1\">($ksize k)<BR>$sec s @ 28.8<br>$rdate</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";
	($x,$y) = &imgsize("$ROOT/navelements/na.gif");
    } else {
	($x,$y) = &imgsize("$ROOT/$thumb");
	$thumb="$ROOTURL/$thumb";
    }

    if ($count > 4)
    {
	print "</TR><TR>\n";
	$count =0;
	
	# dump captions..
	for ($i=0;$i<5;$i++)
	{
    print <<ZZEOFZZ;
    <!-- Captions -->
	<TD VALIGN=TOP WIDTH=25%>
		    <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<br>$rdate</FONT>";
  }
  else
  {
      $captionlist[0] = "$caption";
  }


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

	if ($opt_t)
	{
          # messy if sex. 
	  if ($searchtext ne "")
	  {
	      print qq{<BR><A HREF="$DISPURL/$file?$querystring" $target><IMG SRC="$thumb" WIDTH=$x HEIGHT=$y ALT="[Thumbnail]" ALIGN=BOTTOM $target></A>\n};
	  }
          elsif ($opt_v)
          {
            ($pg,$chaff) = split(/\//,$file);
            print qq{<BR><A HREF="$SCRURL?page=$pg&options=D&options=T&options=U" $target><IMG SRC="$thumb" WIDTH=$x HEIGHT=$y ALT="[Thumbnail]" ALIGN=BOTTOM $target></A>\n};
          }
	  else
	  {
	      print qq{<BR><A HREF="$DISPURL/$PG/$file?$querystring" $target><IMG SRC="$thumb" WIDTH=$x HEIGHT=$y ALT="[Thumbnail]" ALIGN=BOTTOM $target></A>\n};
	  }
        }
	else
	{
	  # link to the filename but no image display
	  if ($searchtext ne "")
	  {
	      print qq{<BR><A HREF="$DISPURL/$file?$querystring" $target> $thumbf</A>\n};
	  }
	  else
	  {
	      print qq{<BR><A HREF="$DISPURL/$PG/$file?$querystring" $target>Image</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 WIDTH=25%>
	<SMALL>
	$captionlist[$i]
	</SMALL>
	</TD>
ZZEOFZZ

}

print "</TR>\n";

# close the html
if ($opt_e)
{
    print "<INPUT TYPE=SUBMIT NAME=\"Display Caption File\" VALUE=\"Display Caption File\">\n";
    print "</FORM>\n";
}


print "</TABLE>\n";

close(thelist);

}

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;

    # note that the way this works you can have the section entries in any order.
    while(<MLIST>)
    {
	if (($_  ne "") && (! /^\#/))
	{
	    ($section,$defimage,$title) = split(/:/);
	    $secid{$section} = $title;
	    $secimg{$section} = $defimage;
	    if ($section > $MAXPAGE) { $MAXPAGE=$section; }
	    $secval[$i++] = $section;
	}
    }
    close(MLIST);

}




