<?php
/**
 * Diese Datei stellt die verschiedenen Funktionen für den Aufbau der
 * Bildergallerie zur Verfügung.
 *
 * Copyright (c) 2007, 2008 Jan Dittberner <jan@dittberner.info>
 * Jan Dittberner IT-Consulting & -Solutions,
 * Cottbuser Str. 1, D-01129 Dresden
 *
 * This file is part of the ScrollingJQueryGallery component of the
 * gnuviech-server.de Websitetools
 *
 * ScrollingJQueryGallery is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * ScrollingJQueryGallery is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ScrollingJQueryGallery.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Version: $Id$
 */

define(GALLERYPREFIX, "bilder");
define(INFOFILE, "galleryinfo.ini");
define(IMAGESEC, "images");
define(GALLERYSEC, "gallery");
define(GALLERY_RE, '/^[\w\d _-]+$/');

$previewwidth = 311;
$thumbheight = 67;

function galleryExists($galleryname) {
  return preg_match(GALLERY_RE, $galleryname) &&
    realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR . $galleryname);
}

function getGalleryConfig($galleryname = null) {
  if ($galleryname) {
    $filepath = realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR .
                         $galleryname . DIRECTORY_SEPARATOR . INFOFILE);
  } else {
    $filepath = realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR . INFOFILE);
  }
  if (is_file($filepath)) {
    return parse_ini_file($filepath, true);
  }
  return array();
}

/**
 * Holt die Bildinformationen zu einem Bild aus der Datei
 * bilder/imginfo.txt und gibt diese zurueck.
 *
 * @param $imagename Bildname
 * @param $galleryname Galleriename
 */
function getImgInfo($galleryname, $imagename) {
  return array("name" => $imagename,
               "data" => getImageLabel($galleryname, $imagename),
               "preview" => GALLERYPREFIX . DIRECTORY_SEPARATOR .
               getScaledImage($galleryname, $imagename,
                              $GLOBALS["previewwidth"], false),
               "full" => GALLERYPREFIX . DIRECTORY_SEPARATOR . $galleryname .
               DIRECTORY_SEPARATOR . $imagename
               );
}

function getImageLabel($galleryname, $imagename) {
  $gallerypath = realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR . $galleryname);
  if (empty($gallerypath) || !is_dir($gallerypath)) {
    return false;
  }
  $filepath = $gallerypath . DIRECTORY_SEPARATOR . $imagename;
  if (!is_file($filepath)) {
    return false;
  }
  $inidata = getGalleryConfig($galleryname);
  $value = $inidata[IMAGESEC][$imagename];
  if ($value) {
    return $value;
  }
  return $imagename;
}

/**
 * Liefert die aktuelle Gallerie. Die Gallerie kann entweder im
 * GET-Parameter "galleryname" stehen, in der "gallery"-Sektion der
 * zentralen galleryinfo.ini angegeben werden oder es wird das erste
 * Unterverzeichnis von GALLERYPREFIX verwendet.
 */
function getCurrentGallery() {
  if (galleryExists($_GET["galleryname"])) {
    return $_GET["galleryname"];
  }
  $filepath = realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR . INFOFILE);
  if (!empty($filepath)) {
    $inidata = getGalleryConfig();
    if (galleryExists($inidata[GALLERYSEC]["default"])) {
      return $inidata[GALLERYSEC]["default"];
    }
  }
  foreach (glob(realpath(GALLERYPREFIX) . DIRECTORY_SEPARATOR . '*',
                GLOB_ONLYDIR) as $directory) {
    $basename = basename($directory);
    if (galleryExists($basename)) {
      return $basename;
    }
  }
  return null;
}

function getScaledImage($galleryname, $basename, $maxdim, $scaleheight=true) {
  if ($maxdim == 0) {
    debug_print_backtrace();
  }
  $gallerydir = realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR . $galleryname);
  if ($scaleheight) {
    $scaleddir = sprintf("%s%sscaled_x%d", $galleryname,
                         DIRECTORY_SEPARATOR, $maxdim);
  } else {
    $scaleddir = sprintf("%s%sscaled%dx_", $galleryname,
                         DIRECTORY_SEPARATOR, $maxdim);
  }
  $scaleddirpath = GALLERYPREFIX . DIRECTORY_SEPARATOR . $scaleddir;
  if (!is_dir($scaleddirpath)) {
    // versuchen das Thumbnail-Verzeichnis anzulegen
    $mkdir = @mkdir($scaleddirpath, 0755);
    if (!$mkdir) {
      return $galleryname . DIRECTORY_SEPARATOR . $basename;
    }
  }
  
  $scaledimage = $scaleddirpath . DIRECTORY_SEPARATOR . $basename;
  if (!is_file($scaledimage)) {
    // Datei erzeugen
    $originalfile = $gallerydir . DIRECTORY_SEPARATOR . $basename;
    $origimage = imagecreatefromjpeg($originalfile);
    $origx = imagesx($origimage);
    $origy = imagesy($origimage);
    if ($scaleheight) {
      $scaleratio = $origy / (1.0 * $maxdim);
      $newy = $maxdim;
      $newx = (int) $origx / $scaleratio;
    } else {
      $scaleratio = $origx / (1.0 * $maxdim);
      $newx = $maxdim;
      $newy = (int) $origy / $scaleratio;
    }
    $newimage = imagecreatetruecolor($newx, $newy);
    imagecopyresampled($newimage, $origimage, 0, 0, 0, 0, $newx, $newy,
                       $origx, $origy);
    imagejpeg($newimage, $scaledimage, 90);
  }
  return $scaleddir . DIRECTORY_SEPARATOR . $basename;
}

/**
 * Gibt die Informationen über Vorschaubilder zurück.
 *
 * @return array das erste Element ist die aufsummierte Breite der
 * Einzelbilder und das zweite Element ist ein assoziatives Array mit
 * den Bildnamen als Keys und dem Ergebnis von getimagesize() als
 * Werten
 */
function getThumbNailInfo($galleryname) {
  $thumbsizes = array();
  $thumbwidthsum = 2;
  foreach (glob(realpath(GALLERYPREFIX . DIRECTORY_SEPARATOR .
                         $galleryname) . DIRECTORY_SEPARATOR .
                '*.jp{e,}g', GLOB_BRACE) as $filename) {
    $basename = basename($filename);
    $thumbfile = getScaledImage($galleryname, $basename,
                                $GLOBALS["thumbheight"]);
    if ($thumbsize = getimagesize(realpath(GALLERYPREFIX .
                                           DIRECTORY_SEPARATOR .
                                           $thumbfile))) {
      $thumbsizes[$basename] = array($thumbfile, $thumbsize);
      $thumbwidthsum = $thumbwidthsum + $thumbsize[0] + 3;
    }
  }
  return array($thumbwidthsum, $galleryname, $thumbsizes);
}

function getGalleryLinks() {
}

function showThumbnails(&$thumbinfo) {
  foreach ($thumbinfo[2] as $basename => $data) {
    printf("<div class=\"thumbnail\"><img src=\"%s\" alt=\"\" \"%s\" /></div>",
           GALLERYPREFIX . DIRECTORY_SEPARATOR . $data[0],
           $data[1][3]);;
  }
}

function showPreview(&$thumbinfo) {
  foreach ($thumbinfo[2] as $basename => $data) {
    $galleryname = $thumbinfo[1];
    $fullname = GALLERYPREFIX . DIRECTORY_SEPARATOR . $galleryname .
      DIRECTORY_SEPARATOR . $basename;
    $scaledimage = getScaledImage($galleryname, $basename,
                                  $GLOBALS["previewwidth"], false);
    $scaledimagesize = getimagesize(realpath(GALLERYPREFIX .
                                             DIRECTORY_SEPARATOR .
                                             $scaledimage));
    printf("<a href=\"%s\" class=\"lightbox\" ><img id=\"contentimg\" src=\"%s%s%s\" alt=\"%s\" %s /></a>",
           $fullname, GALLERYPREFIX, DIRECTORY_SEPARATOR, $scaledimage,
           getImageLabel($galleryname, $basename), $scaledimagesize[3]);
    break;
  }
}

function renderDescription(&$thumbinfo) {
  foreach ($thumbinfo[2] as $basename => $data) {
    print htmlentities(getImageLabel($thumbinfo[1], $basename));
    break;
  }
}