#!/usr/bin/perl

##############################################################################
# Picture.cgi                     Version 2.1                                #
# Copyright 2002  Glenn Dempsey   webmaster@clovenfoot.com                   #
# Created 07/25/01                Last Modified 06/03/02                     #
# Cloven Foot:                    http://clovenfoot.com                      #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2002  Glenn Dempsey   All Rights Reserved.                       #
#                                                                            #
# Picture.cgi may be used and modified free of charge by anyone so long as   #
# this copyright notice and the comments above remain intact.  By using this #
# code you agree to indemnify Glenn Dempsey from any liability that          #
# might arise from its use.                                                  #
#                                                                            #
# Selling the code for this program without prior written consent is         #
# expressly forbidden.  In other words, please ask first before you try and  #
# make money off of my program.                                              #
#                                                                            #
# Obtain permission before redistributing this software over the Internet or #
# in any other medium.	In all cases copyright and header must remain intact #
##############################################################################

if ( (-e "config.cgi") && (-r "config.cgi") && (-s "config.cgi") ){ 
	require "config.cgi";
}
else{
	print "Content-type: text/html\n\n";
	print "ERROR! The config.cgi file was either not found, not readable, or a file size of zero.";
	exit;
}

#Variables
my $number_of_images = 0; #value should always start off as zero
my $nop;
my $pagenum;
my $forloopvar = 0; 
my $forloopimages;
my @image_array;
my $nop_l;
my $last_images;
my $prev_images;
my $prev_pagenum;
#End Variables

#Get rid of "#" from color codes.
$bgcolor =~ s/^#//g;
$pic_border =~ s/^#//g;
$text =~ s/^#//g;
$link_color =~ s/^#//g;
$darkened_links =~ s/^#//g;

&parse_form;

#Time to check if we are using multiple galleries or not
if ($multiple_galleries eq "false"){
	$picture_folder = $nameofpicfolder;
}elsif ($multiple_galleries eq "true"){
	$picture_folder = $query_picfolder;
}else {
	$picture_folder = $nameofpicfolder;
}
#Done checking if we are using multiple galleries or not

#Add the picture folder name to the end of $pathtogallery
$pathtogallery = $pathtogallery . $picture_folder . "\/";

&read_dir;

#Get rid of trailing "/" from $directory, and create a variable for the location of popup.html
my $pic_directory = $directory . "\/" . $picture_folder . "\/";

if ($pages_displayed == (int $pages_displayed / 2) * 2){
	print "Content-type: text/html\n\n";
	print "You must use an odd number for the \$page_displayed variable.  Try again by modifying the config.cgi file.\n";
	exit;
}

@image_array = reverse sort @unsortedfiles;
@image_array = grep /\d\-.*?\.($media)/gi, @image_array;

$number_of_images = @image_array; #Total number of images

$pagenum += 1;
$nop = $number_of_images/$images_per_page; #this tells the script how many pages are needed to display all of the pictures
					   #nop means number of pages

if ($nop =~ /\./){  #this if statement rounds any decimal number up
	@yonop = split(/\./, $nop);
	$nop = $yonop[0] + 1;
}

if (@image_array == ""){

	$pagenum = 0;

}

#Calculate the width of the thumbnail's table
	$thumbs_per_row = ($thumb_width * $thumbs_per_row) + (($thumb_border * 2) * $thumbs_per_row);
#End calculate

print "Content-type: text/html\n\n";

############------------------#############
#the GALLERYHEADER print segment can be modified to include a custom header.
#Tread carefully, though, don't mess with the Javascript unless you know what you are doing.
print <<GALLERYHEADER;
	<HTML>
	<HEAD>
	<TITLE>$title - Seite $pagenum</TITLE>
	
	<SCRIPT language="javascript">
	<!--
		var putItThere = null;
		var chasm = screen.availWidth;
		var mount = screen.availHeight; //chasm and mount help calculate the center of the screen
	
		function popupwindow (URL,popupWidth,popupHeight) {
			
			if (popupWidth > chasm) {
				popupWidth = chasm - 10;
			}
			if (popupHeight > mount) {
				popupHeight = mount - 40;
			}
			
			putItThere = window.open(URL,"popupWindow","width=" + popupWidth + ",height=" + popupHeight + ",toolbar=$popwin_toolbar,directories=$popwin_directories,location=$popwin_location,status=$popwin_status,menubar=$popwin_menubar,resizable=$popwin_resizable,scrollbars=$popwin_scrollbars,left=" + ((chasm - popupWidth - 10) * .5) + ",top=" + ((mount - popupHeight - 30) * .5) + ",screenX=" + ((chasm - popupWidth - 10) * .5) + ",screenY=" + ((mount - popupHeight - 30) * .5));
		}
	// -->
	</SCRIPT>
	
	</HEAD>
	<BODY background="http://www.vilstalweb.de/wuerdinger/fasching/hinterp.gif" bgcolor="$bgcolor" text="$text" link="$pic_border" vlink="$pic_border" alink="$pic_border">
	<center>
	<table align="center" border="0"><tr><td width="$thumbs_per_row">
GALLERYHEADER
############------------------#############

$forloopimages = $images_per_page - 1;

#The heart of the script
for ($image_array = $forloopvar; $image_array <= ($forloopimages + $forloopvar); $image_array++){

	(local $firstsplit1, local $firstsplit2) = split(/\.($media)/, $image_array[$image_array]);
	(local $secondsplit1, local $secondsplit2) = split(/\-/, $firstsplit1);
	$secondsplit2 =~ s/\_/ /g;
	last if ($image_array > ($number_of_images - 1));
	
	$theWidth = &getWidthHeight(WIDTH);
	
	#This URL escapes the title of the image so it will work in Netscape.
	$secondsplit2_escaped = $secondsplit2;
	$secondsplit2_escaped =~ s/ /%20/g;
	
	if ($close_button eq "yes"){
		$theHeight = &getWidthHeight(HEIGHT) + 20;  #Gets the height of the current image and adds 20 pixels to the size of the popup window
		$theHeight2 = $theHeight - 20; #For the image size of the current image in popup.html
	}else{
		$theHeight = &getWidthHeight(HEIGHT);
		$theHeight2 = $theHeight; #For the image size of the current image in popup.html		
	}
	print "<a href=\"$directory/$picture_folder/$image_array[$image_array]\" onClick=\"popupwindow(\&#34;$directory/popup.html?name=$image_array[$image_array]&title=$secondsplit2_escaped&picdirectory=$pic_directory&text=$text&linkcolor=$link_color&bgcolor=$bgcolor&width=$theWidth&height=$theHeight2&close=$close_button\&#34;,$theWidth,$theHeight); return false\"><img src=\"$directory/$picture_folder/$nameofthumbfolder/$image_array[$image_array]\" alt=\"$secondsplit2\" title=\"$secondsplit2\" border=\"$thumb_border\" width=\"$thumb_width\" height=\"$thumb_height\"></a>";
}
#End heart of the script

print "</td></tr><tr><td align=\"right\">";
print "<font size=2 face=verdana,helvetica color=$text>Seite $pagenum von $nop</font><br>";
print "<font size=2 face=verdana,helvetica color=$text>Anzahl Bilder gesamt: $number_of_images</font><br>";

$forloopvar += $images_per_page;
$nop_l = $nop - 1; #for the last button
$last_images = $nop_l * $images_per_page; #for the last button
$prev_images = $forloopvar - ($images_per_page * 2); #for the previous button
$prev_pagenum = $pagenum - 2; #for the previous button

if (($nop == 1) || ($nop == 0)) {
	print "<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>erste Seite</u></font><font size=2 face=verdana,helvetica color=\"$darkened_links\">&nbsp;&nbsp;|&nbsp;&nbsp;</font><font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>letze Seite</u></font><br>";
	print "&nbsp;<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>vorherige Seite</u></font><font size=2 face=verdana,helvetica color=\"$darkened_links\"> | </font>";
	print "<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>nächste Seite</u></font><br>";
}
elsif ($pagenum == 1) {
	print "<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>erste Seite</u></font><font size=2 face=verdana,helvetica color=\"$text\">&nbsp;&nbsp;|&nbsp;";
	&page_numbers;
	print "|&nbsp;&nbsp;</font><a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$nop_l&images=$last_images\"><font size=2 face=verdana,helvetica color=\"$link_color\">letzte Seite</font></a><br>";
	print "&nbsp;<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>vorherige Seite</u></font><font size=2 face=verdana,helvetica color=\"$text\"> | </font>";
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$pagenum&images=$forloopvar\"><font size=2 face=verdana,helvetica color=\"$link_color\">nächste Seite</font></a><br>";
}
elsif ($pagenum < $nop) {
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder\"><font size=2 face=verdana,helvetica color=\"$link_color\">erste Seite</font></a><font size=2 face=verdana,helvetica color=\"$text\">&nbsp;&nbsp;|&nbsp;";
	&page_numbers;
	print "|&nbsp;&nbsp;</font><a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$nop_l&images=$last_images\"><font size=2 face=verdana,helvetica color=\"$link_color\">letzte Seite</font></a><br>";
	print "&nbsp;<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$prev_pagenum&images=$prev_images\"><font size=2 face=verdana,helvetica color=\"$link_color\">vorherige Seite</a></font><font size=2 face=verdana,helvetica color=\"$text\"> | </font>";
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$pagenum&images=$forloopvar\"><font size=2 face=verdana,helvetica color=\"$link_color\">nächste Seite</font></a><br>";
}
elsif ($pagenum == $nop){
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder\"><font size=2 face=verdana,helvetica color=\"$link_color\">erste Seite</font></a><font size=2 face=verdana,helvetica color=\"$text\">&nbsp;&nbsp;|&nbsp;";
	&page_numbers;
	print "|&nbsp;&nbsp;</font><font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>letzte Seite</u></font><br>";
	print "&nbsp;<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$prev_pagenum&images=$prev_images\"><font size=2 face=verdana,helvetica color=\"$link_color\">vorherige Seite</a></font><font size=2 face=verdana,helvetica color=\"$text\"> | </font>";
	print "<font size=2 face=verdana,helvetica color=\"$darkened_links\"><u>nächste Seite</u></font><br>";
}

############------------------#############
##the GALLERYFOOTER print segment can be modified to include a custom footer.

print <<GALLERYFOOTER;
	</td></tr></table>
<p align="center"><font face="Verdana" size="3" color="#0000FF"><b><a href="http://www.vilstalweb.de/wuerdinger/fasching/highlights.htm">zum
Rückblick auf die letzten Faschingsmärkte</a></b></font></p>

</center>
	</BODY>
</HTML>
GALLERYFOOTER
############------------------#############

exit;


##---------Subroutines---------##

sub parse_form {
	$method = $ENV{'REQUEST_METHOD'};
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	if (length($buffer) < 5) {
		$buffer = $ENV{QUERY_STRING};
	}
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$FORM{$name} = $value;
	}
	$pagenum = $FORM{'pagen'};
	$forloopvar = $FORM{'images'};
	$query_picfolder = $FORM{'dir'};
}

sub read_dir {

	opendir(THISDIR, $pathtogallery) or die "cannot open $pathtogallery: $!";
	@unsortedfiles = grep { $_ ne '.' and $_ ne '..' } readdir THISDIR;
	closedir THISDIR;

}

sub page_numbers {
	local $pages_d = ($pages_displayed - 1) / 2;
	local $pagenumadd = $pagenum + $pages_d;
	local $pagenumminus = $pagenum - $pages_d;

	if ($pagenumadd > $nop){
		$pagenumadd = $nop;
	}
	
	if ($pagenumminus < 1){
		$pagenumminus = 1;
	}

	local $loopvar = $images_per_page * ($pagenumminus - 1); 

	for (my $i = $pagenumminus; $i <= $pagenumadd; $i++){
		local $i_minus = $i - 1;
		if ($i == $pagenum){
			print "<font color=\"$darkened_links\">$i</font>&nbsp;";
		}else{
			print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$i_minus&images=$loopvar\"><font color=\"$link_color\">$i</font></a>&nbsp;";
		}
		$loopvar += $images_per_page;
	}
}

sub getWidthHeight {
	my ($dimension) = @_;
	my $graphic_file = $pathtogallery . $image_array[$image_array];
        open(GRAPHIC, "$graphic_file") || die "Can't open graphic $file $!";
        binmode(GRAPHIC); # necessary for non UNIX perl

        if ($graphic_file =~ /\.gif$/i) {
                $tags = &gifSize(GRAPHIC);
        }
        elsif ($graphic_file =~ /\.jpg$|.jpeg$/i) {
                $tags = &jpegSize(GRAPHIC);
        }
        else {
        	$tags = "400 400"; #This will be the default window dimension size if the 
        			   #media is not GIF or JPEG.	
        }

        close  (GRAPHIC);
	
	@tags = split(/ /, $tags);
	
	if ($dimension eq "HEIGHT") {
		return $tags[0];
	}
	elsif ($dimension eq "WIDTH") {
		return $tags[1];	
	}
	else {
		return "400"; #Again, this is the default dimension if programmer didn't choose
			      #either WIDTH or HEIGHT when calling the subroutine.	
	}
}

sub gifSize {
# return a string of height and width tags for a gif.
# this subroutine adapted from:
# http://www.bewley.net/perl/gtindex.html

	my ($GIF) = @_;
	my ($w, $w2, $h, $h2, $gifwidth, $gifsize, $type) = () ;

	read ($GIF, $type, 3);
	seek ($GIF, 6, 0); 
	read ($GIF, $w, 1);
	read ($GIF, $w2, 1);
	read ($GIF, $h,  1); 
	read ($GIF, $h2, 1);
	
	$width  = ord ($w) + ord ($w2) * 256;
	$height = ord ($h) + ord ($h2) * 256;
	return ("$height $width");

}

sub jpegSize {
# gets the width and height (in pixels) of a jpeg file
# this subroutine adapted from:
# http://www.bewley.net/perl/gtindex.html

  my ($JPEG) = @_;
  my ($done) = 0;
  my ($size) = "";

  read($JPEG, $c1, 1); read($JPEG, $c2, 1);
  if( !((ord($c1) == 0xFF) && (ord($c2) == 0xD8))){
    print "This is not a JPEG!";
    $done=1;
  }
  while (ord($ch) != 0xDA && !$done) {
    # Find next marker (JPEG markers begin with 0xFF)
    # This can hang the program!!
    while (ord($ch) != 0xFF) {  read($JPEG, $ch, 1); }
    # JPEG markers can be padded with unlimited 0xFF's
    while (ord($ch) == 0xFF) { read($JPEG, $ch, 1); }
    # Now, $ch contains the value of the marker.
    if ((ord($ch) >= 0xC0) && (ord($ch) <= 0xC3)) {
      read ($JPEG, $junk, 3); read($JPEG, $s, 4);
      ($a,$b,$c,$d)=unpack("C"x4,$s);
      $size=join("", '',$a<<8|$b,' ',$c<<8|$d );
      $done=1;
    } else {
      # We **MUST** skip variables, since FF's within variable names are
      # NOT valid JPEG markers
      read ($JPEG, $s, 2); 
      ($c1, $c2) = unpack("C"x2,$s); 
      $length = $c1<<8|$c2;
      if( ($length < 2) ){
        print "Erroneous JPEG marker length";
        $done=1;
      } else {
        read($JPEG, $junk, $length-2);
      }
    }
  }
  return $size;
}