<?
/*

                                   _JNJ`
                               .JNMH`
                              JMMF`       `;.
                            .NMM)          `MN.
                            MMM)            (MML
                           (MMM`             MMML
                     M  I  D  N  I  G  H  T    C  o  D  E
                           (NMMF             MHNH
                            NMML            .MMM
                             NMML          .NMH
                              4MMNL       .#F
                               `4HNNL_   `
                                   `"""`

                          Copyright (C) 2004-2007
       "Ian (Larry) Latter" <ian dot latter at midnightcode dot org>

    Midnight Code is a registered trademark of Ian Latter.

    This program 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, and mirrored at the Midnight Code web
    site; as at version 2 of the License only.

    This program 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
    (version 2) along with this program; if not, write to the Free
    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA, or see http://midnightcode.org/gplv2.txt

*/

  // ---------------------------------------------------------------------- 

  /*
     Values for you to tune
  */

  $gallery_home_label           = "Top Gallery"; // Home title
  $crumb_delineater             = " :: ";        // Crumb seperator

  $thumbs_per_row               = 4;             // Gallery images per row
  $thumb_rows_per_page          = 0;             // Gallery rows per page

  $thumb_width                  = 0;             // Resize thumb width to this
  $thumb_height                 = 0;             // Resize thumb height to this
  $thumb_max                    = 200;           // Resize longest side to this

  $templates["gallery"]         = "gallery.tpl"; // Gallery template file
  $templates["picture"]         = "picture.tpl"; // Picture template file

  $gallery_thumb                = "gallery.png"; // Gallery thumb file
  $gallery_thumb_auto_scale     = 1;             // Resize static gallery thumb
  $picture_thumb_auto_scale     = 0;             // Resize static picture thumb

  $no_empty_tables              = 1;             // Dont display empty framing
  $gallery_labels               = 1;             // Display gallery labels
  $gallery_images_linked        = 1;             // Link gallery thumbs
  $gallery_image_text           = "Gallery";     // Default gallery thumb text
  $picture_labels               = 0;             // Display picture labels
  $picture_label                = 0;             // Display picture page label

  $image_on_page                = 1;             // Display single picture page

  $order_ascending              = 0;             // Order images by name
  $recursive_galleries          = 1;             // Allow sub-directory walking
  $image_cache                  = 1;             // Enable proxy/browser cache
  $image_cache_age              = 60 * 60 * 24;  // Cache for this many seconds

  $thumb_error_textless         = 0;             // Error thumbs without text
  $thumb_error_transparent      = 1;             // Error thumbs go transparent

  $uservar["action"]            = "action";      // Action user variable name
  $uservar["gallery"]           = "gallery";     // Gallery user variable name
  $uservar["image"]             = "image";       // Image user variable name


  // ----------------------------------------------------------------------


  /*
     Static values
  */

  // Permitted input by regex
  $acceptable_gallery           = 'a-zA-Z0-9\-\_\:';
  $acceptable_picture           = 'a-zA-Z0-9\-\_';
  $acceptable_file              = 'a-zA-Z0-9\-\_\.';
  $acceptable_integer           = '0-9';
  $acceptable_alpha             = 'a-zA-Z';
  $acceptable_alphanum          = 'a-zA-Z0-9';

  // Permitted input types
  $input_type_gallery           = 1;
  $input_type_picture           = 2;
  $input_type_file              = 4;
  $input_type_integer           = 8;
  $input_type_alpha             = 16;
  $input_type_alphanum          = 32;

  // Permitted action types
  $action_type_null             = 0;
  $action_type_gallery          = 0;
  $action_type_thumb_i          = 1;
  $action_type_picture          = 2;
  $action_type_picture_i        = 3;

  // Directory/Gallery conversion types
  $directory_to_gallery         = 1;
  $gallery_to_directory         = 2;

  // Recognised file types
  $entry_type_gallery           = 1;
  $entry_type_picture           = 2;
  $entry_type_any               = 3;

  // Filename annex reserved for static thumbs
  $image_thumb_label            = "-thumb";

  // Filename extensions reserved for image inclusion
  $image_extensions             = array();
  $image_extensions[]           = ".png";
  $image_extensions[]           = ".jpg";
  $image_extensions[]           = ".jpeg";
  $image_extensions[]           = ".gif";

  // Directory entries explicitly ignored - no wildcards
  $ignore_entries               = array();
  $ignore_entries[]             = ".";
  $ignore_entries[]             = "..";
  $ignore_entries[]             = ".htaccess";
  $ignore_entries[]             = $templates["gallery"];
  $ignore_entries[]             = $templates["picture"];
  $ignore_entries[]             = $gallery_thumb;

  // Cascading Style Sheet labels
  $gallery_class["table"]       = "gallery_table";
  $gallery_class["tr"]          = "gallery_tr";
  $gallery_class["td"]          = "gallery_td";
  $gallery_class["img"]         = "gallery_img";
  $gallery_class["a"]           = "gallery_a";
  $picture_class["table"]       = "picture_table";
  $picture_class["tr"]          = "picture_tr";
  $picture_class["td"]          = "picture_td";
  $picture_class["img"]         = "picture_img";
  $picture_class["a"]           = "picture_a";
  $crumb_class["a"]             = "crumb_a";

  // User template objects to be replaced with content
  $gallery_crumb_hole           = "%%CRUMBS%%";
  $gallery_galleries_hole       = "%%GALLERY_GALLERIES%%";
  $gallery_pictures_hole        = "%%GALLERY_PICTURES%%";
  $picture_image_hole           = "%%PICTURE_IMAGE%%";
  $picture_description_hole     = "%%PICTURE_DESCRIPTION%%";


  /*
     Other considerations;
  */
  header("Vary: Content-type, Accept, Accept-Encoding");
  $picview_self = $_SERVER[PHP_SELF];
  if(substr($picview_self, strlen($picview_self) - strlen("index.php"),
    strlen("index.php")) == "index.php")
    $picview_self = substr($picview_self, 0,
      strlen($picview_self) - strlen("index.php"));


  /*
     Functions
  */
  function picview_getinput($user_variable, $type) {
    global $acceptable_gallery, $acceptable_picture, $acceptable_file;
    global $acceptable_integer, $acceptable_alpha, $acceptable_alphanum;
    global $input_type_gallery, $input_type_picture, $input_type_file;
    global $input_type_integer, $input_type_alpha, $input_type_alphanum;

    $user_input = "";

    $raw_input = $_REQUEST[$user_variable];
    if($type & $input_type_gallery) {
      $regexp_val = '/^[' . $acceptable_gallery . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }
    if($type & $input_type_picture) {
      $regexp_val = '/^[' . $acceptable_picture . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }
    if($type & $input_type_file) {
      $regexp_val = '/^[' . $acceptable_file . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }
    if($type & $input_type_integer) {
      $regexp_val = '/^[' . $acceptable_integer . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }
    if($type & $input_type_alpha) {
      $regexp_val = '/^[' . $acceptable_alpha . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }
    if($type & $input_type_alphanum) {
      $regexp_val = '/^[' . $acceptable_alphanum . ']+$/';
      if(preg_match($regexp_val, $raw_input)) {
        $user_input = $raw_input;
      }
    }

    return $user_input;
  }


  function picview_gallerycrumbs($gallery, &$crumbs) {
    global $action_type_null, $action_type_gallery, $gallery_home_label;
    global $uservar;
    global $directory_to_gallery;
    global $picview_self;

    $crumb = 0;

    $gallery_parts = explode(":", $gallery);
    $directory = "./";
    $crumbs[$crumb]["url"]   = $directory;
    $crumbs[$crumb]["label"] = $gallery_home_label;
    foreach($gallery_parts as $gallery_part) {
      $crumb++;
      if(!strlen(trim($gallery_part)))
        continue;
      $directory .= trim($gallery_part) . "/";
      $this_gallery = "";
      picview_directorygallery($directory, $this_gallery,
        $directory_to_gallery);
      $url = $picview_self . "?";
      if($action_type_gallery != $action_type_null)
        $url .= $uservar["action"] . "=" . 
                rawurlencode($action_type_gallery) . "&";
      if(strlen($this_gallery))
        $url .= $uservar["gallery"] . "=" . 
                rawurlencode($this_gallery);
      $label = ucwords(str_replace("_", " ", $gallery_part));
      $crumbs[$crumb]["url"]   = $url;
      $crumbs[$crumb]["label"] = $label;
    }

    return;
  }


  function picview_displaycrumbs(&$content, $crumbs) {
    global $crumb_class, $gallery_crumb_hole, $crumb_delineater;

    $crumb_line = "";
    $crumb = count($crumbs);

    foreach($crumbs as $crumb_key => $crumb_value) {
      $crumb_description = htmlspecialchars($crumb_value["label"]);
      $crumb_line .= "<a href=\"" . $crumb_value["url"] . "\" " .
         "title=\"" . $crumb_description . "\" " .
         "alt=\"" . $crumb_description . "\" " .
         "class=\"" . $crumb_class["a"] . "\">";
      $crumb_line .= $crumb_description;
      $crumb_line .= "</a>";
      $crumb--;
      if($crumb > 0)
        $crumb_line .= $crumb_delineater;
    }

    $content = str_replace($gallery_crumb_hole, $crumb_line, $content);

    return;
  }


  function picview_directorygallery(&$directory, &$gallery, $direction) {
    global $directory_to_gallery, $gallery_to_directory;

    if($direction == $gallery_to_directory) {
      $gallery_parts = explode(":", str_replace(".", "", $gallery));
      $directory = "./";
      foreach($gallery_parts as $gallery_part) {
        if(strlen(trim($gallery_part)))
          $directory .= trim($gallery_part) . "/";
      }
    }

    if($direction == $directory_to_gallery) {
      $directory_parts = explode("/", str_replace(".", "", $directory));
      $gallery = "";
      foreach($directory_parts as $directory_part) {
        if(strlen(trim($directory_part)))
          $gallery .= trim($directory_part) . ":";
      }
    }

    return;
  }


  function picview_displaytemplate($template) {

    $file_contents = "";
    if(!file_exists($template))
      return $file_contents;

    $file_handle = fopen($template, "r");
    while(!feof($file_handle)) {
      $file_contents .= fgets($file_handle, 512);
    }
    fclose($file_handle);

    return $file_contents;
  }


  function picview_getdirectory($directory) {
    global $ignore_entries;
    global $order_ascending;

    $output = array();

    if($dir_handle = @opendir($directory)) {
      while(false !== ($dir_entry = readdir($dir_handle))) {
        $entry_skip = 0;
        foreach($ignore_entries as $ignore_entry) {
          if($entry_skip)
            continue;
          if($dir_entry == $ignore_entry)
            $entry_skip = 1;
        }
        if($entry_skip)
          continue;
        $output[] = $dir_entry;
      }
      closedir($dir_handle);
    }

    if($order_ascending) {
      rsort($output);
    } else {
      sort($output);
    }

    return $output;
  }


  function picview_getentries($directory, $type) {
    global $entry_type_gallery, $entry_type_picture, $entry_type_any;
    global $ignore_entries, $image_extensions;
    global $acceptable_gallery, $directory_to_gallery;
    global $acceptable_file, $image_thumb_label;

    $entries = array();
    $entry_index = 0;

    $dir_array = picview_getdirectory($directory);
    if(is_array($dir_array)) {
      while(false !== ($dir_entry = current($dir_array))) {
        next($dir_array);
        $dir_entry_full = $directory . $dir_entry;
        if(is_dir($directory . $dir_entry)) {
          $regexp_val = '/^[' . $acceptable_gallery . ']+$/';
          if(!preg_match($regexp_val, $dir_entry))
            continue;
          if($type & $entry_type_gallery) {
            $entries[$entry_index]["name"] = $dir_entry;
            $entries[$entry_index]["type"] = $entry_type_gallery;
            picview_directorygallery($dir_entry_full,
              $entries[$entry_index]["target_gallery"], $directory_to_gallery);
            $entry_description = ucwords(str_replace("_", " ", $dir_entry));
            $entries[$entry_index]["description"] = $entry_description;
            $entry_index++;
          }
        } else {
          $regexp_val = '/^[' . $acceptable_file . ']+$/';
          if(!preg_match($regexp_val, $dir_entry))
            continue;
          $entry_skip = 1;
          foreach($image_extensions as $image_extension) {
            if(!$entry_skip)
              continue;
            $extension_len = strlen($image_extension);
            $extension_offset = strlen($dir_entry) - $extension_len;
            if($extension_offset <= 0)
              continue;
            if(substr($dir_entry, $extension_offset, $extension_len)
              == $image_extension) {
              $entry_skip = 0;
              break;
            }
          }
          if($entry_skip)
            continue;
          if($type & $entry_type_picture) {
            $entries[$entry_index]["name"] = $dir_entry;
            $entries[$entry_index]["type"] = $entry_type_picture;
            picview_directorygallery($directory,
              $entries[$entry_index]["target_gallery"], $directory_to_gallery);
            $entries[$entry_index]["target_image"] = $dir_entry;
            $entries[$entry_index]["extension"] = $image_extension;
            $entry_base = substr($dir_entry, 0, $extension_offset);
            $thumb_offset = strlen($entry_base) - strlen($image_thumb_label);
            if(substr($entry_base, $thumb_offset, strlen($image_thumb_label))
              == $image_thumb_label) {
              $entry_base = substr($entry_base, 0, $thumb_offset);
              $entries[$entry_index]["thumb"] = 1;
            } else {
              $entries[$entry_index]["thumb"] = 0;
            }
            $entries[$entry_index]["base"] = $entry_base;
            $entry_description = ucwords(str_replace("_", " ", $entry_base));
            $entries[$entry_index]["description"] = $entry_description;
            $entries[$entry_index]["last_modified"] =
              filemtime($directory . $dir_entry);
            $entry_index++;
          }
        }
      }
    }

    return $entries;
  }


  function picview_orderset(&$entries) {
    global $order_ascending;

    if($order_ascending) {
      rsort($entries);
    } else {
      sort($entries);
    }
    foreach($entries as $entry_key => $entry_value) {
      if(is_array($entry_value))
        picview_orderset($entry_value);
    }
  }


  function picview_displayset($directory, $gallery, $type, $entries, $offset) {
    global $gallery_class, $picture_class;
    global $gallery_labels, $picture_labels;
    global $action_type_null, $action_type_gallery;
    global $action_type_picture, $action_type_thumb_i;
    global $uservar;
    global $thumbs_per_row, $thumb_rows_per_page;
    global $entry_type_picture, $entry_type_gallery;
    global $image_on_page, $gallery_images_linked, $no_empty_tables;
    global $picview_self;

    $gallery_output = "";
    $column_number = 0;
    $row_number = 0;

    if($no_empty_tables) {
      $usable_entries = 0;
      foreach($entries as $entry_index => $entry) {
        if($entry["thumb"])
          continue;
        if($entry["type"] != $type)
          continue;
        $usable_entries++;
      }
      if($usable_entries == 0)
        return $gallery_output;
    }

    if($type & $entry_type_gallery) {
      $table_class = $gallery_class["table"];
      $tr_class    = $gallery_class["tr"];
      $td_class    = $gallery_class["td"];
      $img_class   = $gallery_class["img"];
      $a_class     = $gallery_class["a"];
    } else {
      $table_class = $picture_class["table"];
      $tr_class    = $picture_class["tr"];
      $td_class    = $picture_class["td"];
      $img_class   = $picture_class["img"];
      $a_class     = $picture_class["a"];
    }

    $gallery_output .= "<table class=\"" .
                       htmlspecialchars($table_class) . "\">\n";
    foreach($entries as $entry_index => $entry) {
      if($offset > 0) {
        $offset--;
        continue;
      }
      if($entry["thumb"])
        continue;
      if($entry["type"] != $type)
        continue;
      if($type & $entry_type_gallery) {
        $url = $picview_self . "?";
        if($action_type_gallery != $action_type_null)
          $url .= $uservar["action"] . "=" . 
                  rawurlencode($action_type_gallery) . "&";
        if(strlen($entry["target_gallery"]))
          $url .= $uservar["gallery"] . "=" . 
                  rawurlencode($entry["target_gallery"]);
      } else {
        if($image_on_page) {
          $url = $picview_self . "?";
          if($action_type_picture != $action_type_null)
            $url .= $uservar["action"] . "=" . 
                    rawurlencode($action_type_picture) . "&";
          if(strlen($entry["target_gallery"]))
            $url .= $uservar["gallery"] . "=" . 
                    rawurlencode($entry["target_gallery"]) . "&";
          $url .= $uservar["image"] . "=" . 
                  rawurlencode($entry["base"]);
        } else {
          $url = $directory  . $entry["target_image"];
        }
      }
      $thumb_url = $picview_self . "?";
      if($action_type_thumb_i != $action_type_null)
        $thumb_url .= $uservar["action"] . "=" . 
                      rawurlencode($action_type_thumb_i) . "&";
      if(strlen($entry["target_gallery"]))
        $thumb_url .= $uservar["gallery"] . "=" . 
                      rawurlencode($entry["target_gallery"]) . "&";
      if($type & $entry_type_picture) {
        $thumb_url .= $uservar["image"] . "=" . 
                      rawurlencode($entry["base"]);
      }
      $gallery_description = htmlspecialchars($entry["description"]);
      if($column_number == 0)
        $gallery_output .= "<tr class=\"" .
                           htmlspecialchars($tr_class) . "\">\n";
      $gallery_output .= "  <td class=\"" .
                         htmlspecialchars($td_class) . "\">\n";
      if($gallery_images_linked) {
        $gallery_output .= "    <a href=\"" . $url . "\" " .
          "title=\"" . $gallery_description . "\" " .
          "alt=\"" . $gallery_description . "\" " .
          "class=\"" . htmlspecialchars($a_class) . "\">";
      } else {
        $gallery_output .= "    ";
      }
      $gallery_output .= "<img src=\"" . $thumb_url . "\" " .
        "alt=\"" . $gallery_description . "\" " .
        "class=\"" . htmlspecialchars($img_class) . "\">";
      if($gallery_images_linked)
        $gallery_output .= "</a>";
      $gallery_output .= "<br>\n";
      $gallery_output .= "    <a href=\"" . $url . "\" " .
        "title=\"" . $gallery_description . "\" " .
        "alt=\"" . $gallery_description . "\" " .
        "class=\"" . htmlspecialchars($a_class) . "\">";
      if(($type & $entry_type_gallery && $gallery_labels) ||
         ($type & $entry_type_picture && $picture_labels))
        $gallery_output .= $gallery_description;
      $gallery_output .= "</a>\n";
      $gallery_output .= "  </td>\n";
      $column_number++;
      if($column_number == $thumbs_per_row) {
        $gallery_output .= "</tr>\n";
        $column_number = 0;
        $row_number++;
        if($row_number == $thumbs_rows_per_page)
          break;
      }
    }
    while($column_number != $thumbs_per_row) {
      $gallery_output .= "  <td class=\"" .
                         htmlspecialchars($td_class) . "\"> &nbsp; </td>\n";
      $column_number++;
      if($column_number == $thumbs_per_row)
        $gallery_output .= "</tr>\n";
    }
    $gallery_output .= "</table>\n";

    return $gallery_output;
  }


  function picview_imagefind($directory, $entries, $image, $bethumb) {

    $output = "";

    foreach($entries as $entry_key => $entry_value) {
      if(array_key_exists("base", $entry_value) &&
        array_key_exists("thumb", $entry_value)) {
        if($entry_value["base"] == $image &&
          $entry_value["thumb"] == $bethumb) {
          $output = $entries[$entry_key];
          break;
        }
      }
    }

    return $output;
  }


  function picview_imageget($filepath) {

    $output = array();

    if(!file_exists($filepath))
      return $output;

    $fd = fopen($filepath, "r");
    $image_string = fread($fd, filesize($filepath));
    fclose($fd);

    $image_data = imagecreatefromstring($image_string);
    list($image_width, $image_height) = getimagesize($filepath);

    $output["last_modified"] = filemtime($filepath);
    $output["image_data"] = $image_data;
    $output["width"]  = $image_width;
    $output["height"] = $image_height;
    $output["etag"] = md5($filepath);

    return $output;
  }


  function picview_imageresize($source_object, $x, $y, $max) {
    global $image_thumb_label;

    $thumb_width = $x;
    $thumb_height = $y;
    $thumb_max = $max;

    if($thumb_width == 0 && $thumb_height == 0) {
      if($thumb_max > 0) {
        if($source_object["width"] > $source_object["height"]) {
          $thumb_width = $thumb_max;
        } else {
          $thumb_height = $thumb_max;
        }
      } else {
        return;
      }
    }

    if($thumb_width == 0) {
      $scale_ratio = $source_object["height"] / $thumb_height;
      $thumb_width = $source_object["width"] / $scale_ratio;
    }
    if($thumb_height == 0) {
      $scale_ratio = $source_object["width"] / $thumb_width;
      $thumb_height = $source_object["height"] / $scale_ratio;
    }

    $image_data = imagecreatetruecolor($thumb_width, $thumb_height);
    imagecopyresized($image_data, $source_object["image_data"],
                     0, 0, 0, 0,
                     $thumb_width, $thumb_height,
                     $source_object["width"], $source_object["height"]);

    $output["image_data"] = $image_data;
    $output["width"] = $thumb_width;
    $output["height"] = $thumb_height;
    $output["last_modified"] = $source_object["last_modified"];
    $output["etag"] = md5($source_object["etag"] . $image_thumb_label);

    return $output;
  }


  function picview_textimage($text) {
    global $thumb_error_textless, $thumb_error_transparent;

    $output = array();
    /* TODO: have _textimage support native image (thumb) sizes */
    $image_width = 160;
    $image_height = 100;
    $font = 8;

    if($thumb_error_textless)
      $text = " ";
    $image_data = @imagecreate($image_width, $image_height);
    $back_col = imagecolorallocate($image_data, 255, 255, 255);
    $text_col = imagecolorallocate($image_data, 0, 0, 0);
    if($thumb_error_transparent)
      imagecolortransparent($image_data, $back_col);

    $center_width = round(($image_width / 2) -
      ((imagefontwidth($font) * strlen($text)) / 2));
    $center_height = round(($image_height / 2) -
      (imagefontheight($font) / 2));
    if($center_width < 0)
      $center_width = 0;
    if($center_height < 0)
      $center_height = 0;
    imagestring($image_data, $font,
      $center_width, $center_height, $text, $text_col);

    $output["last_modified"] = time();
    $output["image_data"] = $image_data;
    $output["width"]  = $image_width;
    $output["height"] = $image_height;
    $output["etag"] = md5($text);

    return $output;
  }


  function picview_thumbcreate($directory, $entries, $thumb) {
    global $thumb_width, $thumb_height, $thumb_max;
    global $gallery_thumb, $gallery_image_text;
    global $entry_type_gallery, $entry_type_picture;
    global $gallery_thumb_auto_scale, $picture_thumb_auto_scale;

    $output = array();
    $have_thumb = 0;
    $auto_scale = 1;
    $error_thumb = 0;

    $type = $entry_type_gallery;
    if(strlen(trim($thumb)))
      $type = $entry_type_picture;

    switch($type) {

      case $entry_type_gallery:
        $filename = $directory . $gallery_thumb;
        if(is_file($filename)) {
          $source_object = picview_imageget($filename);
          if(array_key_exists("image_data", $source_object)) {
            $have_thumb = 1;
            $auto_scale = 0;
            if($gallery_thumb_auto_scale)
              $auto_scale = 1;
          } else {
            unset($source_object);
          }
        }
        if(!$have_thumb) {
          $source_object = picview_textimage($gallery_image_text);
          $have_thumb = 1;
          $auto_scale = 0;
          $error_thumb = 1;
        }
        break;

      case $entry_type_picture:
        $image_entry = picview_imagefind($directory, $entries, $thumb, 1);
        if(is_array($image_entry)) {
          if(array_key_exists("thumb", $image_entry)) {
            if($image_entry["thumb"] == 1) {
              $filename = $directory . $image_entry["name"];
              if(file_exists($filename)) {
                $source_object = picview_imageget($filename);
                if(array_key_exists("image_data", $source_object)) {
                  $have_thumb = 1;
                  $auto_scale = 0;
                  if($picture_thumb_auto_scale)
                    $auto_scale = 1;
                } else {
                  unset($source_object);
                }
              }
            }
          }
        }
        if(!$have_thumb) {
          unset($image_entry);
          $image_entry = picview_imagefind($directory, $entries, $thumb, 0);
          if(is_array($image_entry)) {
            if(array_key_exists("name", $image_entry)) {
              $filename = $directory . $image_entry["name"];
              if(file_exists($filename)) {
                $source_object = picview_imageget($filename);
                if(array_key_exists("image_data", $source_object)) {
                  $have_thumb = 1;
                  $auto_scale = 1;
                } else {
                  unset($source_object);
                }
              }
            }
          }
        }
        if(!$have_thumb) {
          $source_object = picview_textimage("Image not found");
          $have_thumb = 1;
          $auto_scale = 0;
          $error_image = 1;
        }
        break;

      default:
        $source_object = picview_textimage("Image not found");
        $have_thumb = 1;
        $auto_scale = 0;
        $error_image = 1;
        break;

    }

    if($auto_scale) {
      $output = picview_imageresize($source_object,
        $thumb_width, $thumb_height, $thumb_max);
      if($source_object["image_data"])
        imagedestroy($source_object["image_data"]);
    } else {
      $output = $source_object;
    }
    unset($source_object);

    return $output;
  }


  function picview_displayimagethru($directory, $entries, $image) {

    $image_entry = picview_imagefind($directory, $entries, $image, 0);
    $image_name = $image_entry["name"];
    if(!strlen($image_name))
      return;
    $filename = $directory . $image_name;

    if(!strlen($filename) || !is_file($filename)) {
      $source_object = picview_textimage("Image not found");
    } else {
      $source_object = picview_imageget($filename);
    }
    picview_displayimage($source_object);
    if($source_object["image_data"])
      imagedestroy($source_object["image_data"]);

    return;
  }


  function picview_displaygallery(&$content, $galleries, $pictures) {
    global $gallery_galleries_hole, $gallery_pictures_hole;

    $content = str_replace($gallery_galleries_hole, $galleries, $content);
    $content = str_replace($gallery_pictures_hole, $pictures, $content);

    return;
  }


  function picview_displayimageref(&$content, $directory, $entries, $image) {
    global $action_type_null, $action_type_picture_i;
    global $picture_image_hole, $picture_description_hole;
    global $uservar;
    global $picture_class, $picture_label;
    global $picview_self;

    $picture_image = "";
    $picture_description = "";

    $image_entry = picview_imagefind($directory, $entries, $image, 0);
    if(is_array($image_entry)) {
      if(array_key_exists("name", $image_entry)) {
        $image_name = $image_entry["name"];
      }
    }

    if(strlen($image_name)) {
      $url = $picview_self . "?";
      if($action_type_picture_i != $action_type_null)
        $url .= $uservar["action"] . "=" . 
                rawurlencode($action_type_picture_i) . "&";
      if(strlen($image_entry["target_gallery"]))
        $url .= $uservar["gallery"] . "=" . 
                rawurlencode($image_entry["target_gallery"]) . "&";
      $url .= $uservar["image"] . "=" . 
              rawurlencode($image_entry["base"]);
      $picture_description = htmlspecialchars($image_entry["description"]);
      $picture_image .= "<img src=\"" . $url . "\" " .
        "alt=\"" . $picture_description . "\" " .
        "class=\"" . htmlspecialchars($picture_class["img"]) . "\">";
    }

    $content = str_replace($picture_image_hole, $picture_image, $content);
    if(!$picture_label)
      $picture_description = "";
    $content = str_replace($picture_description_hole, $picture_description,
      $content);

    return;
  }


  function picview_displayimage($image_object) {
    global $image_cache, $image_cache_age;

    if(!is_array($image_object)) {
      unset($image_object);
      $image_object = picview_textimage("Image not found");
    }
    if(!array_key_exists("image_data", $image_object))
      $image_object = picview_textimage("Image not found");
    $image_data = $image_object["image_data"];
    $modified = $image_object["last_modified"];
    $expires = time() + image_cache_age;
    $etag = $image_object["etag"];

    if($image_cache) {
      header("Expires: " . gmdate("D, d M Y H:i:s", $expires) . " GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s", $modified) . " GMT");
      header("Cache-Control: max-age=" . $image_cache_age . ", public");
      header("Pragma: ");
    } else {
      header("Expires: Mon, 15 Jan 1995 05:00:00 GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-store, no-cache, must-revalidate");
      header("Cache-Control: post-check=0, pre-check=0", false);
      header("Pragma: no-cache");
    }

    ob_start();
    @imagepng($image_data);
    $image_blob = ob_get_contents();
    ob_end_clean();
    if($image_data)
      imagedestroy($image_data);

    header("Content-type: image/png");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . strlen($image_blob));
    header("ETag: " . $etag);
    echo $image_blob;

    return;
  }



  /*
     Main - Input
  */
  $action = picview_getinput($uservar["action"], $input_type_integer);
  if($action < $action_type_gallery || $action > $action_type_picture_i)
    $action = $action_type_gallery;
  $gallery = "";
  if($recursive_galleries)
    $gallery = picview_getinput($uservar["gallery"], $input_type_gallery);
  picview_directorygallery($directory, $gallery, $gallery_to_directory);
  if(!strlen(trim($directory)) || !is_dir(trim($directory))) {
    $gallery = "";
    picview_directorygallery($directory, $gallery, $gallery_to_directory);
  }
  picview_directorygallery($directory, $gallery, $directory_to_gallery);
  $image = picview_getinput($uservar["image"], $input_type_picture);


  /*
     Parse Gallery
  */
  $entries = picview_getentries($directory, $entry_type_any);
  picview_orderset($entries, $entry_type_any);
  picview_gallerycrumbs($gallery, $crumbs);


  /*
     Action
  */
  switch($action) {

    // Display Gallery Page
    case $action_type_gallery:
      $picview_output = picview_displaytemplate($templates["gallery"]);
      $picview_galleries =
        picview_displayset($directory, $gallery,
                           $entry_type_gallery, $entries, $gallery_offset);
      $picview_pictures  =
        picview_displayset($directory, $gallery,
                           $entry_type_picture, $entries, $picture_offset);
      picview_displaycrumbs($picview_output, $crumbs);
      picview_displaygallery($picview_output,
        $picview_galleries, $picview_pictures);
      echo $picview_output;
      break;

    // Display Thumb Image
    case $action_type_thumb_i:
      $picview_output =
        picview_thumbcreate($directory, $entries, $image);
      picview_displayimage($picview_output);
      break;

    // Display Picture Page
    case $action_type_picture:
      $picview_output = picview_displaytemplate($templates["picture"]);
      picview_displaycrumbs($picview_output, $crumbs);
      picview_displayimageref($picview_output, $directory, $entries, $image);
      echo $picview_output;
      break;

    // Display Picture Image
    case $action_type_picture_i:
      picview_displayimagethru($directory, $entries, $image);
      break;

    // Invalid Action
    default:
      break;

  }

  exit;
?>
