#!/usr/bin/perl

# Purpose:  To display a gallery of photos.

# This is the actual display portion of the scripts

# Prereqs:
# - requires pgal_library.pl perl library
# - requires ImageMagick image manipulation tools be installed
# - requires cookies to be enabled on the browser

# Assumptions:
# - Currently only accepts JPEG images with a jpg or jpeg extention
# - Currently if a "converted" filespec exists, it will not check to confirm that the file
#       already the correct dimension but will assume so.

# RISKS:
# - I should be using suexec to deal with file management. Currently I am not. In order
# 	the scripts to function, the directory and files in it must be readable by the
#	same user that Apache is run by, the easiest way to do this is to just make them
#	world writable.  Yes, this is a HUGE SECURITY HOLE for your data.  I'll get around
#	to fixing it.  Use at your own risk.


#set useful stuff
use POSIX;
use CGI;
use CGI::Pretty;
use CGI::Session;
$q = new CGI;
require 'pgal_library.pl';

%GLOBAL = &globals;

$SCRIPT_TITLE="Photo Galleries";
$SCRIPT_HEADER_IMAGE="/pics/header_left_index.gif";

# Has a directory been chosen?
$VIRDIR = $q->param('VIRDIR') if ($q->param('VIRDIR'));

$VIRDIR =~ s/^\///g;
$VIRDIR =~ s/\/$//g; 
$DIRECTORY="$GLOBAL{ROOTDIR}/$VIRDIR";

# Display defaults - eventually put this into config file
$PERPAGE = 5;
$SIZE = "Medium";
$PAGE = 1;

# Get or set a persistent session
($SID,$COOKIE) = &getsid;

# Get gallery config info
%CONFIG = &read_config("$DIRECTORY/$GLOBAL{PGAL_CONFIG}");
@FILES = &read_config_files ($CONFIG{FILE});
%ROTATION = &read_config_rotation ($CONFIG{FILE});
%COMMENT = &read_config_comment ($CONFIG{FILE});
#$NUMFILES = $#FILES + 1;
my $DELETECOUNT = 0;
foreach $FILE (@FILES) {
  $DELETECOUNT++ if ($COMMENT{$FILE} =~ /^DELETED:/);
}

$NUMFILES = $CONFIG{NUMFILES} - $DELETECOUNT;

# print header info, graphics, etc.
&start_pgal_html($SID,$COOKIE,$CONFIG{HEADER_IMAGE},$CONFIG{TITLE});

# Check that a directory has been stated, otherwise start over
&startover ("$GLOBAL{PGALDIR}/index.pl") if (!$VIRDIR);

# Error out if couldn't get gallery config info above.
if (exists $CONFIG{1}) {
  print "$VIRDIR/\.pgal_config exists but could not be read.";
  &end_pgal_html;
  exit;
}


# Change defaults if set in gallery
$PERPAGE = $CONFIG{DEFAULTPERPAGE} if ($CONFIG{DEFAULTPERPAGE});
$SIZE = $CONFIG{DEFAULTSIZE} if ($CONFIG{DEFAULTSIZE});
$PAGE = $CONFIG{PAGE} if ($CONFIG{PAGE});


# Override settings if passed in parameter
$PERPAGE = $q->param('PERPAGE') if ($q->param('PERPAGE'));
$SIZE = $q->param('SIZE') if ($q->param('SIZE'));
$PAGE = $q->param('PAGE') if ($q->param('PAGE'));


# Start printing stuff

# Title
print $q->center($q->h3("$CONFIG{TITLE}")) if ($PAGE == 1);


# Date
print "<div class=\"$GLOBAL{CLASS_HEADER_SMALL}\">\n",
      "$CONFIG{DATE}<br>",
      "</div>" if (($PAGE == 1) && ($CONFIG{DATE}));


# Print Main Comment
&maincomment($CONFIG{MAINCOMMENT}) if ((defined $CONFIG{MAINCOMMENT}) && ($PAGE == 1));


# Print Selectable Options

&goback();
&options($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES);

print $q->p,
      "<div align=center>\n";

#Start Image Display Loop
$COUNT = 0;
foreach $FILE (@FILES) {
  next if ($COMMENT{$FILE} =~ /^DELETED:/);
  $COUNT++;
  $PERPAGE = $NUMFILES if ($PERPAGE == "all");
  next if (($COUNT <= ($PAGE - 1) * $PERPAGE) || ($COUNT > ($PAGE * $PERPAGE)));
  if ($FILE =~ /\.mov$/i) {
    &display_full_movie($VIRDIR, $FILE, $ROTATION{$FILE}, $DIRECTORY);
  } else {
    &display_full_image($VIRDIR, $FILE, $SIZE, $ROTATION{$FILE});
  }
  print "<br>&nbsp;&nbsp;<br>\n";
}

# Print Selectable Options Again
&options($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES);

print $q->p,
      "</div>\n";

&goback();

print "</div>\n";


# Write out footer
&end_pgal_html;
exit;


# Build and print MAINCOMMENT
sub maincomment {
  my ($COMMENT) = @_;
  my ($NEWCOMMENT,$MAINCOMMENT,$FIRSTLINE);

  $FIRSTLINE = 0;
  foreach $NEWCOMMENT (@{$COMMENT}) {
    $MAINCOMMENT = "$MAINCOMMENT\n" if ($FIRSTLINE = 1);
    $FIRSTLINE = 1 if ($FIRSTLINE == 0);
    $MAINCOMMENT = "${MAINCOMMENT}${NEWCOMMENT}";
  }
  $MAINCOMMENT =~ s/([^\n])\n([^\n])/$1<br>\n$2/g;
  $MAINCOMMENT =~ s/\n\n/\n<p>\n/g;
  print $MAINCOMMENT,
        $q->p;
}


# Display images
sub display_full_image {
  my ($VIRDIR, $FILE, $SIZE, $ROTATION) = @_;
  my ($CLASS);

  ($STARTFILE,$EXT) = split(/\./, $FILE);
  $CLASS = "CLASS_${SIZE}_$ROTATION";
  print "<div id=\"$GLOBAL{$CLASS}\">\n";
  &display_image($VIRDIR, $FILE, $SIZE, $ROTATION);
  print $COMMENT{$FILE},
        $q->br,
        "</div>\n";

  return 0;
}


# Display movies
sub display_full_movie {
  my ($VIRDIR, $FILE, $ROTATION, $DIRECTORY) = @_;

  print "<div id=\"$GLOBAL{CLASS_MOVIE}\">\n";
  &display_movie($VIRDIR, $FILE, $ROTATION, $DIRECTORY);
  print $COMMENT{$FILE},
        $q->p,
        "(NOTE: If you don't see an image above, you may need to install Quicktime to view the movie. ",
        "Go to <a href=\"http://www.apple.com/quicktime/download/\" target=\"_blank\">Apple's website (here)</a> ",
        "to download.",
        $q->br,
        "Some movies are LARGE and may take considerable time to download after you click on it - please be patient.)",
        $q->br,
        "</div>\n";

  return 0;
}


# Show the various options
sub options {
my ($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES) = @_;

  print "<div class=\"$GLOBAL{CLASS_HEADER_SMALL}\">\n";

  print "<table border=0 cellspacing=0 width=100%>\n",
           "<tr>\n",
              "<td width=33\% align=left>";

                &size($VIRDIR,$PERPAGE,$PAGE,$SIZE);

  print       "</td>",
              "<td width=34\% align=center>";

                &page($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES);

  print       "</td>",
              "<td width=33\% align=right>";

                &perpage($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES);

  print       "</td>",
           "</tr>",
        "</table>\n";

  print "</div>\n";
}


# Generate the perpage links
sub perpage {
  my ($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES) = @_;
  my ($COUNT, $NEWPAGE);

  print "Per Page",
        $q->br,
        "( ";

  foreach $COUNT ("5", "10", "15", "20", "all") {

    # Figure out new page to show based on new perpage
    $NEWPAGE = 1;
    $NEWPAGE = floor ((($PAGE - 1) * $PERPAGE) / $COUNT) +1 if ($COUNT ne "all");

    if ($COUNT == $PERPAGE) {
      print $q->strong("$COUNT ");
    } else {
      print $q->a({href=>"$GLOBAL{PGALDIR}/pgal_display.pl?VIRDIR=$VIRDIR&PERPAGE=$COUNT&PAGE=$NEWPAGE&SIZE=$SIZE"}, "$COUNT");
    }
    print ", " if ($COUNT ne "all");
  }

  print ")";

  return 0;
} 


# Generate the page links
sub page {
  my ($VIRDIR,$PERPAGE,$PAGE,$SIZE,$NUMFILES) = @_;
  my ($COUNT);

  print "Show Page",
        $q->br,
        "( ";
  $NEWPERPAGE = $PERPAGE;
  $NEWPERPAGE = $NUMFILES if ($PERPAGE eq "all");
  $COUNT = 1;

  while (($COUNT - 1) < ($NUMFILES / $NEWPERPAGE)) {
    if ($COUNT == $PAGE) {
      print $q->strong("$COUNT ");
    } else {
      print $q->a({href=>"$GLOBAL{PGALDIR}/pgal_display.pl?VIRDIR=$VIRDIR&PERPAGE=$PERPAGE&PAGE=$COUNT&SIZE=$SIZE"}, "$COUNT");
    }
    print ", " if ($COUNT < ($NUMFILES / $NEWPERPAGE));
    $COUNT++;
  }

  print ")";

  return 0;
}


# Generate the size links
sub size {
  my ($VIRDIR,$PERPAGE,$PAGE,$SIZE) = @_;
  my ($COUNT);

  print "Size",
        $q->br,
        "( ";
  foreach $COUNT ("Small", "Medium", "Large") {
    if ($COUNT eq $SIZE) {
      print $q->strong("$COUNT ");
    } else {
      print $q->a({href=>"$GLOBAL{PGALDIR}/pgal_display.pl?VIRDIR=$VIRDIR&PERPAGE=$PERPAGE&PAGE=$PAGE&SIZE=$COUNT"}, "$COUNT");
    }
    print ", " if ($COUNT ne "Large");
  }

  print ")";

  return 0;
}


# Generate Go back to gallery link
sub goback {
  print "<div class=\"$GLOBAL{CLASS_HEADER_SMALL}\">\n",
        "<a href=/pgal/>Go back to Gallery List</a>",
        $q->p,
        "</div>\n";
}
