<?php

// First check what exactly was requested in the SEO-friendly format?
if (!isset($_SERVER['PATH_INFO'])) {
    require(
'photo-albums.php');
    return;
}

$mode 'index';
$pic '';
$var_array explode("/"$_SERVER['PATH_INFO']);

if (
count($var_array) == 2
{
    if (
$var_array[1] == '') {
        require(
'photo-albums.php');
        return;
    } 


$album $var_array[1];
if (
count($var_array) > && $var_array[2] != '')
{
    
$pic $var_array[2];
    
$mode "single";
}

// directory locations relative to this script (not URL)
$pics_dir "photo";
$thumbs_dir "photo/thumbs";

//dimensions of thumbnails
$thumb_width 144;
$thumb_height 96;

$ext_pattern ".+\.png$|.+\.jpg$|.+\.avi$|.+\.wmv$|.+\.mpg$|.+\.mpeg$|.+\.mov$";
$ffmpeg_path "/usr/bin/ffmpeg";


function 
create_image_thumbnail($input_path$output_path$thumb_width$thumb_height
{
    
// get attributes of the original image
    
list($width,$height,$pictype) = getimagesize($input_path);

      
// read in the original image
    
switch ($pictype) {
        case 
$img imagecreatefromgif($input_path); break;
        case 
$img imagecreatefromjpeg($input_path); break;
        case 
$img imagecreatefrompng($input_path); break;
    }

    
// maintain the aspect ratio of the image
    
$new_width $thumb_width;
    if (
$width $height) {
        
$new_height $height * ($new_width/$width);
       } else {
        
$new_height $new_width;
        
$new_width $width * ($new_height/$height);
    }

    
// allocate memory for thumbnail image
    
$thumbnail imagecreatetruecolor($new_width$new_height);
    
    
// copy the original image into the thumbnail by resizing it
    
fastimagecopyresampled($thumbnail$img0000$new_width$new_height$width$height4);

    
// save thumbnail to file
    
switch ($pictype) {
        case 
imagegif($thumbnail$output_path); break;
        case 
imagejpeg($thumbnail$output_path); break;
        case 
imagepng($thumbnail$output_path); break;
    }

    return 
$thumbnail;
}


function 
create_video_thumbnail($input_path$thumb_path$thumb_width$thumb_height)
{
    
$cmd "/usr/bin/ffmpeg -i $input_path -ss 00:00:05 -t 00:00:1 -s $thumb_width"."x"."$thumb_height -r 1 -f mjpeg $output_path";
    
exec($cmd);

    
// overlay video icon
    
$insert imagecreatefromgif('video_icon.gif');
    
$background imagecreatefromjpeg($output_path);

    
$insert_x imagesx($insert); 
      
$insert_y imagesy($insert);
    
$background_x imagesx($background);
    
$background_y imagesy($background);

    
imagecopymerge($background,$insert,$background_x-$insert_x,$background_y-$insert_y,0,0,$insert_x,$insert_y,100);
    
imagejpeg($background,$output_path);
}


function 
read_directory($data_dir$ext
{
    
$dir_handle = @opendir($data_dir);
    if (
$dir_handle
    {
        while (
$file readdir($dir_handle)) 
            if (
eregi($ext,$file)) 
                
$files[] = $file;
        
        
closedir($dir_handle);
      }

    if (
gettype($files) == "array")
        
sort($files);
    else
        
$files false;

    return 
$files;
}


function 
index_print($album,$pics_dir,$thumbs_dir,$ext,$w,$h
{
    
$images read_directory($pics_dir."/".$album,$ext);

    if (!
$images)
        return 
"No files in <b>$pics_dir/$album</b>";

    
// if directory for thumbnails does not exist, create it
    
if (!file_exists("$thumbs_dir/$album")) 
        
mkdir("$thumbs_dir/$album"0777);

    
$selflink rtrim($_SERVER["PHP_SELF"], '/');
    
$html '<div id="index-print">';
    
    while (list(
$key$image) = each($images)) 
    {
        
$input_path "$pics_dir/$album/$image";
        
$thumb_path "$thumbs_dir/$album/$image";

        
// different handling depending on whether it is an image or a video
        
$type end(explode("."$image));
        
        if (!
strcasecmp($type"png") || !strcasecmp($type"jpg") || !strcasecmp($type"gif")) 
        {
            if (!
file_exists($thumb_path))
                
create_image_thumbnail($input_path$thumb_path$w$h);
        } 
        else    
// must be video 
        
{
            
$thumb_path .= ".jpg";
            if (!
file_exists($thumb_path)) 
                
create_video_thumbnail($input_path$thumbs_path$w$h);
        }

        
$html .= "\r\n\t<a href=\"$selflink/$image\"><img src=\"/$thumb_path\" alt=\"$image\"/></a>";
    }
    
$html .= "\r\n</div>\r\n";

    return 
$html;
}


function 
image_print($album$pic$pics_dir$ext
{
    
// find the next and previous images
    
$image_arr read_directory("$pics_dir/$album"$ext);
    
$prev '.';
    
$next '.';

    
// find this image in directory listing and capture previous and next
    // images
      
for ($i 0$i sizeof($image_arr); $i++) 
    {
        if (
$image_arr[$i] == $pic
        {
            if (
$i != 0)
                   
$prev $image_arr[$i-1];
    
            if (
$i != (sizeof($image_arr)-1)) 
                   
$next $image_arr[$i+1];
        
            break;
         }
    }  

    
// print out the HTML
    
$src "$pics_dir/$album/$pic";
      list(,,,
$sizestr) = getimagesize($src);
 
    
$html "<div id=\"single-photo\">\r\n";

    
// print the navigation
    
$html .= "<a href=\"$prev\">previous</a> | <a href=\".\">index</a> | <a href=\"$next\">next</a> <br/>";

    
// extract the location and caption if present
    
$size GetImageSize ($src,$info);
    list(
$width$height) = $size;
    if (isset(
$info["APP13"]))
    {
        
$iptc iptcparse ($info["APP13"]);
        
$location $iptc["2#090"][0] . ', ' $iptc["2#101"][0];
        
$caption $iptc["2#005"][0];
    }

    
$html .= "\r\n<img alt=\"$caption, $location\" src=\"/$src\" $sizestr/>";
 
    
// print the photo
    
$html .= "\r\n<table width='$width'>";
    
$html .= '<tr><td class="caption">';

    if (isset(
$caption))
        
$html .= "<b>$caption</b><br/>";

    if (isset(
$location))
        
$html .= $location;

    
$html .= '</td><td class="exif-info">';

    
// print the EXIF data (ISO, f-stop etc)
    
$exif exif_read_data ($src,0,true);
    if ((
$exif != false) && (isset($exif['EXIF'])))
    {
        
$html .= $exif['EXIF']['DateTimeOriginal'];
        
$html .= "<br/>ISO ";
        
$html .= $exif['EXIF']['ISOSpeedRatings'];
        
$html .= ", ";
        
$html .= $exif['EXIF']['ExposureTime'];
        
$html .= " sec, f/";
        
$pieces   explode("/"$exif['EXIF']['FNumber']);
        
$html .= $pieces[0]/$pieces[1];
        
$html .= " @ ";
        
$pieces   explode("/"$exif['EXIF']['FocalLength']);
        
$html .= $pieces[0]/$pieces[1];
        
$html .= " mm";
    }

    
$html .= "</td></tr>\r\n</table>";
    
$html .= '</div>';

    return 
$html;
}



function 
fastimagecopyresampled (&$dst_image$src_image$dst_x$dst_y$src_x$src_y$dst_w$dst_h$src_w$src_h$quality 3
{
    
// Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
      // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
      // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
      // Author: Tim Eckel - Date: 12/17/04 - Project: FreeRingers.net - Freely distributable.
      //
      // Optional "quality" parameter (defaults is 3).  Fractional values are allowed, for example 1.5.
      // 1 = Up to 600 times faster.  Poor results, just uses imagecopyresized but removes black edges.
      // 2 = Up to 95 times faster.  Images may appear too sharp, some people may prefer it.
      // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled.
      // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
      // 5 = No speedup.  Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled.

    
if (empty($src_image) || empty($dst_image)) { 
        return 
false
    }
      
    if (
$quality <= 1) {
        
$temp imagecreatetruecolor ($dst_w 1$dst_h 1);
        
imagecopyresized ($temp$src_image$dst_x$dst_y$src_x$src_y$dst_w 1$dst_h 1$src_w$src_h);
        
imagecopyresized ($dst_image$temp0000$dst_w$dst_h$dst_w$dst_h);
        
imagedestroy ($temp);
      } elseif (
$quality && (($dst_w $quality) < $src_w || ($dst_h $quality) < $src_h)) {
        
$tmp_w $dst_w $quality;
        
$tmp_h $dst_h $quality;
        
$temp imagecreatetruecolor ($tmp_w 1$tmp_h 1);
        
imagecopyresized ($temp$src_image$dst_x $quality$dst_y $quality$src_x$src_y$tmp_w 1$tmp_h 1$src_w$src_h);
        
imagecopyresampled ($dst_image$temp0000$dst_w$dst_h$tmp_w$tmp_h);
        
imagedestroy ($temp);
      } else {
        
imagecopyresampled ($dst_image$src_image$dst_x$dst_y$src_x$src_y$dst_w$dst_h$src_w$src_h);
      }
      return 
true;
}


function 
main($mode,$album,$pic,$pics_dir,$thumbs_dir,$w,$h,$ext=".jpg"
{
    if (
file_exists("$pics_dir/$album/title.txt"))
        
$album_name rtrim(file_get_contents("$pics_dir/$album/title.txt"));
    else {
        
$album_name '';
        
$tokens explode('-'$album);
        foreach (
$tokens as $token)
            
$album_name .= ucwords($token) . ' ';
      }

    
$page_title 'Photo Album: ' $album_name;
    
$page_description 'Photos from the album - '.$album_name;
    
$crumbs['Photos'] = '/photos/';
    
$crumbs[$album_name] = null;

      switch (
$mode) {
        case 
"single" :
            
$page_title .= " ($pic)";
            
$hide_rightmenu true;
            
$crumbs[$album_name] = '/photos/'.$album;
            
$crumbs[$pic] = null;
            include(
'header.inc');
            echo 
image_print($album,$pic,$pics_dir,$ext);
            break;
        default :
            include(
'header.inc');
            echo 
"<h2>$page_title</h2>\r\n";
            echo 
index_print($album,$pics_dir,$thumbs_dir,$ext,$w,$h);
      }

    include(
'footer.inc');
}


main($mode,$album,$pic,$pics_dir,$thumbs_dir,$thumb_width,$thumb_height,$ext_pattern);

?>