#!/usr/bin/perl

##############################################################################
# Picture.cgi                     Version 2.1.8                              #
# Copyright 2003  Glenn Dempsey   webmaster@clovenfoot.com                   #
# Created 07/25/01                Last Modified 09/02/03                     #
# Cloven Foot:                    http://clovenfoot.com                      #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2003  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 #
##############################################################################

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

if ( (-e "config.cgi") && (-r "config.cgi") && (-s "config.cgi") ){ 
	require "config.cgi";
}
else{
	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 "You must use an odd number for the \$page_displayed variable.  Try again by modifying the config.cgi file.\n";
	exit;
}

#get rid of ".." "thumbs" and other directory names, and just keep image files
@unsortedfiles = grep /\.($media)/gi, @unsortedfiles;

#Set the type of sorting for the pictures
if ($sorting eq "rev_timestamp"){
	&file_date; #subroutine to capture the timestamps of all the files
	@image_array = sort { $date_hash{$a} <=> $date_hash{$b} || $a cmp $b } keys %date_hash;  #sort the hash by timestamp and put the sorted keys into an array
}
elsif ($sorting eq "timestamp"){
	&file_date; #subroutine to capture the timestamps of all the files
	@image_array = reverse sort { $date_hash{$a} <=> $date_hash{$b} || $a cmp $b } keys %date_hash;  #sort the hash by timestamp and put the sorted keys into an array
}
elsif ($sorting eq "reverse"){
	@image_array = reverse sort { lc $a cmp lc $b } @unsortedfiles;
}
elsif ($sorting eq "normal"){
	@image_array = sort { lc $a cmp lc $b } @unsortedfiles;
}
elsif ($sorting eq "none"){
	@image_array = @unsortedfiles;
}
else {
	@image_array = reverse sort { lc $a cmp lc $b } @unsortedfiles;
}
#Done setting type of sorting

$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
	$orig_thumbs_per_row = $thumbs_per_row;
	$td_width = ($thumb_width * $thumbs_per_row) + (($thumb_border * 2) * $thumbs_per_row);
	$total_thumb_width = $thumb_width+($thumb_border * 2);
#End calculate

#
# Get the status of motion on the server:
#
$motion_status = `pgrep -f "/usr/local/bin/motion"`;
if ( $motion_status == "" ) {
	$motion_status = "<font color=pink>off</font>";
} else {
	$motion_status = "<font color=lightgreen>on</font>";
}


############------------------#############
#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 - Page $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,name) {
			
			if (popupWidth > chasm) {
				popupWidth = chasm - 10;
			}
			if (popupHeight > mount) {
				popupHeight = mount - 40;
			}
			
			putItThere = window.open(URL,name,"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 bgcolor="$bgcolor" text="$text" link="$pic_border" vlink="$pic_border" alink="$pic_border" style="background-image: url(mimi_bg.png); background-repeat: no-repeat; background-position: right bottom;">
<!--	<center>	-->
	<span style="position: absolute;">motion detection is: $motion_status</span>
	<center><h1>[::kitty_foodcam::]</h1><font size=1 style="position: relative; top: -15px;">it's foodalicious!</font></center>
	<table cellspacing="0" cellpadding="0" border="0" style="margin-left: 50px;"><tr><td width="$td_width" align="left">
GALLERYHEADER
############------------------#############

$forloopimages = $images_per_page - 1;
$table_incre = 0;

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

	(local $firstsplit1) = split(/\.($media)/, $image_array[$image_array]);
	(local $secondsplit1, local $secondsplit2) = split(/\-/, $firstsplit1);
	if ($filename_convention eq "on") {
		$secondsplit2 =~ s/\_/ /g;
	}
	last if ($image_array > ($number_of_images - 1));
	
	$theWidth = &getWidthHeight(WIDTH);
	
	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		
	}

	#
	# This is a hack to reference a corresponding .flv file.
	#
	$video_file = $image_array[$image_array];
	$video_file =~ s/-\d+\.(gif|jpg|jpeg)$/\.flv/;

	#print $video_file;

	#This URL escapes the variables of the image so it will work in Netscape.
	$image_array[$image_array] =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;
		
	$firstsplit1_escaped = $firstsplit1;
	$firstsplit1_escaped =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;

	$secondsplit2_escaped = $secondsplit2;
	$secondsplit2_escaped =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;

	if($table_incre == 0 || $table_incre == $thumbs_per_row){
		print "<table cellspacing=$cellspacing cellpadding=$cellpadding border=0><tr>\n";
		
		if ($captions eq "on"){
			print "<td height=6></td></tr><tr>\n";
		}
	}

	print "<td align=center valign=top>\n";

	if ($captions eq "on"){
		print "<table width=$total_thumb_width cellspacing=0 cellpadding=0 border=0><tr><td align=center valign=top>\n";
	}

	print "<a href=\"$directory/$picture_folder/$image_array[$image_array]\" onClick=\"popupwindow(\&#34;$directory/popup.html?name=$image_array[$image_array]&title=" . ($filename_convention eq "off" ? $firstsplit1_escaped : $secondsplit2_escaped) . "&picdirectory=$pic_directory&text=$text&linkcolor=$link_color&bgcolor=$bgcolor&width=$theWidth&height=$theHeight2&close=$close_button\&#34;,$theWidth,$theHeight,1$image_array); return false\"><img src=\"$directory/$picture_folder/" . ($nameofthumbfolder ne "null" ? "$nameofthumbfolder/" : "") . "$image_array[$image_array]\" alt=\"" . ($filename_convention eq "off" ? $firstsplit1 : $secondsplit2) . "\" title=\"" . ($filename_convention eq "off" ? $firstsplit1 : $secondsplit2) . "\" border=\"$thumb_border\" width=\"$thumb_width\" " . ($thumb_height ne "null" ? "height=\"$thumb_height\"" : "") . "></a><br>\n";
	###No more video 20081229
	###print "<a href=\"$directory/$picture_folder/$video_file\" onClick=\"popupwindow(\&#34;$directory/popup.html?name=$video_file&title=" . ($filename_convention eq "off" ? $firstsplit1_escaped : $secondsplit2_escaped) . "&picdirectory=$pic_directory&text=$text&linkcolor=$link_color&bgcolor=$bgcolor&width=$theWidth&height=$theHeight2&close=$close_button\&#34;,$theWidth,$theHeight,1$image_array); return false\"><img src=\"$directory/$picture_folder/" . ($nameofthumbfolder ne "null" ? "$nameofthumbfolder/" : "") . "$image_array[$image_array]\" alt=\"" . ($filename_convention eq "off" ? $firstsplit1 : $secondsplit2) . "\" title=\"" . ($filename_convention eq "off" ? $firstsplit1 : $secondsplit2) . "\" border=\"$thumb_border\" width=\"$thumb_width\" " . ($thumb_height ne "null" ? "height=\"$thumb_height\"" : "") . "></a><br>\n";
	
	if ($captions eq "on"){
		print "</td></tr><tr><td align=center valign=top><font size=$font_size face=$font>" . ($filename_convention eq "off" ? $firstsplit1 : $secondsplit2) . "</font></td></tr></table>\n";
	}

	print "</td>\n";

	if($table_incre == $thumbs_per_row - 1 && ($images_per_page - 1 != $table_incre)){
		print "</tr></table>\n";
	}

	if($thumbs_per_row == $table_incre){
		$thumbs_per_row = $thumbs_per_row + $orig_thumbs_per_row;
	}
	
	$table_incre++;
}
#End heart of the script

print "</tr></table></td></tr><tr><td height=10></td></tr><tr><td align=\"right\">";
print "<font size=$font_size face=$font color=$text>Page $pagenum out of $nop</font><br>";
print "<font size=$font_size face=$font color=$text>Total number of images: $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=$font_size face=$font color=\"$darkened_links\"><u>first</u></font><font size=$font_size face=$font color=\"$darkened_links\">&nbsp;&nbsp;|&nbsp;&nbsp;</font><font size=$font_size face=$font color=\"$darkened_links\"><u>last</u></font><br>";
	print "&nbsp;<font size=$font_size face=$font color=\"$darkened_links\"><u>previous</u></font><font size=$font_size face=$font color=\"$darkened_links\"> | </font>";
	print "<font size=$font_size face=$font color=\"$darkened_links\"><u>next</u></font><br>";
}
elsif ($pagenum == 1) {
	print "<font size=$font_size face=$font color=\"$darkened_links\"><u>first</u></font><font size=$font_size face=$font 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=$font_size face=$font color=\"$link_color\">last</font></a><br>";
	print "&nbsp;<font size=$font_size face=$font color=\"$darkened_links\"><u>previous</u></font><font size=$font_size face=$font color=\"$text\"> | </font>";
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$pagenum&images=$forloopvar\"><font size=$font_size face=$font color=\"$link_color\">next</font></a><br>";
}
elsif ($pagenum < $nop) {
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder\"><font size=$font_size face=$font color=\"$link_color\">first</font></a><font size=$font_size face=$font 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=$font_size face=$font color=\"$link_color\">last</font></a><br>";
	print "&nbsp;<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$prev_pagenum&images=$prev_images\"><font size=$font_size face=$font color=\"$link_color\">previous</a></font><font size=$font_size face=$font color=\"$text\"> | </font>";
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$pagenum&images=$forloopvar\"><font size=$font_size face=$font color=\"$link_color\">next</font></a><br>";
}
elsif ($pagenum == $nop){
	print "<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder\"><font size=$font_size face=$font color=\"$link_color\">first</font></a><font size=$font_size face=$font color=\"$text\">&nbsp;&nbsp;|&nbsp;";
	&page_numbers;
	print "|&nbsp;&nbsp;</font><font size=$font_size face=$font color=\"$darkened_links\"><u>last</u></font><br>";
	print "&nbsp;<a href=\"$cgi_location/$cgi_script?dir=$query_picfolder&pagen=$prev_pagenum&images=$prev_images\"><font size=$font_size face=$font color=\"$link_color\">previous</a></font><font size=$font_size face=$font color=\"$text\"> | </font>";
	print "<font size=$font_size face=$font color=\"$darkened_links\"><u>next</u></font><br>";
}

############------------------#############
#the GALLERYFOOTER print segment can be modified to include a custom footer.

print <<GALLERYFOOTER;
	</td></tr></table>
<!--	</center>	-->
	</BODY>
	</HTML>
GALLERYFOOTER
############------------------#############

exit;


##---------Subroutines---------##
sub file_date {
	foreach $a_file (@unsortedfiles){
		local $afile_path = $pathtogallery . $a_file;	#create the entire file path
		local $last_write = (stat($afile_path))[9];	#get the timestamp
		$date_hash{$a_file} = $last_write;		#add the timestamp to the hash
	}
}

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;
}
