<?php

include_once "scripts/sb_thumbnails.php";


function album_style($album){
  global $data_directory,$blog_config;

  $stylefile = $data_directory.'/thumbs/'.$album.'.sty';
  if (@file_exists($stylefile)){
    $lines = @file($stylefile);
    if (is_array($lines)){
      if (picture_page_style_exists($lines[0])){
	return $lines[0];
      }
    }
  }
  if (isset($blog_config['blog_album_style'])){
    return $blog_config['blog_album_style'];
  }
  return 'smallbottomleft';
}


function picture_page_style_exists($style){
  return function_exists($style.'_picture_page');
}

function album_is_protected($album){
  global $data_directory;

  if (@file_exists($data_directory.'/thumbs/'.$album.'/.passwd.php')){
    return true;
  }
  return false;
}

function check_album_password($album,$password){
  global $data_directory;
  $passfile=$data_directory.'/thumbs/'.$album.'/.passwd.php';
  if (@file_exists($passfile)){
    require($passfile);
    if (isset($album_password)){
      if (crypt($password,$album_password) === $album_password){
	return true;
      }
      return false;
    }
    return true;
  }
  return true;
}


function album_password_form($album){
  global $lang_string;

  $string = $lang_string[ 'protected_login' ];
  $string = str_replace('%s',$album,$string);
  $html = $string;

  $html .= '<p><form enctype="multipart/form-data" action="gallery.php" 
      method="POST">';
  $html .= '<input type="hidden" name="album" value="'.$album.'">';
  $html .= $lang_string['password'];
  $html .= '<input name="password" size="10" type="password">';
  $html .= '<input name="login" type="submit" value="submit">';
  $html .= '</form></p>';
  return $html;
}



/////////////////////////////////////////////////////////
//
// handling gallery access log files
//
/////////////////////////////////////////////////////////


//---------------------------------------------
// save image access in gallery.log
//---------------------------------------------

function logPicViews($pic){
  $logFile = $GLOBALS['data_directory'] . "/gallery.log";
  if ($fh = fopen($logFile, 'a')){
    fwrite($fh, $pic);
    fclose($fh);
  }
}


//---------------------------------------------
// show the most viewed images (as thumbnails)
//---------------------------------------------

function mostViewed($number){
  global $album_directory;
  $logFile = $GLOBALS['data_directory'] . "/gallery.log";
  $topFile = $GLOBALS['data_directory'] . "/most_viewed.txt";

  if (!file_exists($topFile)){
    makeGalleryStats();
  }
  else{

    @$log_time = filemtime($logFile);
    @$top_time = filemtime($topFile);

    if ($log_time>$top_time) {
      makeGalleryStats();
    }
  }

  $list = "";
  $thumbnails = "";
  if ($fh = fopen($topFile, "r")){
    for ($i = 1; $i <= $number; $i++) {
      $line = fgets($fh, 4096);
      if ($line == FALSE){ break; }
      $line = rtrim($line);
      list($count,$pic)=split("\t",$line);

      $pic = str_replace($album_directory.'/','',$pic);
      $album = dirname($pic);
      $pic = basename($pic);

      $link = 'gallery.php?album='.$album.'&amp;pic='.$pic;
      $list .= '['.$count.']&nbsp;<a href="'.$link.'">'.$album.'/'.$pic.'</a><br />';
      $thumbnails .= thumbnail($album,$pic);
    }
    fclose($fh);
  }
  //  $html = '<table><tr><td>'.$list.'</td>';
  //  $html .= '<td>'.$thumbnails.'</td></tr></table>';
  $html = '<div id="img_float_right">'.$list.'</div>';
  $html .= $thumbnails;
  return $html;
}


//----------------------------------
// create file with access counts
//----------------------------------

function makeGalleryStats(){
  $logFile = $GLOBALS['data_directory'] . "/gallery.log";
  $topFile = $GLOBALS['data_directory'] . "/most_viewed.txt";

  $counts = array();

  if ($out = fopen($topFile, "w")){
    if (file_exists($logFile)){
      if ($in = fopen($logFile, "r")){
	while (!feof($in)) {
	  $line = fgets($in, 4096);
	  $line = rtrim($line);
	  $line = str_replace('/./','/',$line);
	  if ($line != "" && file_exists($line)){
	    $counts[$line]++;
	  }
	}
	fclose($in);
      }
    }
    arsort($counts,SORT_NUMERIC);
    reset($counts);
    while (list($key, $val) = each($counts)) {
      fwrite($out,$val."\t".$key."\n");
    }
    fclose($out);
  }
}







// ------------------------
// photo calendar
// ------------------------
function photo_calendar ( $m, $y, $d , 
			  $showtoday=true, $nextprev=true,$showdays=true) {
  global $lang_string, $user_colors;
  global $album_directory;
		
  if ( !isset( $m ) || $m == 'xx' ) {
    $m = date( 'm' );
  }
  if ( !isset( $y ) || $y == 'xx' ) {
    $y = date( 'y' );
  }
  if ( !isset( $d ) || $d == 'xx' ) {
    $d = date( 'd' );
  }

  $date_string = mktime(0, 0, 0, $m, 1, $y ); //The date string we need for some info... saves space ^_^
  $day_start = date( 'w', $date_string ); //The number of the 1st day of the week
  if ( strftime( '%w', mktime( 0, 0, 0, 1, 1, 2007 ) )!=0 )
    {
      $day_start = ( $day_start + 6 ) % 7;
    }
  //Calculate the previous/next month/year
  if ( $m < 12 ){
    $next_month = $m + 1;
    $next_year = $y + 2000;
  }
  else{
    $next_year = $y + 1;
    $next_month = 1;
  }
  if ( $m > 1 ){
    $previous_month = $m - 1;
    $previous_year = $y;
  }
  else{
    $previous_year = $y - 1;
    $previous_month = 12;
  }

  $prefix = '20';
  if (!file_exists($album_directory.'/'.$prefix.$y)){
      if (file_exists($album_directory.'/'.$y)){
      $prefix = '';
    }
  }

  $year_album = $prefix . $y;
  $month_album = $prefix . $y . '/' . $m;
  $today_album = $prefix . $y . '/' . $m . '/' . $d;

  $next_album = 
    $prefix.sprintf('%02d',$next_year%100).'/'.sprintf('%02d',$next_month);
  $prev_album = 
    $prefix.sprintf('%02d',$previous_year%100).'/'.sprintf('%02d',$previous_month);
  
  $str = '
    <table border="0" cellpadding="0" cellspacing="0" 
           align="center" class="calendar">
    <tr><td align="center">';
  if ($nextprev){
    $str .= '<a href="gallery.php?album='.
      $prev_album.'&amp;' . 
      'y=' . sprintf( '%02d', $previous_year % 100 ) . 
      '&amp;m=' . sprintf( '%02d', $previous_month ) .'">&laquo;</a>';
  }
  $str.= '</td><td align="center" colspan="5"><b>' . 
    '<a href="gallery.php?album='.$month_album.
    '&amp;y=' . sprintf( '%02d', $y % 100 ) . 
    '&amp;m=' . sprintf( '%02d', $m ) .'">' .
    ucwords( strftime( '%B ', $date_string) ) . 
    '</a><a href="gallery.php?album='.$year_album.
    '&amp;y=' . sprintf( '%02d', $y % 100 ) . 
    '&amp;m=' . sprintf( '%02d', $m ) .'">' .
    ucwords( strftime( '%Y', $date_string) ) . 
    '</a></b></td><td align="center">';
  if ($nextprev){
    $str.='<a href="gallery.php?album='.$next_album.'&amp;' . 
      'y=' . sprintf( '%02d', $next_year % 100 ) . 
      '&amp;m=' . sprintf( '%02d', $next_month ) .'">&raquo;</a>';
  }
  $str.= '</td></tr>';


  if ($showdays){
    $str.='<tr>';
    for ( $i=0; $i<7; $i++ ){
      //    if ( $day_start!=0 ){
      $str .= '<td>' . ucwords(strftime('%a',mktime(0,0,0,1,($i+1)%7,1990))) . '</td>';
      //    }
      //    else{
      //  $str .= '<td>' . ucwords( strftime( '%a', mktime(0, 0, 0, 1, ($i+7)%7, 1990 ) ) ) . '</td>';
      //    }
    }
    $str.= '</tr>';
  }

  $str .= '<tr>';
		
  //The empty columns before the 1st day of the week
  for ( $i = 0; $i<$day_start; $i++ )
    {
      $str .= '<td>&nbsp;</td>';
    }
  $current_position = $day_start;
  $total_days_in_month = date( 't', $date_string);
  
  //Loop all the days from the month
  for ( $i = 1; $i<=$total_days_in_month; $i++){
    if ( mktime(0, 0, 0, $m, $i, $y ) == mktime(0, 0, 0 ) ){
      $str = $str . '<td align="center"><u>';
    }
    else{
      $str = $str . '<td align="center">';
    }

    $day_album = 
      $prefix.sprintf('%02d',$y%100).'/'.
      sprintf('%02d',$m).'/'.sprintf('%02d',$i);

    $pics = getPictureList($day_album);
    if (is_array($pics) && count($pics)>0){
      $str .= '<a href="gallery.php?album='.$day_album.
	'&amp;d=' . sprintf( '%02d', $i) . 
	'&amp;m=' . sprintf( '%02d', $m ) . 
	'&amp;y=' . sprintf( '%02d', $y % 100 ) . 
	'" title="' . count($pics) . '">' . $i . '</a>';
    }
    else{
      $str = $str . $i;
    }
    if ( mktime(0, 0, 0, $m, $i, $y ) == mktime(0, 0, 0 ) ){
      $str = $str . '</u></td>';
    }
    else{
      $str = $str . '</td>';
    }
      
    $current_position++;
    
    if ( $current_position == 7 ){
      $str = $str . '</tr><tr>';
      $current_position = 0;
    }
  }
  $end_day = 7-$current_position; //There are
  
  //Fill the last columns
  for ( $i = 0; $i<$end_day; $i++ ){
    $str .= '<td></td>';
  }
  $str .= '</tr>';

  if ($showtoday){
    $str .= '<tr><td colspan="7" align="center">' . '<a href="gallery.php?album='. $today_album . '&amp;'. strftime( 'y=%y&amp;m=%m&amp;d=%d">%x') . '</a></td></tr>';
  }
  $str.= '</table>';
  return( $str );
}






//////////////////////////////////////////////////////////////////
// check if there's a blog entry for a given picture

function pic_entry($album,$pic){
  global $album_directory;
  $img=$album_directory.'/'.$album.'/'.$pic;

  if (file_exists($img.'.url')){
    $lines = file($img.'.url');
    $line = array_pop($lines);
    return explode('|',$line);
  }
  $thumb=getThumbnailURL($album.'/'.$pic);
  if (file_exists($thumb.'.url')){
      $lines = file($thumb.'.url');
      $line = array_pop($lines);
      return explode('|',$line);
  }
  $scaled=getScaledURL($img);
  if (file_exists($scaled.'.url')){
      $lines = file($scaled.'.url');
      $line = array_pop($lines);
      return explode('|',$line);
  }
  return false;
}

function save_pic_entry($img,$y,$m,$entry){
  $linkfile = $img.'.url';
  $str = implode('|',array($y,$m,$entry));
  if ($fh = fopen($linkfile, 'w')){
    if (flock($fh, LOCK_EX)) {
      fwrite($fh, $str);
      flock($fh, LOCK_UN);
    }
    fclose($fh);
  }
}




//////////////////////////////////////////////////////////////////////////




/* BEGIN SECTION:   URL-handling
 *
 *        Functions to make handling of URLs easier.
 */

// setGlobal(): promote a request variable to global scope
// $name: variable name
function setGlobal($name,$option = false) {
    if (isset($_REQUEST[$name])) {
	$GLOBALS[$name] = $_REQUEST[$name];
    } elseif ($option!==false && isset($_REQUEST[$option])) {
	$GLOBALS[$name] = $_REQUEST[$option];
    }
}


// setupStickyURLOptions(): setup sticky options global variable
function setupStickyURLOptions() {
    global $sticky_options;
    $sticky_options_match = '/^(lang|tl|style|debug)$/i';
    $sticky_options = array();
    if (isset($_GET)) {
	foreach($_GET as $option => $value) {
	    if (preg_match($sticky_options_match,$option)) {
		$sticky_options[$option] = $value;
	    }
	}
    }
}


// setStickyOption(): set the value of a sticky option
// $option: option name
// $value: option value
function setStickyOption($option,$value = false) {
    global $sticky_options;
    $sticky_options[$option] = $value;
}


// unsetStickyOption(): clear the value of a sticky option
// $option: option name
function unsetStickyOption($option) {
    global $sticky_options;
    unset($sticky_options[$option]);
}


// makeURL(): properly format a url
// $page: base URL, may be a null string
// $option: [array] of option, keys are option name, values are option values
function makeURL($page,$params = array(),$no_sticky = false) {
    global $sticky_options;
    $url = "$page?";
    $first = true;
    // add all the params, encoded as needed
    foreach($params as $param => $value) {
	$url .= ($first ? "" : "&amp;") . "$param=" . urlencode($value);
	$first = false;
    }
    // add any sticky options
    if (!$no_sticky) {
	foreach($sticky_options as $option => $value) {
	    if (!isset($params[$option])) {
	      $url .= ($first ? "" : "&amp;") . "$option=" . urlencode($value);
	      $first = false;
	    }
	}
    }
    return $url;
}

/* END SECTION:   URL-handling
 */





/* BEGIN SECTION:   File-handling
 *
 *        Functions to work with files and directories
 */

// getPictureList() returns list of all files in a directory
// $album: relative path to album
function getPictureList($album){
    global $album_directory;
    $dir = makeAlbumPath($album);
    if (is_dir($dir)){    
      $list = getFilelist($album);
    }
    else {
      $list = read_virtual_album($album);
    }
    return $list;
}

function makeAlbumPath($album) {
    global $album_directory;
    return $album=="" ? $album_directory : "$album_directory/$album";
}

// getFilelist() returns list of all files (relative paths from $data_directory)in a directory
// $album: relative path to album directory
function getFilelist($album){
    global $pic_extentions, $other_extentions;

    $dir = makeAlbumPath($album);
    $list = array();
    $fd = opendir($dir);
    $i = 0;
    while($file = readdir($fd)){
	if(is_file("$dir/$file") && 
	   (preg_match($pic_extentions,$file) || 
	    preg_match($other_extentions,$file))) {
	    $list[$i] = $file;
	    $i = $i + 1;
	}
    }
    closedir($fd);
    sort($list, SORT_STRING);
    reset($list);
    return $list;
}

/* END SECTION:   File-handling
 */
 
/* BEGIN SECTION:   Server Scaling-functions
 *
 *        Some small functions to do the dirty work...
 */

// validScaledExists(): determins if the picture already has an existing scaled
// $pic: relative path to picture
function validScaledExists($pic){
    $scaled_time = 0;
    $tn_file_name = getScaledURL($pic);
    @$scaled_time = filemtime($tn_file_name);
    @$pic_time = filemtime($pic);
    // compare mod dates of picture and scaled
    // use out-of-date scaleds if GD is not available
    if ($scaled_time!==FALSE && 
	(!$GLOBALS['gd_available'] || $pic_time<=$scaled_time)) {
	$result = true;
    } else {
	$result = false;
    }
    return $result;
}

// getScaledURL($pic): generate proper scaled file path
// $pic: relative path to picture 
function getScaledURL($pic){
  global $pic_extentions;
  $base = preg_replace($pic_extentions,'',$pic);
  $scaled = $GLOBALS['data_directory'] . '/scaled/'. $base . ".jpg";
  if (!file_exists($scaled)){
    $scaled = $GLOBALS['data_directory'] . "/scaled/$pic" . ".jpg";
  }
  return $scaled;
}

/* END SECTION:   Server Scaling
 */
 



/* BEGIN SECTION:   Helper-functions
 *
 *        Some small functions to do the dirty work...
 */

// reverse_strrchr(): returns the characters preceeding the last occurance of the needle
// $haystack: target
// $needle: search string
function reverse_strrchr($haystack, $needle)
{
    $pos = strrpos($haystack, $needle);
    if($pos === false) {
	return $haystack;
    }
    return substr($haystack, 0, $pos + 1);
}


// pre-PHP5 compatibility
if (!function_exists('file_get_contents')) { 
    // file_get_contents(): reads the contents of a file into a string
    // $fielname: path to file
    // $use_include_path: search for relative paths along the include path (default false)
    function file_get_contents($filename, $use_include_path = 0) { 
	$file = @fopen($filename, 'rb', $use_include_path); 
	if ($file) { 
	    if ($fsize = @filesize($filename)) { 
		$data = fread($file, $fsize); 
	    }
	    else { 
		while (!feof($file)) { 
		    $data .= fread($file, 1024); 
		}
	    } 
	    fclose($file); 
	} 
	return $data; 
    } 
}

// d(): outout string if in debug mode
// $s string to output
function d($s) {
    global $debug;
    if ($debug) {
	echo $s . "<br/>\n";
    }
}

// setTextDefault(): 
// $name name of variable to set
// $value value to assign to variable with name $name
function setTextDefault($name,$value) {
    $GLOBALS[$name] = isset($GLOBALS[$name]) ? $GLOBALS[$name] : $value;
}




/* BEGIN SECTION:   compatibility-functions
 *
 *        compatibility for older versions of PHP...
 */
if (!function_exists('file_get_contents'))
{
    function file_get_contents ($filename, $incpath = false, $resource_context = null){
	if ($fh = @fopen($filename, 'rb', $incpath) === false) {
	    trigger_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
	    return false;
	}
	
	clearstatcache();
	if ($fsize = filesize($filename)) {
	    $data = fread($fh, $fsize);
	}
        
	else {
	    while (!feof($fh)) {
		$data .= fread($fh, 8192);
	    }
	}
	fclose($fh);
	return $data;    
    }
}
/* END SECTION:   Helper-functions
 */






/////////////////////////////////////////////////
//
// make a picture page!
//
/////////////////////////////////////////////////


function picture_page($album_directory,$album,$pic) {

  $style = album_style($album);
    //  $style = 'pretty';
  if (isset($_REQUEST['style'])){
    $style = $_REQUEST['style'];
  }

  $valbum = $album;
  $vpic = $pic;
  if (is_virtual_album($album)){
    $liste = getPictureList($album);
    $album = dirname($liste[$pic]);
    $pic = basename($liste[$pic]);
  }
  $img_src = strpos($pic,"/") ? $pic : "$album_directory/$album/$pic";

  /*
  $scaled=getScaledURL($img_src);
  if (file_exists($scaled)){
    $img_src=$scaled;
  }
  */

  if (preg_match($GLOBALS['pic_extentions'],$pic)) {
    $elements = getimagesize($img_src);
    $width = $elements[0];
    $height = $elements[1];
    // new 2005-06-02:
    // log viewed pictures in a file
    logPicViews($img_src."\n");
  }
  else {
    $elements = false;
  }

  // slideshow mode --> use basic picture mode!
  if ($_REQUEST['slideshow']){
    return basic_picture_page($album_directory,$valbum,$vpic,
			       $img_src,$elements);
  }

  if (function_exists($style.'_picture_page')){
    $function = $style.'_picture_page';
    return $function($album_directory,$valbum,$vpic,
		     $img_src,$elements);
  }
  else{
    return pretty_picture_page($album_directory,$valbum,$vpic,
			       $img_src,$elements);
  }
}


function picture_page_styles(){
  $styles = array('simple',
		  'thumbs',
		  'topleft',
		  'topright',
		  'bottomleft',
		  'bottomright',
		  'top',
		  'bottom',
		  'left',
		  'right',
		  'smalltopleft',
		  'smalltopright',
		  'smallbottomleft',
		  'smallbottomright',
		  'smalltop',
		  'smallbottom',
		  'smallleft',
		  'smallright');
  return $styles;
}


//------------------------------------------------------------------------
// simple style (previous & next links)!


function simple_picture_page($album_directory,$album,$pic,$img_src,$elements){
  global $logged_in;
  global $signed_in,$blog_permissions;

  $pichtml = '';

//  if ($logged_in){
  if ($logged_in || ($signed_in && $blog_permissions['send_album'])){
    $pichtml .= email_pic_form($album,$pic);
  }
  if ($logged_in || ($signed_in && $blog_permissions['setup'])){
    $pichtml .= set_album_style_form($album,$pic);
  }

  $pichtml .= picture_description($album_directory,$album,$pic);
  $pichtml .= prev_next_navigation($album_directory,$album,$pic);

  // add a [post] link if logged in
  // --> image is posted as new entry using add_picpost.php
  //     (use scaled version if necessary)
//  if ($logged_in){
  if ($signed_in && $blog_permissions['add']){
    $pichtml .= img_post_button($album,$pic,$img_src);
  }

  $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);

  $picname = ($pos=strrpos($pic,"/")) ? substr($pic,$pos+1) : $pic;
  $pichtml .= '<br />'.$picname;

  return $pichtml;

}

// end simple style
//------------------------------------------------------------------------


//------------------------------------------------------------------------
// basic style (no navigation)


function basic_picture_page($album_directory,$album,$pic,$img_src,$elements){

  $pichtml = '';

  $pichtml .= picture_description($album_directory,$album,$pic);
  $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);

  $picname = ($pos=strrpos($pic,"/")) ? substr($pic,$pos+1) : $pic;
  $pichtml .= '<br />'.$picname;

  return $pichtml;

}

// end basic style
//------------------------------------------------------------------------


//------------------------------------------------------------------------
// previous-next style with thumbnails


function thumbs_picture_page($album_directory,$album,$pic,$img_src,$elements){
  global $logged_in;
  global $signed_in,$blog_permissions;

  $pichtml = '';

//  if ($logged_in){
  if ($logged_in || ($signed_in && $blog_permissions['send_album'])){
    $pichtml .= email_pic_form($album,$pic);
  }
  if ($logged_in || ($signed_in && $blog_permissions['setup'])){
    $pichtml .= set_album_style_form($album,$pic);
  }

  $pichtml .= picture_description($album_directory,$album,$pic);
  $pichtml .= prev_next_navigation($album_directory,$album,$pic,'thumbs');

  // add a [post] link if logged in
  // --> image is posted as new entry using add_picpost.php
  //     (use scaled version if necessary)
//  if ($logged_in){
  if ($signed_in && $blog_permissions['add']){
    $pichtml .= img_post_button($album,$pic,$img_src);
  }

  $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);

  $picname = ($pos=strrpos($pic,"/")) ? substr($pic,$pos+1) : $pic;
  $pichtml .= '<br />'.$picname;

  return $pichtml;

}

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



//------------------------------------------------------------------------
// pretty style


function pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width=null,$thumb_pos='bottomleft'){
  global $logged_in;
  global $signed_in,$blog_permissions;

  $pichtml = '';
  $deschtml = '';

  $picdescr = picture_description($album_directory,$album,$pic);

  if ($logged_in || ($signed_in && $blog_permissions['send_album'])){
    $pichtml .= email_pic_form($album,$pic);
  }
  if ($logged_in || ($signed_in && $blog_permissions['setup'])){
    $pichtml .= set_album_style_form($album,$pic);
    $deschtml = '<div class="picture_description">';
    $deschtml .= pic_description_form($album,$pic,$picdescr);
    $deschtml .= '</div><br />';
  }
  elseif ($picdescr!=''){
    $deschtml = '<div class="picture_description">';
    $deschtml .= $picdescr;
    $deschtml .= '</div><br />';
  }

  // add a [post] link if logged in
  // --> image is posted as new entry using add_picpost.php
  //     (use scaled version if necessary)
//  if ($logged_in){
  if ($signed_in && $blog_permissions['add']){
    $pichtml .= img_post_button($album,$pic,$img_src);
  }

  global $blog_config;
  if ($thumb_width == null){
    $nr_thumbs = floor($blog_config['blog_max_pic_width']/
		       ($blog_config['blog_thumb_width']+5));
      $table_width = $blog_config['blog_thumb_width']+5;
  }
  else{
    // $nr_thumbs = floor($blog_config['blog_max_pic_width']/
    //	       ($thumb_width+5));
    $nr_thumbs = floor($blog_config['blog_max_pic_width']/
		       ($thumb_width*3/2));
    $table_width = $thumb_width+5;
  }

  $pichtml .= prev_next_navigation($album_directory,$album,$pic);
//  $picname = ($pos=strrpos($pic,"/")) ? substr($pic,$pos+1) : $pic;
//  $pichtml .= $picname.'<br />';

  if ($thumb_pos == 'top' || 
      (($thumb_pos == 'topleft' || $thumb_pos == 'topright') && 
       $elements[0]>=$elements[1])){
    $pichtml .= thumbnail_navigation($album_directory,$album,$pic,
				     $nr_thumbs,null,$thumb_width);
    $pichtml .= '<br />'.$deschtml;
    $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);
  }
  elseif ($thumb_pos == 'bottom' ||
	  (($thumb_pos == 'bottomleft' || $thumb_pos == 'bottomright') &&  
	   $elements[0]>=$elements[1])){
    $pichtml .= $deschtml;
    $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);
    $pichtml .= '<br />';
    $pichtml .= thumbnail_navigation($album_directory,$album,$pic,
				     $nr_thumbs,null,$thumb_width);
  }
  elseif ($thumb_pos == 'left' || 
	  (($thumb_pos == 'topleft' || $thumb_pos == 'bottomleft') &&  
	   $elements[0]<$elements[1])){
    $pichtml .= '<table><tr><td align="right" width="';
    $pichtml .= $table_width;
    $pichtml .= '">';
    $pichtml .= thumbnail_navigation($album_directory,$album,$pic,
				     $nr_thumbs,$thumb_width);
    $pichtml .= '</td><td>';
    $pichtml .= $deschtml;
    $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);
    $pichtml .= '</tr></table>';
  }
  else{
    $pichtml .= '<table><tr><td>';
    $pichtml .= $deschtml;
    $pichtml .= picture($album_directory,$album,$pic,$img_src,$elements);
    $pichtml .= '<td align="left" width="';
    $pichtml .= $table_width;
    $pichtml .= '">';
    $pichtml .= thumbnail_navigation($album_directory,$album,$pic,
				     $nr_thumbs,$thumb_width);
    $pichtml .= '</td>';
    $pichtml .= '</tr></table>';
  }

  return $pichtml;

}

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

//------------------------------------------------------------------------
// same as pretty page but small thumbnails (width = 100)


function topleft_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'topleft');
}

function bottomleft_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottomleft');
}

function topright_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'topright');
}

function bottomright_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottomright');
}

function left_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'left');
}

function right_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'right');
}

function top_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'top');
}

function bottom_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottom');
}



function smalltopleft_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=75){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'topleft');
}

function smallbottomleft_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottomleft');
}

function smalltopright_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'topright');
}

function smallbottomright_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottomright');
}





function smallleft_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'left');
}

function smallright_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'right');
}

function smalltop_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'top');
}

function smallbottom_picture_page($album_directory,$album,$pic,$img_src,
				  $elements,$thumb_width=50){
  return pretty_picture_page($album_directory,$album,$pic,$img_src,$elements,
			     $thumb_width,'bottom');
}



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


function album_description($album_directory,$album){
  global $data_directory,$logged_in;

  $html = '';

    if(file_exists($data_directory."/thumbs/".$album."/description.html")){
      //$html =  "<div class='album_description'>\n";
	$html .= implode("\n",file($data_directory."/".$album."/description.html"));
	//$html .=  "</div>\n";
    } 
    elseif(file_exists($data_directory."/thumbs/".$album."/description.txt")){
      //$html =  "<div class='album_description'>\n";
      //$html .= htmlentities(implode("\n",file($data_directory."/thumbs/".$album."/description.txt")));
	$html .= implode("\n",file($data_directory."/thumbs/".$album."/description.txt"));
	//$html .=  "</div>\n";
    } 
    elseif(file_exists($album_directory . "/" . $album . "/description.html")){
      //$html =  "<div class='album_description'>\n";
	$html .= implode("\n",file($album_directory . "/" . $album . "/description.html"));
	//$html .=  "</div>\n";
    } 
    elseif(file_exists($album_directory . "/" . $album . "/description.txt")){
      //$html =  "<div class='album_description'>\n";
      //$html .= htmlentities(implode("\n",file($album_directory . "/" . $album . "/description.txt")));
	$html .= implode("\n",file($album_directory . "/" . $album . "/description.txt"));
	//$html .=  "</div>\n";
    }
 
    return $html;
}

function picture_description($album_directory,$album,$pic){

  global $data_directory;

    $desc = $data_directory.'/thumbs/'.$album.'/'.$pic;

    if(file_exists("$desc.html")) {
      //$pichtml =  "<div class='picture_description'>\n";
	$pichtml .= implode("\n",file("$desc.html"));
	//$pichtml .=  "</div>\n";
	return $pichtml;
    }
    elseif(file_exists("$desc.txt")) {
      //$pichtml =  "<div class='picture_description'>\n";
	$pichtml .=  htmlentities(file_get_contents("$desc.txt"));
	//$pichtml .=  "</div>\n";
	return $pichtml;
    } 

    $desc = $album_directory.'/'.$album.'/'.$pic;

    if(file_exists("$desc.html")) {
      //$pichtml =  "<div class='picture_description'>\n";
	$pichtml .= implode("\n",file("$desc.html"));
	//$pichtml .=  "</div>\n";
	return $pichtml;
    }
    elseif(file_exists("$desc.txt")) {
      //$pichtml =  "<div class='picture_description'>\n";
	$pichtml .=  htmlentities(file_get_contents("$desc.txt"));
	//$pichtml .=  "</div>\n";
	return $pichtml;
    } 

    return '';

}




function picture($album_directory,$album,$pic,$img_src,$elements) {

    global $max_picture_scaling;
    global $lang_string;
    global $blog_config;

    $pichtml='';
    $img_link = $img_src;

    if ($elements===false) {
      if (preg_match('/\.swf$/i',$img_src)) {
	// more about flash player parameters:
	// http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_12701
	// http://www.jeroenwijering.com/?item=embedding_flash
	$pichtml .= '<object>';
	$pichtml .= '<param name="movie" value="'.$img_src.'" />';
	$pichtml .= '<param name="loop" value="false" />';
	$pichtml .= '<param name="quality" value="high" />';
	$pichtml .= '<param name="scale" value="noborder" />';
	$pichtml .= '<embed src="'.$img_src.'" ';
	$pichtml .= 'allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" scale="noborder" loop="false">';
	$pichtml .= '</embed></object>';
      }
      else{
	// non-displayable file types
	d("non-displayable");
	// $img_src = makeThumbnailURL($album,$pic);
	$pichtml .=  "<a href='$img_link' class='picturefooter'>";
	$pichtml .=  "<img class='picture' src='$img_src' alt='$pic'/>";
	$pichtml .= "</a><br/>\n";
      }
    }
    else{
      $width = $elements[0];
      $height = $elements[1];

      if(($width * $height) > ($blog_config["blog_max_pic_width"] * 
			       $blog_config["blog_max_pic_height"] * 
			       $max_picture_scaling)){
	list($new_width,$new_height) = getWidthHeight($width,$height);
	d("Server Scaled ($width,$height) => ($new_width,$new_height)");
	if (validScaledExists($img_src)) {
	  $scaled_url = getScaledURL($img_src);
	} 
	else {
	  $scaled_url = makeURL("scale.php",array("picture"=> $img_src),true);
	}
	$pichtml .=  "<a href='$img_link' class='picturefooter'>";
	$pichtml .=  "<img class='picture' src='$scaled_url' width='$new_width' height='$new_height' alt='$pic'/></a><br/>\n";
      }
      elseif($width > $blog_config["blog_max_pic_width"] || 
	     $height > $blog_config["blog_max_pic_height"]){
	list($new_width,$new_height) = getWidthHeight($width,$height);
	// show picture in new dimensions:
	d("Browser Scaled ($width,$height) => ($new_width,$new_height)");
	$pichtml .=  "<a href='$img_link' class='picturefooter'>";
	$pichtml .=  "<img class='picture' src='$img_src' width='$new_width' height='$new_height' alt='$pic'/></a><br/>\n";
      }
      // not bigger than maximum...
      else {
	// ...just show the picture
	d("Unscaled");
	$pichtml .=  "<img class='picture' src='$img_src' alt='$pic'/><br/>";
      }
    }
    return $pichtml;
}




function prev_next_navigation($album_directory,$album,$pic,$style='default'){
  global $logged_in;
  global $lang_string;

  $liste = getPictureList($album);

  $valbum = $album;
  if (is_virtual_album($album)){
    $virtual = true;
    $actualpicture = $pic;
    $album = dirname($liste[$pic]);
    $pic = basename($liste[$pic]);
  }
  else{
    $virtual = false;
    $actualpicture = 0;
    for($i = 0; $i < count($liste); $i++){
      if($liste[$i] == $pic){
	$actualpicture = $i;
      }
    }
  }

  ///////////////////////////////////////////////
  // navigation
  ///////////////////////////////////////////////

  $pichtml = '';

  $previous = $actualpicture - 1;
  $next = $actualpicture + 1;

  if($virtual){
    $previous_pic = $previous;
  }
  else {
    $previous_pic = $liste[$previous];
  }
  if($virtual){
    $next_pic = $next;
  }
  else {
    $next_pic = $liste[$next];
  }

  if($actualpicture > 0) {
    $previous_url=makeURL("",array("album"=>"$valbum","pic"=>"$previous_pic"));
  }

  if($actualpicture < count($liste)-1){
    $next_url = makeURL("",array("album"=>"$valbum","pic"=>"$next_pic"));
  }

  //----------------------------------------------------------------
  // default navigation ................. show 'previous' and 'next'
      
  global $blog_config;
  //  $pichtml .=  "<table width='85%'><tr class='quickjump'>\n";
  $pichtml .=  "<table width='95%'><tr class='quickjump'>\n";
    
  // link to previous picture
  $pichtml .=  "<td align='left'>";

  // theme image path
  global $blog_theme;
  $img_path = "themes/" . $blog_theme . "/images/";

  if (isset($previous_url)){
    if ($style == 'thumbs'){
      $pichtml.=thumbnail($album,$previous_pic);
    }
    else{
      $pichtml.="<a href='$previous_url'>";
      if (file_exists($img_path.'previous.png')){
	$pichtml.='<img src="'.$img_path.'previous.png" border="0" />';
      } else {
	$pichtml.=$lang_string['previous'];
      } 
      $pichtml.="</a>";
    }
  }
  $pichtml.="</td>\n";

  // link to next picture
  $pichtml .=  "<td align='right'>";
  if (isset($next_url)){
    if ($style == 'thumbs'){
      $pichtml.=thumbnail($album,$next_pic);
    }
    else{
      $pichtml.="<a href='$next_url'>";
      if (file_exists($img_path.'next.png')){
	$pichtml.='<img src="'.$img_path.'next.png" border="0" />';
      } else {
	$pichtml.=$lang_string['next'];
      } 
      $pichtml.="</a>";
    }
  }
  $pichtml.="</td>\n";

  $pichtml .=  "</tr></table>\n";

  return $pichtml;
}


function getPictureIndexNr($album,$pic){
  $liste = getPictureList($album);

  if (is_virtual_album($album)){
    return $pic;
  }
  else{
    for($i = 0; $i < count($liste); $i++){
      if($liste[$i] == $pic){
	return $i;
      }
    }
  }
  return 0;
}


function thumbnail_navigation($album_directory,$album,$pic,$nr_thumbs=4,
			      $thumb_width=null,$thumb_height=null){
  global $logged_in;
  global $lang_string;

  $liste = getPictureList($album);

  $valbum = $album;
  if (is_virtual_album($album)){
    $virtual = true;
    $actualpicture = $pic;
    $album = dirname($liste[$pic]);
    $pic = basename($liste[$pic]);
  }
  else{
    $virtual = false;
    $actualpicture = 0;
    for($i = 0; $i < count($liste); $i++){
      if($liste[$i] == $pic){
	$actualpicture = $i;
      }
    }
  }

  $pichtml = '';

  $start = $actualpicture - floor($nr_thumbs/2) + 1;
  if ($start < 0){$start = 0;}
  $end = $start + $nr_thumbs - 1;
  if ($nr_thumbs<3){$end = $start+2;}
  if($end > count($liste)-1){
    $end = count($liste)-1;
    $start = $end - $nr_thumbs + 1;
    if ($start < 0){$start = 0;}
  }

  for ($i=$start;$i<=$end;$i++){
    if($virtual){
      $album = dirname($liste[$i]);
      $pic = basename($liste[$i]);
      $link = makeURL("",array("album"=>$valbum,"pic"=>$i));
    }
    else{
	$pic=$liste[$i];
	$link = makeURL("",array("album"=>$album,"pic"=>$pic));
    }
    if ($i != $actualpicture){
      $pichtml .= thumbnail($album,$pic,$link,//null,null,
			    $thumb_width,$thumb_height)."\n";
    }
    elseif($nr_thumbs>2){
      $pichtml .= '<span class="selected">';
      $pichtml .= thumbnail($album,$pic,$link,//null,null,
			    $thumb_width,$thumb_height);
      $pichtml .= "</span>\n";
    }
  }
  return $pichtml;
}












function getWidthHeight($width,$height) {
  global $blog_config;
  $max_picture_width = $blog_config['blog_max_pic_width'];
  $max_picture_height = $blog_config['blog_max_pic_height'];
	// global $max_picture_width,$max_picture_height;
	if (($width / $height) > ($max_picture_width / $max_picture_height)){
		$new_width = $max_picture_width;
		$new_height = ($max_picture_width / $width) * $height;
	}
	else {
		$new_height = $max_picture_height;
		$new_width = ($max_picture_height / $height) * $width;
	}
	return array(round($new_width),round($new_height));
}


/////////////////////////////////////////////////
// end of picture page!
/////////////////////////////////////////////////



function subalbum($album_directory,$album){

    include "scripts/sb_gallery_config.php";

    if ($album == '.'){
      $album_path = '';
      $root_dir = $album_directory;
    }
    else{
      $album_path = $album.'/';
      $root_dir = $album_directory.'/'.$album;
    }
    if (!is_dir($root_dir)){return '';}

    $subdir = array();
    $fd = opendir($root_dir);
    $i = 0;
    while($file = readdir($fd)){
	if($file != "." && $file != ".." && 
	   is_dir("$root_dir/$file") && ($file != 'CVS')) {
	    $subdir[$i] = $file;
	    $i = $i + 1;
	}
    }
    closedir($fd);
    sort($subdir, SORT_STRING);
    reset($subdir);


    // $html = '<table width="100%"><tr><td>';
    $html = '<div align="left"><table>';

    for ($i = 0; $i < count($subdir); $i++){

      $dir = $root_dir.'/'.$subdir[$i];

      global $logged_in;
      if (!album_is_protected($album_path.$subdir[$i]) || $logged_in){
	if ($fd = opendir($dir)){
	  while($file = readdir($fd)){
	    if (is_file("$dir/$file") && preg_match($pic_extentions,$file)){
	      $img = $file;
	      break;
	    }
	  }
	  closedir($fd);
	}
      }


      $link='?album='.$album_path.$subdir[$i].'&amp;page=1';
      $html .= '<tr><td align="right">';
      $html .= '<a href="'.$link.'">';
      $html .= $subdir[$i].'</a>';

      if (isset($img) && file_exists($dir.'/'.$img)){

	//$html .= '<tr><td align="right">';

	$html .= '<br /><a href="'.$link.'">';
	if (validThumbnailExists("$album_path$subdir[$i]/$img")) {
	  $html .=  "<img border='0' class='thumbnail' src='" . 
	    getThumbnailURL("$album_path$subdir[$i]/$img") . "'";
	} else {
	  $tn_url = makeURL("thumb.php",
			    array("picture"=> "$album_path$subdir[$i]/$img"),
			    true);
	  $html .=  "<img border='0' class='thumbnail' src='$tn_url'";
	}

	$html .= ' alt="'.$img.'" /></a></td>';
      }

      $html .= '<td valign="top">';
      $html .= "<div class='album_description'>";
      $html .= album_description($album_directory,$album_path.$subdir[$i]);
      $html .= '</div></td></tr>'."\n";


      // this is too much ...
      /*
      else{
	$html.=subalbum($album_directory,$album.'/'.$subdir[$i]);
      }
      */
    }
    $html .= '</table></div>';

/*    $html .= '</td><td valign="top">';
    $html .= mostViewed(10);
    $html .= '</td></tr></table>'; */

    return $html;
}
 


function virtual_album_file($album){
  global $album_directory;
  // global $data_directory;
  return $album_directory.'/'.$album.'.album';
}


function open_virtual_album($album){
  $_SESSION['valbum'] = $album;
}


function close_virtual_album(){
  unset($_SESSION['valbum']);
}

function read_virtual_album($album){
  $album_file = virtual_album_file($album);
  $pics=array();
  if (file_exists($album_file)){
    $pics = file($album_file);
    $pics = array_map('rtrim',$pics);
  }
  return $pics;
}


function is_virtual_album_file($file){
  $parts = explode('.',$file);
  if (array_pop($parts) == 'album'){
    return(implode('.',$parts));
  }
  return false;
}

function is_virtual_album($album){
  global $album_directory;
  if (file_exists($album_directory.'/'.$album.'.album')){
    return true;
  }
  return false;
}





/////////////////////////////////////////////////
// thumbnail functions
/////////////////////////////////////////////////


// show a thumbail of an image from a given album


function thumbnail($album,$pic,$link=null,$width=null,$height=null,
		   $long=null,$short=null){
  $img = $album.'/'.$pic;
  if ($link == null){
      $link = makeURL("",array("album"=>$album,"pic"=>$pic));
  }
  //$link='?album='.$album.'&amp;pic='.$pic;
  $html = '<a href="'.$link.'">';
  if (validThumbnailExists($img)) {
      $img = getThumbnailURL($img);
      $html .=  "<img border='0' class='thumbnail' src='" . $img . "'";
  } else {
    $tn_url = makeURL("thumb.php",
		      array("picture"=> $img),true);
    $html .=  "<img border='0' class='thumbnail' src='$tn_url'";
  }

  if ($short != null ){
      $elements = @getimagesize($img);
      if (is_array($elements)){
	$w = $elements[0];
	$h = $elements[1];
	if ($w>$h){$height = $short;}
	else{$width = $short;}
      }
  }
  if ($long != null ){
      $elements = @getimagesize($img);
      if (is_array($elements)){
	$w = $elements[0];
	$h = $elements[1];
	if ($w>$h){$width = $long;}
	else{$height = $long;}
      }
  }
  if ($width != null){
    $html .= ' width="'.$width.'"';
  }
  if ($height != null){
    $html .= ' height="'.$height.'"';
  }
  $html .= ' alt="'.$img.'"/></a>';
  return $html;
}


/////////////////////////////////////////////////
// make thumbnail page (without description/names)
/////////////////////////////////////////////////

function thumbnails($album_directory,$album,$page){

  global $logged_in;
  global $signed_in,$blog_permissions;
  global $lang_string;
  global $blog_config;

    include "scripts/sb_gallery_config.php";

    if ($album == ''){$album='.';}

    $album_description = album_description($album_directory,$album);


    if ($blog_permissions['setup']){
      $thumbhtml = '<form method="post">';
      $thumbhtml .= '<input type="hidden" name="album" value="'.$album;
      $thumbhtml .= '" />';
      global $theme_vars;
      $thumbhtml .= $lang_string['album_description'].'<br />';
      $thumbhtml .= '<textarea style="width: '.$theme_vars['max_image_width'];
      $thumbhtml .= 'px;" name="description" rows="2">';
      $thumbhtml .= $album_description;
      $thumbhtml .= '</textarea>';
      $thumbhtml .= '<input type="submit" name="change" value="';
      $thumbhtml .= $lang_string['sb_edit'];
      $thumbhtml .= '" />';
      $thumbhtml .= '</form>';
    }
    else{
    $thumbhtml=
      "<div class='album_description'>".
      $album_description.      
      "</div>";
    }

    $page = $page=="" ? "1" : $page;

    $liste = getPictureList($album);
 
    if (!count($liste)){
      return  subalbum($album_directory,$album);
    }


    /*
    if ($blog_permissions['setup']){
      sb_language( 'add' );
      global $temp_text;
      $temp_text = $thumbhtml;
      include_once('scripts/sb_blogeditor.php');
      $thumbhtml = editor_description($album);
    }
    */
    


//    if ($logged_in){
    if ($logged_in || ($signed_in && $blog_permissions['send_album'])){
      $thumbhtml.='<hr>';
      $thumbhtml.=email_pic_form($album,null);
    }

    // write quickjump-bar:
    // calculate number of pages needed:


    $number_of_pages = 
      floor((count($liste)-0.5) / $blog_config['blog_thumbs_per_page'])+1;

    /*
    if((floor(count($liste) / ($rows_per_page * $pics_per_row))) == 
       (count($liste) / ($rows_per_page * $pics_per_row))){
	$number_of_pages = 
	    (floor(count($liste) / ($rows_per_page * $pics_per_row)));
    }
    else{
	$number_of_pages = 
	    (floor(count($liste) / ($rows_per_page * $pics_per_row)) + 1);
    }
    */

    if ($number_of_pages > 1){
	// begin quickjump-bar
	$thumbhtml .=  "<table width='85%'><tr class='quickjump'>\n";
	if($page!="all" && $page > 1){
	    $p = $page - 1;
	    $url = makeURL("",array("album"=>"$album","page"=>"$p"));
	    $thumbhtml .= 
		"<td><a href='$url'>".$lang_string['previous']."</a></td>\n";
	}
	else {
	    $thumbhtml .=  "<td>".$lang_string['previous']."</td>\n";
	}
	//write pages
	for($a = 1; $a <= $number_of_pages; $a++){
	    $url = makeURL("",array("album"=>"$album","page"=>"$a"));
	    $thumbhtml .=  "<td><a href='$url'>$a</a></td>\n";
	}
	$thumbhtml .=  "\n";
	// show 'all' button
	if ($page!="all") {
	    $url = makeURL("",array("album"=>"$album","page"=>"all"));
	    $thumbhtml .=  "<td><a href='$url'>".$lang_string['show_all']."</a></td>\n";
	}
	// 'end' quickjump-bar
	if($page!="all" && $page < $number_of_pages){
	    $p = $page + 1;
	    $url = makeURL("",array("album"=>"$album","page"=>"$p"));
	    $thumbhtml .= "<td><a href='$url'>".$lang_string['next']."</a></td>\n";
	}
	else{
	    $thumbhtml .=  "<td>".$lang_string['next']."</td>\n";
	}
	$thumbhtml .=  "</tr></table>\n";
    }

    //write the actual thumbnails
    $offset= $page!="all" ? (($blog_config['blog_thumbs_per_page'])*($page-1)) : 0;
    // $offset= $page!="all" ? (($rows_per_page*$pics_per_row)*($page-1)) : 0;
    global $thumb_width;
    $index = $offset + $i;
    $max = count($liste);

    if (($page!="all") && ($max > $index + ($blog_config['blog_thumbs_per_page']))){
	$max = $index + $blog_config['blog_thumbs_per_page'];
    }
/*
    if (($page!="all") && ($max > $index + ($rows_per_page * $pics_per_row))){
	$max = $index + ($rows_per_page * $pics_per_row);
    }
*/
    $virtual = false;
    if (is_virtual_album($album)){
      $virtual = true;
      $valbum = $album;
    }

    for ($i=$index;$i<$max;$i++){

      if ($virtual){
	$album = dirname($liste[$i]);
	$liste[$i] = basename($liste[$i]);
      }

	// link url for picture page or direct link if not a picture
	if (preg_match($pic_extentions,$liste[$i])  ||
	    preg_match('/\.swf$/i',$liste[$i])) {

	    if (isset($_SESSION['valbum']) && 
		$signed_in && $blog_permissions['edit_album']){
//  	    if ($logged_in && isset($_SESSION['valbum'])){
		if ($_SESSION['valbum'] == $valbum){
		    $url=makeURL("",array("album"=>"$valbum",
					  "del"=>$album."/".$liste[$i],
					  "idx" => "$i",
					  "page" => "$page"));
		}
		else{
		    $url=makeURL("",array("album"=>"$album",
					  "add"=>"$liste[$i]",
					  "page" => "$page"));
		}
	    }
	    elseif ($virtual){
		$url=makeURL("",array("album"=>"$valbum","pic"=>"$i"));
	    }
	    else{
		$url=makeURL("",array("album"=>"$album","pic"=>"$liste[$i]"));
	    }
	} else {
	    $url = getPictureURL($album,$liste[$i]);
	}
	$thumbhtml .=  "<a href='$url'>";
	if (validThumbnailExists("$album/${liste[$i]}")) {
	    $thumbhtml .=  "<img class='thumbnail' src='" . 
		getThumbnailURL("$album/${liste[$i]}") . "'";
	} else {
	    $tn_url = makeURL("thumb.php",array("picture"=> "$album/${liste[$i]}"),true);
	    $thumbhtml .=  "<img class='thumbnail' src='$tn_url'";
	}

	// Check if there is a description and show it in alt
	if(file_exists("$album_directory/$album/$liste[$i].txt")){
	    $desc = file_get_contents("$album_directory/$album/${liste[$i]}.txt");
	    $thumbhtml .= ' alt="'.$desc.'"';
	}
	else{
	    $picname = $liste[$i];
	    $picname = ($pos = strrpos($picname,"/")) ? substr($picname,$pos+1) : $picname;
	    $thumbhtml .= ' alt="'.$picname.'"';
	}

	if ($_SESSION['THUMB_SIZE'] === 'small'){
	  $width = $blog_config['blog_thumb_height']/3;
	  $thumbhtml.=' height="'.$width.'"';
	}
	elseif ($_SESSION['THUMB_SIZE'] === 'medium'){
	  $width = $blog_config['blog_thumb_height']/3*2;
	  $thumbhtml.=' height="'.$width.'"';
	}
	  
	$thumbhtml .=  " /></a>\n";
    }
    return $thumbhtml;
}


/////////////////////////////////////////////////
/////////////////////////////////////////////////


// getPictureURL($pic): generate proper picture relative URL
// $album: album path
// $pic: picture name
function getPictureURL($album,$pic) {
    include "scripts/sb_gallery_config.php";
    if (strpos($pic,"/")) {
	return $album_directory.'/'.$pic;
    } else {
	return $album_directory.'/'.$album.'/'.$pic;
    }
}


function getPicture($album,$pic){

  if (is_virtual_album($album)){
    $liste = getPictureList($album);
    return getPictureURL($album,$liste[$pic]);
  }
  return getPictureURL($album,$pic);
}


function listdirold($root,$link,$maxdepth){
  $dir='';
  $level=0;
  return traversedir($root,$link,$dir,$level,$maxdepth);
}

function traversedir($root,$link,$dir,$level,$maxdepth){
  if (($maxdepth>0) && ($level>=$maxdepth)){return '';}
  $html='';
  $thisdir=$root;
  if ($dir != ''){$thisdir.='/'.$dir;}
  if (is_dir($thisdir)){
	$handle=opendir($thisdir);
	while ($file = readdir($handle)) {
	    if (preg_match('/^\./',$file)) continue;
	    if ($file == 'CVS') continue;
	    if(is_dir($thisdir.'/'.$file)) {
		for ($i=0;$i<=$level;$i++){$html .= '&nbsp;&nbsp;&nbsp;';}
		if ($dir == '') $album=$file;
		else $album=$dir.'/'.$file;
		$html .= "<a href='$link$album'>$file</a><br />\n";
		$html .= traversedir($root,$link,$album,$level+1,$maxdepth);
	    }
	}
    }
    return $html;
}

if (!function_exists('http_build_query')) {
   function http_build_query($formdata, $numeric_prefix = "")
   {
       $arr = array();
       foreach ($formdata as $key => $val)
         $arr[] = urlencode($numeric_prefix.$key)."=".urlencode($val);
       return implode($arr, "&");
   }
}



/////////////////////////////////////////////////////////////////




function listdir($root,$link,$maxdepth,$reverse=false,$dates=true){
  return listdir_alphabetic($root,$link,$maxdepth,$reverse,$dates);
  //return listdir_recent($root,$link,10,$maxdepth);
}


function listdir_recent($root,$link,$max,$maxdepth){

  getsubdir($root,$dir,$subdirs,$level,$maxdepth);
  if (!is_array($subdirs)){return '';}
  arsort($subdirs,SORT_NUMERIC);
  $html = '';
  $count = 0;
  foreach($subdirs as $subdir => $mtime) {
    $count++;
    $html .= "<a href='$link$subdir'>$subdir</a><br />\n";
    if ($count>$max){return $html;}
  }
  return $html;
}


function listdir_alphabetic($root,$link,$maxdepth,$reverse=false,$dates=false){

  getsubdir($root,$dir,$subdirs,$level,$maxdepth);
  if (!is_array($subdirs)){return '';}
  if ($reverse){
    krsort($subdirs,SORT_STRING);
  } else {
    ksort($subdirs,SORT_STRING);
  }
  $html = '';
  $count=0;
  // while (list($subdir, $mtime) = each($subdirs)) {
  foreach($subdirs as $subdir => $mtime) {

    $dirs = explode('/',$subdir);
    foreach ($dirs as $dir){$html .= '&nbsp;&nbsp;';}
    if ($dates){
      $name = replace_month($dirs);
    }
    else{
      $name = array_pop($dirs);
    }

    $html .= "<a href='$link$subdir'>$name</a><br />\n";
  }
  return $html;
}

function replace_month($dirs){
  $m = array_pop($dirs);
  if (count($dirs)==1){
    if (strlen($m)==2){
      if (is_numeric($m)){
	if ($m>0 && $m<13){
	  global $lang_string;
	  return ucwords($lang_string['sb_months'][$m-1]);
	}
      }
    }
  }
  return $m;
}


 function getsubdir($root,$dir,&$subdirs,$level,$maxdepth){

   if ((!isset($_REQUEST["album"])) || 
       (substr($_REQUEST["album"],0,strlen($dir)) != $dir)){
     if (($maxdepth>0) && ($level>=$maxdepth)){return '';}
   }

    $thisdir=$root;
    if ($dir != ''){$thisdir.='/'.$dir;}
    if (is_dir($thisdir)){
        $handle=opendir($thisdir);
        while ($file = readdir($handle)) {
            if (preg_match('/^\./',$file)) continue;
            if ($file == 'CVS') continue;
            if(is_dir($thisdir.'/'.$file)) {
                if ($dir == '') $album=$file;
                else $album=$dir.'/'.$file;
                $subdirs[$album]=filemtime($thisdir.'/'.$file);
                getsubdir($root,$album,$subdirs,$level+1,$maxdepth);
            }
        }
    }
}



?>
