#!/usr/local/bin/php
<?php

include_once("album.config.php");
include_once("album.inc.php");
include_once("image.inc.php");
include_once("inifile.php");

$albumConfig['onlyImages'] = false;
$albumConfig['createImages'] = true;
$albumConfig['createInfo'] = false;
$albumConfig['copyCSS'] = true;

// Default title
$title = "My";

array_shift($_SERVER["argv"]);
do
{
   switch(current($_SERVER["argv"]))
   {
   case "--imagesonly":
      $albumConfig['onlyImages'] = true;
      break;
   case "--noimages":
      $albumConfig['createImages'] = false;
      break;
   case "--createinfo":
      $albumConfig['createInfo'] = true;
      break;
   case "--nocss":
      $albumConfig['copyCSS'] = false;
      break;
   case "--irregular":
      $albumConfig['ratingAction'] = RATING_SIZES;
      break;
   case "--regular":
      $albumConfig['ratingAction'] = RATING_SELECTOR;
      break;
   case "--srcdir":
      array_shift($_SERVER["argv"]);
      $srcDir = current($_SERVER["argv"]);
      break;
   case "--dstdir":
      array_shift($_SERVER["argv"]);
      $dstDir = current($_SERVER["argv"]);
      break;
   case "--title":
      $title = current($_SERVER["argv"]);
      break;
   default:
      if(isset($srcDir))
         $dstDir = current($_SERVER["argv"]);
      else
         $srcDir = current($_SERVER["argv"]);
      break;
   }
   array_shift($_SERVER["argv"]);
}
while(count($_SERVER["argv"]));

if(!isset($srcDir) || !isset($dstDir))
{
   echo "Usage:\tstaticalbum [options] [--srcdir] srcdir [--dstdir] dstdir\n\n";
   echo "Options:\n";
   echo "\t--imagesonly\tCreate thumbnails only, no HTML files\n";
   echo "\t--noimages\tCreate no thumbnails, only HTML files\n";
   echo "\t--createinfo\tCreate {$albumConfig['infoFile']} files\n";
   echo "\t--nocss\t\tDo not create local copy of CSS file\n";
   return 1;
}

// Copy CSS file?
if($albumConfig["copyCSS"])
{
   $fp = fopen("{$dstDir}/album.css", "w");
   fwrite($fp, join('', file($albumConfig['cssURL'])));
   fclose($fp);
}

// If we are creating HTML files, copy image borders
if($albumConfig['createImages'])
{
   $dir = dirname($_SERVER['SCRIPT_FILENAME']);
   mkdirRecursive("{$dstDir}/images");

   $images = array(
      "border-l.gif", "border-t.gif", "border-r.gif", "border-b.gif",
      "border-tl.gif", "border-tr.gif", "border-bl.gif", "border-br.gif",
      "2border-l.gif", "2border-t.gif", "2border-r.gif", "2border-b.gif",
      "2border-tl.gif", "2border-tr.gif", "2border-bl.gif", "2border-br.gif");

   foreach($images as $img)
      copy("{$dir}/images/{$img}", "{$dstDir}/images/{$img}");
}

// Create all image and HTML files
$ratings = ($albumConfig['ratingAction'] & RATING_SELECTOR) ? 5 : 1;
$imageIndex = array();

for($showRating = 1; $showRating < $ratings; $showRating++)
{
   if($ratings > 1)
      fwrite(STDERR, "Processing rating level {$showRating}...\n");

   createAlbum($srcDir, $dstDir, 0, $ratings != 1);

   if(isset($albumConfig['slideShow']))
   {
      foreach($imageIndex as $dir => $files)
         fixCrossJumps($dir, $dstDir);
      
      // And finally for the toplevel file
      $next = getNextFile("{$dstDir}", 0);
      $post = $showRating == 1 ? "" : "-{$showRating}";
      appendLink("{$dstDir}/index{$post}.html", "{$next}/index-{$showRating}-1.html" );
   }
}

if(!$albumConfig['onlyImages'])
{
   $fp = fopen("{$dstDir}/index-slideshow.html", "w");
   fwrite($fp, "<html><head><script>nextImage = ''; slideShow = false;" .
               "function init() { imgFrame.form.slideshow.checked = slideShow; slide(); }" .
               "function slide() { setTimeout('image()'," .$albumConfig['slideShow'] ."); }" .
               "function image() { slideShow = imgFrame.form.slideshow.checked;" .
               "if(imgFrame.form.slideshow.checked && nextImage != '') {" .
               "var l = imgFrame.location.href; imgFrame.location.href = l.substring(0, l.lastIndexOf('/') + 1) + nextImage; } else imgFrame.form.slideshow.checked = false; }");
   fwrite($fp, "</script></head>");
   fwrite($fp, "<frameset rows='100%' border=0 frameborder=0 framespacing=0>");
   fwrite($fp, "<frame name='imgFrame' src='index.html' scrolling=no marginwidth=0 marginheight=0>");
   fwrite($fp, "</frameset></html>");
   fclose($fp);
}

return;

// Support functions for appending a reference to the next image for each image page

function fixCrossJumps($dir, $dstDir)
{
   global $imageIndex, $albumConfig, $showRating;

   fwrite(STDERR, "Generating slideshow jumps for {$dir}...\n");

   for($i = 0, $cnt = count($imageIndex[$dir]); $i < $cnt; $i++)
   {
      $file = $imageIndex[$dir][$i];
      if(in_array(strtolower(substr($file, strrpos($file, ".")+1)), $albumConfig['imgSuffix']))
      {
         $next = getNextFile($dir, $i+1);
         appendLink("{$dir}/{$file}/index-{$showRating}-1.html", "../{$next}/index-{$showRating}-1.html" );
         appendLink("{$dir}/{$file}/index-{$showRating}-2.html", "../{$next}/index-{$showRating}-2.html");
      }
      else
      {
         $next = getNextFile("{$dir}/{$file}", 0);
         $post = $showRating == 1 ? "" : "-{$showRating}";
         appendLink("{$dir}/{$file}/index{$post}.html", "{$next}/index-{$showRating}-1.html" );
      }
   }
}

function getNextFile($dir, $index)
{
   global $imageIndex, $albumConfig, $showRating;
   for($i = $index, $cnt = count($imageIndex[$dir]); $i < $cnt; $i++)
   {
      $file = $imageIndex[$dir][$i];
         
      if(in_array(strtolower(substr($file, strrpos($file, ".")+1)), $albumConfig['imgSuffix']))
         return $file;
      else
      {
         $next = getNextFile("{$dir}/{$file}", 0);
         return ($next != "" ? "{$file}/{$next}" : "");
      }
   }

   // If we are here, we were the last image in the directory

   $parent = dirname($dir);
   if(is_array($imageIndex[$parent]))
   {
      $index = array_search(basename($dir), $imageIndex[$parent]);
      $next = getNextFile($parent, $index+1);
      return ($next != "" ? "../{$next}" : "");
   }
   else
      return "";
}

function appendLink($file, $next)
{
   if(file_exists($file))
   {
      $fp = @fopen($file, "a+");
      @fwrite($fp, "<script>if(parent.slide) parent.nextImage = '{$next}'</script>");
      @fclose($fp);
   }
}

// Support function for traversing all directories

function createAlbum($srcDir, $dstDir, $level, $useRatings)
{
   global $albumConfig, $albumName, $showRating, $imageIndex, $title;

   fwrite(STDERR, "Creating album for directory '$srcDir'...\n");

   $iniFile = new IniFile("{$srcDir}/{$albumConfig['infoFile']}");
   $albumName = $srcDir;

   if($showRating == 1)
      mkdirRecursive($dstDir);

   // Get all files in there and copy images and create thumbs and image pages
   $imageIndex[$dstDir] = $iniFile->getSections();

   $handle = @opendir($srcDir);
   while($file = @readdir($handle))
      if(!in_array($file, $imageIndex[$dstDir]) &&
            (in_array(strtolower(substr($file, strrpos($file, ".")+1)), $albumConfig['imgSuffix']) ||
            (is_dir("{$srcDir}/{$file}") && $file != "thumbs" && $file[0] != ".")))
      $imageIndex[$dstDir][] = $file;
   @closedir($handle);

   for($i = 0, $cnt = count($imageIndex[$dstDir]); $i < $cnt; $i++)
   {
      $file = $imageIndex[$dstDir][$i];
      $next = ($i < $cnt - 1) ? $imageIndex[$dstDir][$i+1] : null;

      if(in_array(strtolower(substr($file, strrpos($file, ".")+1)), $albumConfig['imgSuffix']))
      {
         fwrite(STDERR, "\tProcessing image '$file'... ");

         $albumConfig['staticLevel'] = str_repeat("../", $level+1);
         if(isset($albumConfig['copyCSS']))
            $albumConfig['cssURL'] = $albumConfig['staticLevel'] . "album.css";

         if($showRating == 1)
            mkdirRecursive("{$dstDir}/{$file}/thumbs/medium");

         if($albumConfig['createImages'] && $showRating == 1)
            createThumbs("{$srcDir}/{$file}", $dstDir);
         if(!$albumConfig['onlyImages'])
         {
            if($showRating == 1 || ($iniFile->valueExists($file, 'rating') && $iniFile->getValue($file, 'rating') >= $showRating))
            {
               fwrite(STDERR, "HTML files... ");
               createImagePage(1, "{$srcDir}/{$file}", $dstDir, $iniFile, $useRatings);
               createImagePage(2, "{$srcDir}/{$file}", $dstDir, $iniFile, $useRatings);
            }
         }
         fwrite(STDERR, "\n");

      }
      else
      {
         if($showRating == 1)
            mkdirRecursive("{$dstDir}/{$file}");

         createAlbum("{$srcDir}/{$file}", "{$dstDir}/{$file}", $level+1, $useRatings);

         if($albumConfig['createImages'] && $showRating == 1)
         {
            $thumb = "{$srcDir}/{$file}/thumbs/album.jpg";
            if(is_file($thumb))
            {
               fwrite(STDERR, "\tCopying album thumbnail...\n");
               copy($thumb, "{$dstDir}/{$file}/album.jpg");
            }
            else
            {
               fwrite(STDERR, "\tCreating album thumbnail...\n");
               createAlbumThumb("{$dstDir}/{$file}", "{$dstDir}/{$file}");
            }
         }
      }
   }

   if(!$albumConfig['onlyImages'])
   {
      $albumConfig['staticLevel'] = str_repeat("../", $level);
      if(isset($albumConfig['copyCSS']))
         $albumConfig['cssURL'] = $albumConfig['staticLevel'] . "album.css";

      ob_start();
      fwrite(STDERR, "\tCreating HTML file for directory '$srcDir'...\n");

      displayAlbum($iniFile, "", ($level == 0) ? $title : $srcDir, $level > 0, "{$dstDir}/{$albumConfig['infoFile']}", $albumConfig["createInfo"]);

      $postfix = ($useRatings && $showRating > 1) ? "-{$showRating}" : "";
      $fp = fopen("{$dstDir}/index{$postfix}.html", "w");
      fwrite($fp, ob_get_contents());
      fclose($fp);

      ob_end_clean();
   }
}

function createImagePage($size, $imageName, $dstDir, $iniFile, $useRatings)
{
   global $albumConfig, $showRating;

   $image = basename($imageName);
   $dir = "{$dstDir}/{$image}";

   ob_start();
   displayImagePage($imageName, $imageName, $size, $iniFile);

   $p = $useRatings ? "-{$showRating}" : "";
   $fp = @fopen("{$dir}/index{$p}-{$size}.html", "w");
   @fwrite($fp, ob_get_contents());
   @fclose($fp);

   ob_end_clean();
}

function createThumbs($imageName, $dstDir)
{
   global $albumConfig;

   $image = basename($imageName);
   $dir = "{$dstDir}/{$image}";

   fwrite(STDERR, "copying image... ");
   copy($imageName, "{$dir}/{$image}");

   $thumb = dirname($imageName) . "/thumbs/" . basename($imageName);
   if(is_file($thumb))
   {
      fwrite(STDERR, "copying small thumbnail... ");
      copy($thumb, "{$dir}/thumbs/" . basename($imageName));
   }
   else
   {
      fwrite(STDERR, "creating small thumbnail... ");
      createThumb("{$dir}/{$image}", 0);
   }

   $thumb = dirname($imageName) . "/thumbs/medium/" . basename($imageName);
   if(is_file($thumb))
   {
      fwrite(STDERR, "copying medium image... ");
      copy($thumb, "{$dir}/thumbs/medium/" . basename($imageName));
   }
   else
   {
      fwrite(STDERR, "creating medium image... ");
      createThumb("{$dir}/{$image}", 1);
   }
}

?>
