#!/usr/local/bin/perl

# Simple Gallery v.06b
# Copyright 2006-2008 Jeremy Kister http://jeremy.kister.net./

use strict;
use CGI qw(:standard -nosticky);
use CGI::Carp ('fatalsToBrowser');

my $q = CGI->new;

my $me = $ENV{'SCRIPT_NAME'};
my $dir = $q->param('dir');
die "dir: $dir\n" if($dir =~ /\.\./);
die "private area\n" if($dir =~ /private\//);
my $id = $q->param('id') || '1';
die "id: $id\n" unless($id =~ /^\d+$/);

my $path = $ENV{'DOCUMENT_ROOT'} . '/' . $dir;

print $q->header(-expires=>'now'), $q->start_html('Simple Gallery');
my (%files,%thumbs);
if(opendir(DIR, $path)){
	my $i = 1;
	foreach my $obj (sort grep {/\.(?:jpe?g|gif|png)/i} readdir DIR){
		unless(-d "$path/$obj"){
			$files{$i} = $obj;
			if(-s "$path/thumbnails/$obj"){
				$thumbs{$i} = $obj;
			}
		}
		$i++;
	}
	closedir DIR;
	my $x = ($id + 1);
	my $next = (exists($files{$x})) ? $x : 1;
	my $thumb = ( $thumbs{$id} && (! $q->param('nothumb')) ) ? 'thumbnails/' : '';

	print '<font size="2">', "\n",
	      '[ <a href="javascript:history.back(1)',
	      '">Back</a>', "\n",
	      ' | <a href="', $me, "?dir=${dir}&id=${id}&nothumb=1",
	      '">Enlarge</a>', "\n",
	      ' | <a href="', $me, "?dir=${dir}&id=${next}",
	      '">Next</a> ]', "\n",
	      "&nbsp;&nbsp;${thumb}$files{$id}\n",
	      "<br><br>\n",
	      '<a href="', $me, "?dir=${dir}&id=${next}",
 	      '">', "\n",
	      '<img border="0" src="', $dir, '/', $thumb, $files{$id}, '"></a><br>', "\n",
	      "</font>\n";
}else{
	print "could not open directory: $path: $!\n";
}

print $q->end_html();
