<?php

require_once '../app.inc.php';
require_once '../appmenu.inc.php';
require_once 'album.inc.php';

$album = get('album');
$image = get('image');
$thumb = get('thumb');

// Validation
if (
  ($image || $thumb) && !$album ||	// Image or thumbnail but no album
  $image && preg_match('/\\//', $image) ||	// Image mustn't contain '/'
  $thumb && preg_match('/\\//', $thumb) ||	// Thumbnail neither
  !album_allowed($album)		// Security restrictions
) {
  header('Location: /album/');		// Show the root album menu
  exit;
}
$album = sanitize($album);

$title = "Album";

// Check what arguments were passed

if (array_key_exists('random_thumb', $_GET)) {	// Display a random thumbnail
  echo random_thumb('.');
  exit();
} elseif (array_key_exists('random', $_GET))	// Display a random image
  random_image($album, $image);

$trail = '';
if ($image) {		// Display an image
  $file = "$album/$image";
  $info['alt'] = "$image in " . last_album($album);
  // pass URI + &exif=1 to force EXIF dump
  $info['exif'] = array_key_exists('exif', $_GET);
  image_info($file, $info);	// Read .info file
  $title .= $NAV_SEP_HIER . (array_key_exists('title', $info) ? $info['title'] : $image);
  $trail = breadcrumbs($file);
} elseif ($thumb) {	// Display a thumbnail
  $tn = "$album/tn_$image";
  if (is_readable($tn)) {
    header("Content-Type: " . image_type_to_mime_type(exif_imagetype($tn)));
    echo file_get_contents($tn);
  } else if (($thumb = exif_thumbnail("$album/$thumb", $x, $y, $type)) !== false) {
    header("Content-Type: " . image_type_to_mime_type($type));
    echo $thumb;
  }
  exit();
} elseif ($album) {	// Display an album menu
  $title .= $NAV_SEP_HIER . basename($album);
  $trail = breadcrumbs($album);
} else			// Display the root album menu
  $album = '.';

// remove HTML tags in the title
$title = preg_replace('/<[^>]+>/', '', $title);

// Create the application object (finally...) and display the page header
$app = new Application($title, $menu, $trail);
$app->sidebar = false;		// Suppress the sidebar, it breaks the layout
$app->header();

// Read the album directory to build the navigation links
// or the album overview
$subalbums = array();
$images = array();
$others = array();
image_dir($album, $subalbums, $images, $others);

// Output the image or the album overview
if ($image) {
  // Output the navigation bar
  if ($nav = image_nav($images, $album, $image))
    echo "\n<div class=\"nav\">\n$nav\n</div>\n\n";
  album_image($file, $info);
} else {
  album_thumbs($album, $subalbums, $images, $others);
  // In the root album, display a random image
  if ($album == '.') {
    random($album, $image);
    $info = array('alt' => '', 'size' => '', 'descr' => '');
    $info['subtitle'] = 'Zufallsbild: ' .
      album_link($album, $album) . ' / ' .
      image_text_link($image, $album, $image);
    $info['noexif'] = 1;	// Suppress EXIF infos
    album_image("$album/$image", $info);
  }
}

$app->footer();
?>