<?php
@set_time_limit(300);

$gallery_path "/gallery";
$use_sql false;

$use_imagemagick true;
$main_title "Quick and Dirty Gallery";
$t_prev "Prev";
$t_next "Next";
$t_up "Up";

// max image sizes. 0 means unlimited. not 0 in both dimensions, please.
$thumb_width 0;
$thumb_height 75;
$img_width 640;
$img_height 640;

if (
file_exists("config.php")) {
    include(
"config.php");
}

if (
$use_sql) {
    require(
"mysql-secrets.php");
}

function 
a_href($parts$text) {
    
$parts preg_grep("/./"$parts);
    return 
'<a href="'.join("/"$parts).'.html">'.$text.'</a>';
}

function 
mkdir_p($dir) {
    
$basename dirname($dir);
    if (!
is_dir($basename)) {
        
mkdir_p($basename);
    }
    
mkdir($dir);
}

function 
thumbsize ($src_width$src_height$desired_width$desired_height) {
    if (
$desired_height) {
        
$tmp_width $desired_height $src_width $src_height;
        if (
$desired_width == || $tmp_width <= $desired_width) {
            return array (
$tmp_width$desired_height);
        }
    }
    if (
$desired_width) {
        
$tmp_height $desired_width $src_height $src_width;
        return array (
$desired_width$tmp_height);
    }
    
// should never reach here
    
die("Error calculating size");
}

function 
thumb($path$image$width$height){
    global 
$gallery_path$use_imagemagick;
    
$thumb_dir "thumbs/${width}x${height}/$path";
    
$thumb "$thumb_dir/$image";

    if(!
is_file($thumb) || (filemtime("$path/$image") > filemtime($thumb))){
        if (
$use_imagemagick) {
            
$size getimagesize("$path/$image");
            
$src_width $size[0];
            
$src_height $size[1];
        } else {
            if(
preg_match("/\.png$/i",$image)){
                
$src_img imagecreatefrompng("$path/$image");
            }else{
                
$src_img imagecreatefromjpeg("$path/$image");
            }
            
$src_width imagesx($src_img);
            
$src_height imagesy($src_img);
        }

        list(
$dest_width$dest_height) = thumbsize($src_width$src_height$width$height);
        if (
$src_width <= $dest_width && $src_height <= $dest_height) {
            return 
"$gallery_path/$path/$image";
        }

        if(!
is_dir($thumb_dir)) {
            
mkdir_p($thumb_dir);
        }

        if (
$use_imagemagick) {
            
//echo "convert -resize ${dest_width}x${dest_height} -filter Lanczos '$path/$image' '$thumb'<br />";
            
echo `umask 002; convert -resize ${dest_width}x${dest_height} -filter Lanczos '$path/$image' '$thumb' 2>&1`;
        } else {
            
$dst_img = @imagecreatetruecolor($dest_width,$dest_height);
            
//$dst_img = imagecreate($dest_width,$dest_height);
            
imagecopyresampled($dst_img$src_img0000$dest_width$dest_height$src_width$src_height);
            
//imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height);
            
if(preg_match("/\.png$/i",$image)){
                
imagepng($dst_img,$thumb,100);
            }else{
                
imagejpeg($dst_img,$thumb,100);
            }
            
imagedestroy($src_img);
            
imagedestroy($dst_img);
        }
    }
    return 
"$gallery_path/$thumb";
}

function 
alt($comment){
    return 
htmlentities(preg_replace("/(\015\012)|(\015)|(\012)/"," ",$comment));
}

function 
htmldesc($desc){
    
$desc nl2br(htmlentities($desc));
    
$desc str_replace("&lt;","<",$desc);
    
$desc str_replace("&gt;",">",$desc);
    
$desc str_replace("&quot;",'"',$desc);
    return 
$desc;
}

function 
searchform ($search "") {
    return 
'<form action="'.$PHP_SELF.'">
                <p><input type="text" name="search" value="'
.$search.'" /> <input type="submit" value="Search" /></p>
                </form>'
;
}

function 
search($search) {
    global 
$gallery_path$use_sql$thumb_width$thumb_height;
    if (!
$use_sql) {
        return array(
"Searching disabled""Searching is disabled, because no database is in use");
    }
    
$title "Searching...";
    
$body "";

    
$body .= searchform($search);

    
$result mysql_query("SELECT dir,image,description FROM gallery_desc WHERE dir LIKE '%$search%' OR image LIKE  '%$search%' OR description LIKE '%$search%'");
    if(
$row mysql_fetch_array($result)){
        
$body .= "<p>The following images match your query:</p>\n<p>\n";
        do{
            
$dir $gallery_path.'/'.$row["dir"];
            
$img $row["image"];
            
$alt alt(desc($row["dir"],$row["image"],$row["description"]));
            
$body .= '<a href="'.$gallery_path.'/'.preg_replace(",^./,","",$row["dir"]).'/'.$row["image"].'.html"><img src="'.thumb($dir$img$thumb_width$thumb_height).'" alt="'.$img.'" title="'.$alt.'" /></a>';
            
//$body .= '<p>'.$row["dir"].'<br />'.$row["image"].'</p>';
            
$result2 mysql_query("SELECT distinct image FROM gallery_comment WHERE dir='".$row["dir"]."' AND image='".$row["image"]."'");
            if(
$row2 mysql_fetch_array($result2)){
                
$body .= "*\n";
            }else{
                
$body .= "\n";
            }
        }while(
$row mysql_fetch_array($result));
        
$body .= "</p>\n";
    }else{
        
$body .= "<p>No images found</p>";
    }
    return array(
$title$body);
}

function 
is_gallery_dir ($dir$file) {
    return (
is_dir("$dir/$file") && !preg_match("/^(\.)|(thumbs$)/",$file));
}

function 
is_gallery_pic ($dir$file) {
    return (
preg_match("/\.(jpg|jpeg|png)$/i",$file));
}

function 
make_links ($parent$this_pic$type) {
    global 
$gallery_path$t_prev$t_next$t_up;
        if (
$parent == "") {
            
$parent ".";
        }

        if (
$handle opendir($parent)) {
            while (
false !== ($file readdir($handle))) {
                if (
$type == "dirs" && is_gallery_dir ($parent$file) ||
                    
$type == "files" && is_gallery_pic ($parent$file)) {
                        
$files[] = $file;
                }
            }
        } else {
            echo 
"Unable to open $parent!\n";
        }

        if (
is_array($files)) {
            
sort($files);
            
$pos array_search($this_pic$files);
            if(
$prev $files[$pos 1]){
                
$prevlink a_href(array($gallery_path,$parent,$prev), $t_prev);
            }else{
                
$prevlink =    $t_prev;
            }
            if(
$next $files[$pos 1]){
                
$nextlink a_href(array($gallery_path,$parent,$next), $t_next);
            }else{
                
$nextlink $t_next;
            }
        } else {
            
$prevlink =    $t_prev;
            
$nextlink $t_next;
        }

        if (
$parent == "" || $parent == ".") {
            
$up "$gallery_path/";
        } else {
            
$up "$gallery_path/$parent.html";
        }

        return 
"<p class=\"links\">$prevlink <a href=\"$up\">$t_up</a> $nextlink</p>";
}

function 
read_file ($file) {
    if(
$fd fopen ($file"r")){
        
$data fread($fdfilesize ($file));
    }
    
fclose($fd);
    return 
$data;
}

function 
desc($path,$image,$desc=""){
    if (
$desc) {
        return 
$desc;
    }

    
$descfile "$path/$image.txt";
    if (
is_file($descfile)) {
        
$desc read_file($descfile);
    }

    if (!
$desc) {
        
$desc $image;
    }

    return 
$desc;
}

function 
pretty_name ($dir$file) {
    if (
is_file("$dir/$file.txt")) {
        return 
read_file("$dir/$file.txt");
    }
    return 
str_replace("_"" "$file);
}

function 
show_dir($show) {
    global 
$gallery_path$use_sql$main_title$thumb_width$thumb_height;
    
$title $main_title;
    
$body "";
    
$open ".";
    if (
$show) {
        
$show preg_replace(",/+$,",''$show);
        
$parent dirname($show);
        
$this_dir basename($show);
        
$links make_links ($parent$this_dir"dirs");
        
$open $show;
        
$body .= $links;
    }
    if (
$this_dir) {
        
$title pretty_name($parent$this_dir);
    }
    if (
$handle opendir($open)) {
        while(
false !== ($file readdir($handle))){
            if (
is_gallery_dir($open$file)) {
                
$dirs[] = $file;
            } elseif (
is_gallery_pic($open$file)) {
                
$images[] = $file;
            }
        }
        if (
is_array($dirs)) {
            
sort($dirs);
            
reset($dirs);
            
$body .= "<ul>\n";
            foreach(
$dirs as $dir){
                
$body .= '<li>'.a_href(array($gallery_path,$show,$dir), pretty_name($open$dir))."</li>\n";
            }
            
$body .= "</ul>\n";
        }
        if (
is_array($images)) {
            if (
$use_sql) {
                
$result mysql_query("SELECT distinct image FROM gallery_comment WHERE dir='$open/'");
                while(
$row mysql_fetch_array($result)){
                    
$commented[$row["image"]] = 1;
                }
            }
            
sort($images);
            
reset($images);
            
$body .= "<p>\n";
            foreach(
$images as $img){
                
$thumb thumb($open$img$thumb_width$thumb_height);
                
$alt alt(desc($open,$img,$desc[$img]));
                
$body .= sprintf('<a href="%s" class="thumb"><img src="%s" alt="%s" title="%s" class="thumb" /></a>',
                            
$gallery_path.'/'.$show.'/'.$img.".html"$thumb$img$alt);
                if(
$commented[$img] == 1){
                    
$body .= "*\n";
                }else{
                    
$body .= "\n";
                }
            }
            
$body .= "</p>\n";
        }
    }else{
        
$body .= "<p>ERROR: Could not open directory '$open'</p>";
    }
    if (
$show) {
        
$body .= $links;
    }
    return array(
$title$body);
}

function 
show_file ($show) {
    global 
$gallery_path$img_width$img_height;
    
$title "";
    
$body "";
    
$parent dirname($show);
    
$dir './'.$parent;
    
$image basename($show);
    
$links make_links ($parent$image"files");
    
$desc htmldesc(desc($dir$image));
    
$smaller_img thumb($parent$image640640);
    
$title pretty_name($parent$image);

    
$body .= $links;
    
$body .= sprintf('<p><a href="%s" class="large"><img src="%s" alt="%s" class="large" /></a></p>'."\n<p>%s</p>\n",
                
$gallery_path.'/'.$show$smaller_img$title$desc);
    
$body .= $links;

    
$body .= comments ($dir$image);

    return array(
$title$body);
}

function 
comments ($dir$image) {
    global 
$use_sql;
    if (!
$use_sql) {
        return 
"";
    }
    
$text "";
/*
    $text .= <<EOF;
    <form action="<?php echo $gallery_path?>/comment-submit.php" method="post">
    <table class="addcomment">
        <tr>
            <th colspan="2">Write a comment:</th>
        </tr>
        <tr>
            <td>Nick:</td>
            <td><input type="text" name="nick" size="25" />*</td>
        </tr>
        <tr>
            <td>E-mail:</td>
            <td><input type="text" name="mail" size="25" /></td>
        </tr>
        <tr>
            <td>Webpage:</td>
            <td><input type="text" name="webpage" size="25" /></td>
        </tr>
        <tr>
            <td>Comment:</td>
            <td><textarea name="comment" cols="20" rows="3"></textarea>*</td>
        </tr>
        <tr>
            <td>
                <input type="hidden" name="dir" value="<?php echo $dir?>/" />
                <input type="hidden" name="image" value="<?php echo $image?>" />
                <input type="hidden" name="return" value="<?php echo "$gallery_path/$dir/$image.html"?>" />
            </td>
            <td>
                <input type="submit" value="Add comment" />
            </td>
        </tr>
    </table>
    </form>
EOF
*/
    
$result mysql_query("SELECT nick,mail,webpage,comment,added FROM gallery_comment WHERE dir='$dir/' AND image='$image' ORDER BY id");
    if (
$row mysql_fetch_array($result)) {
        
$text .= "<h2>Comments:</h2>";
        do {
            if (
$row["mail"]) {
                
$row["nick"] = '<a href="mailto:'.$row["mail"].'">'.$row["nick"].'</a>';
            }
            if (
$row["webpage"]) {
                
$row["webpage"] = ' (<a href="'.$row["webpage"].'">'.$row["webpage"].'</a>)';
            }
            
//echo '<p>Written by '.$row["nick"].$row["webpage"].' on '.$row["added"].":<br />\n".$row["comment"]."</p>\n";
            
$text .= '<p>Written by '.$row["nick"].$row["webpage"].":<br />\n".$row["comment"]."</p>\n";
        } while(
$row mysql_fetch_array($result));
    }
    return 
$text;
}

// Prevent people from seeing stuff they're not supposed to see.
if($_REQUEST["show"]){
    
$show $_REQUEST["show"];
}
if(
$show){
    
$show preg_replace(",(^/)|(^./)|(^~)|(\.\./)|(\.\.),","",$show);
}
if(
$_REQUEST["search"]){
    
$search $_REQUEST["search"];
}
if(
$search) {
    list(
$title$body) = search($search);
} elseif(
is_dir($show) || $show == '') {
    list(
$title$body) = show_dir($show);
} elseif(
is_file($show)) {
    list(
$title$body) = show_file($show);
}else{
    
$title "Error";
    
$body "<p>ERROR: File '$show' not found.</p>";
}

include(
"header.php");

echo 
$body;
if (
$use_sql) {
    
searchform();
}

include(
"footer.php");

?>