<?php
    
/*
    autogallery.php - Generate a live web gallery (including thumbnails) for an
        arbitrarily complex directory tree of images.

    Copyright (C) 2001-2003, Edward Hennis <eah+autogallery@vaxer.net>

    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; either version 2 of the License, or (at
    your option) any later version.

    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
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    The full GPL is available at the end of this file in the function
        ShowLicense()

    Requirements:
    - Your web server must be able to process trailing path information
    For apache, you'll need to add something like this block to httpd.conf
    > # AcceptPathInfo
    > # This directive controls whether requests that contain trailing
    > # pathname information that follows an actual filename (or
    > # non-existent file in an existing directory) will be accepted
    > # or rejected. The trailing pathname information can be made
    > # available to scripts in the PATH_INFO environment variable.
    > #  http://httpd.apache.org/docs-2.0/mod/core.html#acceptpathinfo
    > AcceptPathInfo on

    Version History:
    - 1.2 - 12/30/2003 - Index mpeg videos.
    - 1.1 - 9/9/2003  - Integrated FindTarget function into BuildAllFiles
                function.  No longer need to build entire file tree, just
                the tree along the path to our "target".  We should be able
                to scale real well now.
    - 1.0 - 8/18/2003 - First version with any semblance of documentation.

    Known issues:
    - None at the moment

    Todo:
    - Switch from using URL params to Path_info params
    - Index other files (videos)
    - Choice on sort order
    - Write some frelling usage docs
    - Cache thumbnails in a directory that the apache user can write
    - Cache thumbnails in a MySQL table

    $Header: /home/eah/.CVSROOT/gallery/gallery.php,v 1.15 2007-07-07 00:52:29 eah Exp $
    */
    
if (isset($gallery_has_started)
        && 
$gallery_has_started) {
        return 
FALSE;
    }
    
$gallery_has_started 1;

    
// image files are big
    
ini_set"memory_limit""64M" );

    @include_once(
"/var/www/functions.inc.php");

    
define("DEBUG"false);
    
define("IMAGEDEBUG"false);
    if (
DEBUG)
    {
        
ini_set"display_errors""On" );
        
ini_set"log_errors""Off" );
        print 
"<h1>DEBUG!</h1>";
    }
    else
    {
        
ini_set"error_reporting"ini_get"error_reporting" ) & ~E_NOTICE );
    }
    if( !isset( 
$_SERVER) )
    {
        if( 
DEBUG ) print "<h2>Old version: Superglobals not available. Using references.</h2>\n";
        
$_SERVER = &$HTTP_SERVER_VARS;
        
$_REQUEST = &$HTTP_REQUEST_VARS;
        
$_GET = &$HTTP_GET_VARS;
        
$_POST = &$HTTP_POST_VARS;
        
$_SESSION = &$HTTP_SESSION_VARS;
        
$_ENV = &$HTTP_ENV_VARS;
        
$_COOKIE = &$HTTP_COOKIE_VARS;
        
$_FILES = &$HTTP_POST_FILES;
    }

    if (isset(
$_GET["gimmesource"])) {
        
highlight_file(__FILE__);
        return;
    } elseif (isset(
$_GET["showlicense"])) {
        return 
ShowLicense();
    }

    if (!
extension_loaded('gd')) {
        if (
DEBUG) print "Trying to load gd extensions<br>\n";
        @
dl('gd.so');
    }
    if (!
extension_loaded('exif')) {
        if (
DEBUG) print "Trying to load exif extensions<br>\n";
        @
dl('exif.so');
    }

    
// options and parameters
    
$counter 0;
    
$defaultlimit 4;
    
$thumb "thumb_";
    
$thumblen strlen($thumb);
    
$thumbextregex "/.(thm)$/";
    
$thumbparam "thumb";
    
$videothumbparam "videothumb";
    
$scaleparam "scale";
    
$qualparam "quality";
    
$param "index";
    
$target stripslashesarray_key_exists$param$_GET ) ? $_GET[$param] : '' );
    if (
DEBUG) print "Target is " $target "<br>";

    
$enable_exif function_exists("read_exif_data");
    if (
DEBUG && !$enable_exif) {
        print 
"can't parse exif data\n";
    }

    
# Build a simple form out of this and submit it to
    #  $MYSELF
    
$scalearray = array(
        array( 
"width" => 100"height" => 100 ),
        array( 
"width" => 320"height" => 240 ),
        array( 
"width" => 640"height" => 480 ),
        array( 
"width" => 800"height" => 600 ),
        array( 
"width" => 1280"height" => 1024 ),
        array( 
"width" => 2048"height" => 1536 ),
        array( 
"width" => 2560"height" => 1920 )
    );
    
$fullsizelabel "Full Size";
    
$defaultscale "";
    
$qualarray = array(
        array( 
"value" => 10"label" => "Utter crap" ),
        array( 
"value" => 70"label" => "Low Quality (Faster)" ),
        array( 
"value" => 90"label" => "High Quality" ),
    );
    
$highqualitylabel "Original Quality (Slower)";
    
$defaultqual "";

    
# The various handlers for each image type keyed on the
    # return value from GetImageSize()
    
$handlers = array(
        
=> array(
            
// GIF
            
"load" => "ImageCreateFromGIF",
            
"show" => "ImageGIF",
            
"mime" => "image/gif",
        ),
        
=> array(
            
// JPG
            
"load" => "ImageCreateFromJPEG",
            
"show" => "ImageJPEG",
            
"mime" => "image/jpeg",
        ),
        
=> array(
            
// PNG
            
"load" => "ImageCreateFromPNG",
            
"show" => "ImagePNG",
            
"mime" => "image/png",
        ),
        
=> array(
            
// SWF
            
"load" => "ImageCreateFromWBMP",
            
"show" => "ImageWBMP",
            
"mime" => "image/wbmp",
        )
    );

    
# If REQUEST_URI is not available, use the "old" method.
    
if (!empty($_SERVER["REQUEST_URI"])) {
        
$MYSELF $_SERVER["REQUEST_URI"];
    } else {
        
$MYSELF $_SERVER["SCRIPT_NAME"];
        if (!empty(
$_SERVER["QUERY_STRING"])) {
            
$MYSELF .= "?" $_SERVER["QUERY_STRING"];
        }
    }

    
// configurable overrides
    
if (!isset($gallery) or ! is_array($gallery)) {
        
$gallery = array();
    }
    if (
DEBUG) {
        
dump($gallery"Original options:");
    }
    
InitGlobalOptions($gallery);
    if (
DEBUG) {
        
dump($gallery"Computed options:");
    }

    
$thumbpixels $gallery["thumbpixels"];

    function 
InitGlobalOptions(&$gallery)
    {
        global 
$_SERVER;

        if (isset(
$gallery["no_title"])) {
            
$gallery["head1"] = $gallery["title"] = $gallery["head2"] = "";
        } else {
            if (! isset(
$gallery["head1"])) {
                
$gallery["head1"] = "<html>\n<head>\n<title>";
            }
            if (! isset(
$gallery["title"])) {
                
$gallery["title"] = "Gallery";
            }
            if (! isset(
$gallery["head2"])) {
                
$gallery["head2"] = "</title>\n" .
                    
"<meta name=\"monetization\" content=\"\$coil.xrptipbot.com/R5rqeJzRRHqG8MHciH2V9g\">" .
                    
"</head>\n<body>";
            }
        }
        if (! isset(
$gallery["script"])) {
            if (
substr($_SERVER["SCRIPT_NAME"], -1) != "/"
                
$gallery["script"] = basename($_SERVER["SCRIPT_NAME"]);
            else
                
$gallery["script"] = "";
            if (
DEBUG) {
                print 
"Script name: server: " $_SERVER["SCRIPT_NAME"] . "\nComputed: "
                    
$gallery["script"] . "\n<br>";
            }
        }
        if (! isset(
$gallery["index"])) {
            
$gallery["index"] = $gallery["script"];
        }
        if (! isset(
$gallery["subparams"])) {
            
$gallery["subparams"] = $gallery["script"];
        }
        if (! isset(
$gallery["thumbpixels"])) {
            
$gallery["thumbpixels"] = 150;
        }
        if (! isset(
$gallery["DefaultScale"])) {
            global 
$defaultscale;
            
$gallery["DefaultScale"] = $defaultscale;
        }
        if (! isset(
$gallery["DefaultQual"])) {
            global 
$defaultqual;
            
$gallery["DefaultQual"] = $defaultqual;
        }

        foreach(array(
"text""zoomtext") as $field) {
            if (! isset(
$gallery[$field])) {
                
$gallery[$field] = array();
            }
        }

        
// see also the "text" and "zoomtext" arrays which I'll have to write
        //  docs for later.
    
}

    function 
CopyOverrides(&$source, &$dest)
    {
        
$overrides = array(
            
"script",
            
"index",
            
"subparams",
            
"copyright",
            
"DefaultScale",
            
"DefaultQual",
        );

        if (
DEBUG) {
            
dump($source"CopyOverrides from:");
            
dump($dest"to:");
        }

        foreach (
$overrides as $globalvar) {
            if (
array_key_exists($globalvar$source)
                && ! 
array_key_exists($globalvar$dest)) {
                
$dest[$globalvar] = $source[$globalvar];
            }
        }
    }

    function 
dump($var$label "")
    {
        print(
"<pre><strong>$label</strong>\n");
        
ob_start("htmlentities");
        
var_export($var);
        
ob_end_flush();
        print(
"\nMemory usage: " number_formatmemory_get_usage() ) . "<br>\n" );
        print(
"</pre>" );
    }

    
/* Stolen from a comment on
    https://secure.php.net/manual/en/function.session-register.php
    */
    
function emulate_session_register()
    {
        function 
session_register()
        {
            
$args func_get_args();
            foreach (
$args as $key)
            {
                
$_SESSION[$key]=$GLOBALS[$key];
            } 
        }

        function 
session_is_registered($key)
        {
            return isset(
$_SESSION[$key]);
        }

        function 
session_unregister($key)
        {
            unset(
$_SESSION[$key]);
        } 
    }
    if (!
function_exists('session_register'))
        
emulate_session_register(); 

    function 
SID($join "?")
    {
        
$trans_sid = (bool)ini_get("session.use_trans_sid");
        if (!
$trans_sid && session_id() == '' ) {
            
ini_set("session.use_trans_sid"1);
            
$trans_sid = (bool)ini_get("session.use_trans_sid");
        }
        if (
$trans_sid) {
            return 
"";
        }
        if (
SID != "")
            return 
$join strip_tags(SID);
        return 
"";
    }
    
    function 
Array_fold_recursive(&$array1, &$array2)
    
/* Note that we will not be returning a value, but will be modifying the arrays in place.
     *
     * I don't like the way PHP's array_merge and array_merge_recursive
     * functions handle collisions, so we're going to do it my way
     *
     * Given two array, array1, and array2, fold the values of array2 into array1.
     * In the case of STRING key collisions:
     * 1) If the values are both arrays, then they will be recursively folded.
     * 2) If only the first value is an array, the second value will be appended to it. 
     * 3) If the first value is not an array, it will be overwritten with the second value.
    */
    
{
        foreach(
$array2 as $key2 => $value2) {
            if (
is_string($key2)) {
                if (! 
array_key_exists($key2$array1)) {
                    
$array1[$key2] = $value2;
                } elseif (
is_array($array1[$key2]) && is_array($array2[$key2])) {
                    
Array_fold_recursive($array1[$key2], $array2[$key2]);
                } elseif (
is_array($array1[$key2])) {
                    
$array1[$key2][] = $value2;
                } else {
                    
$array1[$key2] = $value2;
                }
            } else {
                
$array1[] = $value2;
            }
        }
    }

    function 
ScaleDown($a$b$maxa$maxb NULL)
    {
        if (
is_null($maxb))
            
$maxb $maxa;
        if (
$a && $b && $maxa && $maxb
            
&& ($a $maxa || $b $maxb)) {
            if (
$a $maxa $b $maxb) {
                
$newa $maxa;
                
$newb round($b $a $maxa);
            } else {
                
$newa round($a $b $maxb);
                
$newb $maxb;
            }
            return array(
$newa$newb);
        }

        return array(
$a$b);
    }

    function 
GenerateThumb($file$maxpixelwidth=0$maxpixelheight=NULL,
        
$quality=NULL$try_exif=FALSE)
    {
        global 
$thumb$enable_exif$handlers$qualarray;

        if (
DEBUG) {
            
dump(func_get_args(), "GenerateThumb arguments");
        }
        if (
is_null($maxpixelheight))
            
$maxpixelheight=$maxpixelwidth;
        
$qualityvalue is_null($quality) ? $qualarray[0]["value"]
            : (isset(
$qualarray[$quality]) ? $qualarray[$quality]["value"]
            : 
100);
        if (
DEBUG) {
            
dump($qualityvalue"\$qualityvalue");
        }
        
// find or create a thumbnail for the given file.
        
if ($try_exif
            
&& $enable_exif
            
&& ($exif = @read_exif_data($file))
            && 
$exif
            
&& (@$exifthumb exif_thumbnail($file))
            && 
$exifthumb !== false
            
)
        {
            if (
DEBUG) print("Exif thumbnail<br>\n");
            
//$im = ImageCreateFromString($exif["Thumbnail"]);
            
header("Content-Type: $mime");
            
//$show($im, '', $qualityvalue);
            //ImageDestroy($im);
            
print($exifthumb);
            return 
TRUE;
        } elseif (
is_file($file)
            && 
is_readable($file)
            && @
$size GetImageSize($file)) {
            
// dump the existing thumbnail image.
            
if (DEBUG) print("Manual thumbnail<br>\n");
            
$width $size[0];
            
$height $size[1];
            
$type $size[2];
            
$load $handlers[$type]["load"];
            
$show $handlers[$type]["show"];
            
$mime $handlers[$type]["mime"];
            
//$mime = image_type_to_mime_type( $type );
            
if (DEBUG) {
                
dump($load"load");
                
dump($show"show");
                
dump($mime"mime");
                
dump(function_exists($load), "function_exists(load)");
                
dump(function_exists($show), "function_exists(show)");
            }
            if (isset(
$load) && isset($show) && isset($mime)
                && 
function_exists($load)
                && 
function_exists($show)
                && 
$maxpixelwidth
                
) {
                if (
DEBUG) print("Scale down to $maxpixelwidth<br>\n");
                
$im NULL;
                if( 
DEBUG )
                {
                    
dumpgd_info(), "gd_info" );
                    
$handle fopen($file"r");
                    
$contents fread($handle159);
                    
fclose($handle);
                    
dumpbin2hex$contents ) );
                    
$im ImageCreateFromJPEG$file );
                    
dumpbin2hex$im ) );
                }
                if (
$im = @$load($file)) {
                    
// scale it down!
                    
if( DEBUG ) print("\n<br>Scale: $width$height$maxpixelwidth$maxpixelheight<br>\n");
                    list(
$thumbwidth$thumbheight)
                        = 
ScaleDown($width$height$maxpixelwidth$maxpixelheight);
                    if( 
DEBUG ) print("\n<br>Actual: $width$height$thumbwidth$thumbheight<br>\n");
                    if( ! 
IMAGEDEBUG )
                    {
                        
$thumbim null;
                        if( 
function_exists"imagecreatetruecolor" ) )
                            @
$thumbim imagecreatetruecolor($thumbwidth$thumbheight);
                        if( ! 
$thumbim )    // imagecreatetruecolor doesn't exist, or failed
                            
$thumbim ImageCreate($thumbwidth$thumbheight);
                        if( 
DEBUG dump("ImageCreate");
                        
ImageCopyResized($thumbim$im0000,
                            
$thumbwidth$thumbheight$width$height);
                        if( 
DEBUG dump("ImageCopyResized");
                        
ImageDestroy($im);
                        
$im $thumbim;
                    }

                    
header("Content-Type: $mime");
                    
$show($im''$qualityvalue);
                    
ImageDestroy($im);
                    
$thumbfilename dirname($file) . DIRECTORY_SEPARATOR $thumb basename($file);
                    if (
is_null($quality) && ! file_exists($thumbfilename)) {
                        
$ret = @$show($im$thumbfilename30);
                        if (
DEBUG) {
                            if (
$ret) {
                                print 
"Wrote $thumbfilename (returned $ret)\n";
                            } else {
                                print 
"Failed writing $thumbfilename\n";
                            }
                            exit();
                        }
                    }
                    return 
TRUE;
                }
            } elseif (isset(
$mime)) {
                
// ugly fallback case, just send the raw file

                
header("Content-Type: $mime");
                
//$show($im, '', $qualityvalue);
                //ImageDestroy($im);
                
readfile($file);
                
#$content = file($file);
                #print(join('', $content));
                
return TRUE;
            }
        }
        return 
FALSE;
    }

    function 
SendThumbnail($file, &$gallery)
    {
        global 
$thumb$thumbpixels$scaleparam$scalearray
            
$qualparam$qualarray,
            
$_GET$handlers;

        
$fileinfo = array();
        
$prev NULL;
        
$next NULL;
        
$parent NULL;
        
$allfiles BuildAllFiles($gallery$fileinfo$prev$next,
            
$parent$file);
        if (
$fileinfo && array_key_exists("result"$fileinfo)) {
            
$fileinfo =& $fileinfo["result"];
        }
        if (
DEBUG) {
            
dump($_GET"_GET");
        }
        if (isset(
$file)
            && 
$fileinfo
            
&& array_key_exists("file"$fileinfo)) {
            if (
DEBUG) {
                
dump($fileinfo"fileinfo");
            }
            
// Compute the thumbpixels width and height
            
$scale=$_GET[$scaleparam];
            if (isset(
$scale) && is_numeric($scale)
                && 
$scale >= && $scale count($scalearray)) {
                
$thumbpixelswidth $scalearray[$scale]["width"];
                
$thumbpixelsheight $scalearray[$scale]["height"];
            } else if (isset(
$scale)) {
                
// No scaling, just re-compressing
                
$thumbpixelswidth $fileinfo["size"][0];
                
$thumbpixelsheight $fileinfo["size"][1];
            } else {
                
$thumbpixelswidth $thumbpixelsheight $thumbpixels;
                unset(
$scale);
            }
            
// figure out which quality to use
            
if (isset($scale)) {
                
$qual=$_GET[$qualparam];
                if(
DEBUG) {
                    
dump($qualparam"\$qualparam");
                    
dump($qual"\$qual");
                }
                if (isset(
$qual) && is_numeric($qual)
                    && 
$qual >= && $qual count($qualarray)) {
                    
$qual intval($qual);
                } else {
                    
$qual "";
                }
            } else {
                
$qual NULL;
            }
            if (
DEBUG) {
                
dump($qual"\$qual");
            }
            
// Try to generate a thumbnail
            
if (DEBUG) print "Generate thumbnail on " $file "<br>";
            if ((
                    ! isset(
$scale) && GenerateThumb($fileinfo["thumbname"])
                )
                || 
GenerateThumb($file$thumbpixelswidth$thumbpixelsheight
                    
$qual, !isset($scale)))
            {
                return 
TRUE;
            }
        }

        
$im ErrorImage();
        for (
$i 0$i count($handlers); $i++) {
            if (
function_exists($handlers[$i]["show"])) {
                
$show $handlers[$i]["show"];
                
$mime $handlers[$i]["mime"];
                
header("Content-Type: $mime");
                
$show($im''80);
                break;
            }
        }
        
ImageDestroy($im);
        return 
FALSE;
    }

    function 
VideoMessage($which)
    {
        if (
$which) {
            return 
"Video file.\nClick to view.";
        } else {
            return 
"Video file.";
        }
    }

    function 
VideoFont()
    {
        return 
5;
    }

    function 
ErrorMessage()
    {
        return 
"No thumbnail";
    }

    function 
ErrorFont()
    {
        return 
3;
    }

    function 
SendVideoThumbnail(&$gallery$which)
    {
        global 
$thumb$thumbpixels$scaleparam$scalearray
            
$qualparam$qualarray,
            
$_GET$handlers;

        
$im ErrorImage(VideoMessage($which), VideoFont());
        for (
$i 0$i count($handlers); $i++) {
            if (
function_exists($handlers[$i]["show"])) {
                
$show $handlers[$i]["show"];
                
$mime $handlers[$i]["mime"];
                
header("Content-Type: $mime");
                
$show($im''80);
                break;
            }
        }
        
ImageDestroy($im);
        return 
FALSE;
    }

    function 
MessageImageSize($message$font)
    {
        
$fheight imagefontheight($font);
        
$fwidth imagefontwidth($font);
        
$message explode("\n"$message);

        
$x = (max(array_map("strlen"$message)) + 2) * $fwidth//95;
        
$y = (count($message) + 2) * $fheight//25;

        
return compact("fheight""fwidth""x""y""message""font");
    }

    function 
ErrorImage($message null$font null)
    {
        if (!
extension_loaded('gd')) {
            exit;
        }
        global 
$thumbpixels;
        if (!
$message$message ErrorMessage();
        if (!
$font$font ErrorFont();

        
$size MessageImageSize($message$font);
        
extract($size);
        
$im ImageCreate($x,$y); // Create a blank image
        
$bgc ImageColorAllocate ($im255255255);
        
$tc  ImageColorAllocate ($im000);
        
ImageFilledRectangle ($im00$x$y$bgc);
        
/* Output an errmsg */
        
foreach ($message as $num => $line) {
            
ImageString($im$font, ($x $fwidth strlen($line)) / 2
                (
$num 1) * $fheight$line$tc);
        }
        return 
$im;
    }

    function 
ExtraInfo($file$info$exif=NULL$header=0)
    {
        global 
$enable_exif;
        
$ret "";
        
$openheader TRUE;

        if (
$header && $openheader) {
            
$ret_h .= "<h$header align=\"center\">";
        } else {
            
$ret_h .= "<br>";
        }
        
/*
        print("<pre>");
        //var_dump($info);
        var_dump(array_keys($info));
        foreach ($info as $key => $value) {
            $iptc = iptcparse ($value);
            print("\n\n\n[$key] = \n");
            var_dump ($iptc);
            if (! $iptc && $header) {
                print("\n$value\n");
            }
        }
        print("</pre>");
        */
        
if (DEBUG && FALSE) {
            
$ret .= "<br>";
            
$ret .= ($enable_exif "Exif enabled" "No exif functions");
            if (
$enable_exif) {
                
$exif = @read_exif_data($file);
                
$ret .= "<Br>";
                foreach (
$exif as $key => $value)
                {
                    
$ret .= "$key, ";
                }
                
$ret .= "<Br>";
                
$ret .= array_key_exists("DateTime"$exif);
            }
        }
        if (
is_dir($file)) {
            if (@
$mtime filemtime($file)) {
                
$ret .= $ret_h;
                
$openheader false;
                
$ret .= strftime("%a %b %e %Y %I:%M%p"$mtime);
            }
        } elseif ((
            ! 
is_null($exif)
            || 
is_file($file)
            && 
$enable_exif
            
&& ($exif = @read_exif_data($file))
            && 
$exif
            
)
            && 
array_key_exists("DateTime"$exif)
            && 
preg_match("/(\d{4}):(\d{2}):(\d{2}) "
                
"(\d{2}):(\d{2}):(\d{2})/",
                
$exif["DateTime"],$match)
            )
        {
            if (
DEBUG$ret .= "<br>(Found exif date info)\n"
                
$exif["DateTime"] . "\n";
            
$ret .= $ret_h;
            
$openheader false;
            
$ret .= gmstrftime("%a %b %e %Y %I:%M%p"
                
gmmktime($match[4], $match[5], $match[6],
                
$match[2], $match[3], $match[1]));
        }
        elseif (isset (
$info["APP12"]))
        {
            
#$ret .= "<br><pre>" . $info["APP12"] . "</pre>\n";
            
if (preg_match("/TimeDate=(\d+)/",$info["APP12"],$match)) {
                
$ret .= $ret_h;
                
$openheader false;
                
$ret .= gmstrftime("%a %b %e %Y %I:%M%p"$match[1]);
            }
        } elseif (isset (
$info["APP1"])) {
            if (
preg_match("/(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/",
                
$info["APP1"],$match)) {
                
#$ret .= "<br><pre>" . $match[0] . "</pre>\n";
                
$ret .= $ret_h;
                
$openheader false;
                
$ret .= gmstrftime("%a %b %e %Y %I:%M%p"
                    
gmmktime($match[4], $match[5], $match[6], $match[2], $match[3], $match[1]));
            }
        }
        if (isset (
$info["APP13"])) {
            
$ret .= $ret_h;
            
$openheader false;
            
ob_start();
            
$iptc iptcparse ($info["APP13"]);
            if (
is_array($iptc)
                && isset(
$iptc["2#120"])) {
                print 
$iptc["2#120"][0];
                
#var_dump ($iptc);
                /*
 $caption = $iptc["2#120"][0];
    $graphic_name = $iptc["2#005"][0];
        $urgency = $iptc["2#010"][0];    
    $category = $iptc["2#015"][0];    
    // note that sometimes supp_categories contans multiple entries
$supp_categories = $iptc["2#020"][0];
$spec_instr = $iptc["2#040"][0];
$creation_date = $iptc["2#055"][0];
$photog = $iptc["2#080"][0];
$credit_byline_title = $iptc["2#085"][0];
$city = $iptc["2#090"][0];
$state = $iptc["2#095"][0];
$country = $iptc["2#101"][0];
$otr = $iptc["2#103"][0];
$headline = $iptc["2#105"][0];
$source = $iptc["2#110"][0];
$photo_source = $iptc["2#115"][0];
$caption = $iptc["2#120"][0];    
Keywords: $iptc["2#025"][n];   (there is a list of keywords)
Caption Writer: $iptc["2#122"][0];
                */
                
$ret .= ob_get_contents();
            }
            
ob_end_clean();
        }
        if (
$header && ! $openheader) {
            
// header was opened
            
$ret .= "</h$header>\n";
        } else {
            
$ret .= "\n";
        }
        return 
$ret;
    }

    function 
filedircmp($a$b)
    {
        
/*
        if (array_key_exists("dir", $a) && array_key_exists("file", $b)) {
            return -1;
        } elseif (array_key_exists("file", $a) && array_key_exists("dir", $b)) {
            return 1;
        } else */
{
            return 
strcmp($a["name"], $b["name"]);
        }
    }

    function &
LoadGalleryOptions($filename)
    {
        
// DO NOT do anything with the global $gallery in here!
        
global $gallery_has_started;

        
ob_start();
        
$cwd getcwd();
        
// change dir so that any relative includes of the subfile will work
        
chdir(dirname($filename));
        
// include the file.  note that if it includes this script, it will abort becuase of the ref to 
        //  $gallery_has_started
        
include(basename($filename));
        
// change back
        
chdir($cwd);

        if (
DEBUG) {
            
$contents ob_get_contents();
        }
        
ob_end_clean();
        if (
DEBUG) {
            
dump($contents"Results of including $filename:");
            
dump( isset( $gallery ) ? $gallery NULL"Options are:");
        }
        return isset(
$gallery) ? $gallery : array();
    }

    function &
FindTarget($allfiles$path, &$prev, &$next, &$parent) {
        
$pathinfo explode(DIRECTORY_SEPARATOR$path);

        
$currfiles = &$allfiles;

        
//$lastparent = array();
        
$parent["result"] =& $currfiles;

        
$each each($pathinfo);
        while (list(
$key$search) = $each) {
            
$each each($pathinfo);
            if (
DEBUG) print "looking for $search<br>\n";
            
$match NULL;
            unset(
$prev["result"]);
            
$keys array_keys($currfiles);
            while (list(, 
$currindex) = each($keys)) {
                
$curr = &$currfiles[$currindex];
                if ((! 
$each || array_key_exists("dir"$curr))
                    && 
$curr["name"] === $search) {
                    if (
DEBUG) {
                        print(
"Match at $currindex<br>\n");
                    }
                    if (
$each) {
                        if (
DEBUG) {
                            print(
"Parent name is " $parent["result"]["name"]
                                . 
"<br>\nParent type is " gettype($parent["result"]) . "<br>\n");
                        }
                        
//$lastparent["result"] =& $parent["result"];
                        
$parent["result"] = &$curr;
                        
$currfiles = &$curr["children"];
                        
$match $currindex;
                        break;
                    } else {
                        list(, 
$nextindex) = each($keys);
                        if (
$nextindex) {
                            
$next["result"] = &$currfiles[$nextindex];
                        }
                        
/*
                        if (array_key_exists("file", $curr)) {
                            // if the match is a file, then the proper parent is the directory
                            // above the "current"
                            if (array_key_exists("result", $lastparent)) {
                                $parent["result"] =& $lastparent["result"];
                            } else {
                                unset($parent["result"]);
                            }
                        }
                        */
                        
if (DEBUG) {
                            print(
"Parent name is " $parent["result"]["name"]
                                . 
"<br>\nParent type is " gettype($parent["result"])
                                . 
"<br>\nPrev name is " $prev["result"]["name"]
                                . 
"<br>\nNext name is " $next["result"]["name"]
                                . 
"<br>\n");
                        }
                        return 
$curr;
                    }
                }
                
$prev["result"] = &$curr;
            }
            if (
is_null($match)) {
                if (
DEBUG) print("No match<br>\n");
                return 
NULL;
            }
        }

        return 
NULL;
    }

    function 
BuildFileMatch(&$hit, &$currentfile, &$gallery,
        &
$allfiles, &$index,
        &
$fileinfo, &$parent, &$prev, &$next, &$targetrest, &$targetsearch)
    {
        
extract($currentfileEXTR_REFS);
        if (
array_key_exists("dir"$currentfile)) {
            if (
DEBUG) {
                
dump($currentfile"Possible directory "
                    
"match on $targetsearch");
            }
            if ((
is_array($parent))
                && (
$targetrest != '')
                && (! 
is_null($targetrest))) {
                if (
DEBUG) {
                    print(
"Parent name is "
                        
$parent["result"]["name"]
                        . 
"<br>\nParent type is "
                        
gettype($parent["result"])
                        . 
"<br>\n");
                }
                
$parent["result"] = &$currentfile;
            }
    
            
CopyOverrides($gallery,
                
$gallery["children"][$filename]);
            
$currentfile["children"] =
                
BuildAllFiles($gallery["children"][$filename],
                    
$fileinfo$prev$next$parent,
                    
$targetrest$fullfile
                
);
            
$currentfile["gallerysettings"] =
                &
$gallery["children"][$filename];
    
            if (
count($currentfile["children"])) {
                
$hit true;
                if (
DEBUG) {
                    
dump($currentfile"Confirmed directory "
                        
"match on $targetsearch");
                }
                
// File and directory label determination
                
if (! isset($gallery["text"][$filename])
                    && isset(
$gallery["children"][$filename]["title"])) {
                    if (
DEBUG) print "Using param title for $filename text<br>\n";
                    
$gallery["text"][$filename] = $gallery["children"][$filename]["title"];
                } elseif (! isset(
$gallery["children"][$filename]["title"])) {
                    if (isset(
$gallery["text"][$filename])) {
                        if (
DEBUG) print "Using param text for $filename title<Br>\n";
                        
$gallery["children"][$filename]["title"] = $gallery["text"][$filename];
                    } else {
                        if (
DEBUG) print "Using defaulttext ($defaulttext) for $filename title<br>\n";
                        
$gallery["children"][$filename]["title"] = $defaulttext;
                    }
                } elseif (
DEBUG) {
                    print 
"Using params for both $filename text ("
                        
$gallery["text"][$filename]
                        . 
") and title("
                        
$gallery["children"][$filename]["title"]
                        . 
")<br>\n";
                }
            } else {
                
// No children.  Remove this dir from the 
                // file array
                
array_splice($allfiles$index1);
            }
        } elseif (
array_key_exists("file"$currentfile)) {
            if (
preg_match("/\.(mpe?g)$/i"$filename)) {
                
$hit true;
                
/*
                unset($currentfile["file"]);
                */
                
$currentfile["video"] = 1;
                
$currentfile["size"] = "Video";
                
$currentfile["thumbname"] .= ".jpg";
                if (
DEBUG) {
                    
dump($currentfile"Video match on " $targetsearch);
                }
            } else if (
preg_match("/\.(avi|mov|asf|3g2)$/i"$filename$matches)) {
                
$hit true;
                
/*
                unset($currentfile["file"]);
                */
                
$currentfile["video"] = 1;
                
$currentfile["size"] = "Video";
                
$currentfile["thumbname"] = str_replace$matches[0], ".thm"$currentfile["fullfile"] );
                if (
DEBUG) {
                    
dump($currentfile"Video match on " $targetsearch);
                }
            } else if (@
$size GetImageSize($fullfile$info)) {
                
$hit true;
                if (
DEBUG) {
                    
dump($currentfile"File match on "
                        
$targetsearch);
                }
                
// just a normal file
                
if (DEBUG && FALSE) {
                    print(
"file " $filename "<br>\n");
                }
                
$temp = array(
                    
"size" => $size,
                    
"info" => $info
                
);
                if (
DEBUG) {
                    
$temp["info"] = "Suppressed for DEBUG";
                }
                
Array_fold_recursive($currentfile$temp);
            } else {
                
// Not an image.  Remove this file from the 
                // file array
                
array_splice($allfiles$index1);
            }
        }    
// file or dir check
        
if (DEBUG && !$hit) {
            
dump($currentfile"No match");
        }
    }

    function 
BuildAllFiles(&$gallery, &$fileinfo, &$prev, &$next, &$parent,
        
$target ''$dirname ".")
    
// if $target is '', process all the items, but pass a NULL target to dirs
    // if $target is NULL, process only the last item (basically for the parent thumbnail)
    // if $target is in the current dir, only process it.
    // if $target is not in the current dir, act as if it was ''.
    // if $target has extra path info after hitting a file, ignore it.
    
{
        global 
$thumblen$thumb$thumbextregex;
        if (
DEBUG) {
            
dump($gallery"looking in dir " $dirname "<br>\n");
        }
        if (!isset(
$gallery["children"])) {
            
$gallery["children"] = array();
        }
        
/* split the target into
            targetsearch - the component we're looking for in the current dir
            targetrest - the rest of the path
        */
        
if (DEBUG && FALSE) {
            
$targetNULL;
            
dump($target"target string");
        }
        if (
is_null($target)) {
            
$targetsearch $targetrest $target;
        } else {
            
$target explode(DIRECTORY_SEPARATOR$target2);
            if (
DEBUG && TRUE) {
                
dump($target"target array");
            }
            
$targetsearch array_shift($target);
            if (
$targetsearch == '') {
                
$targetrest NULL;
            } else {
                
$targetrest implode(DIRECTORY_SEPARATOR$target);
            }
        }
        if (
DEBUG && TRUE) {
            
dump($targetsearch"targetsearch in $dirname");
            
dump($targetrest"rest of target");
        }
        if (
$dir opendir($dirname)) {
            
$allfiles = array();
            
$info = array();
            
$pathinfo explode(DIRECTORY_SEPARATOR$dirname2);
            
array_shift($pathinfo);
            
$pathinfo[] = "";
            
$pathinfo implode(DIRECTORY_SEPARATOR$pathinfo);
            if (
DEBUG && TRUE) {
                print(
"pathinfo is " $pathinfo "<br>\n");
            }
            
// BuildAllFiles portion
            
while ($filename readdir($dir)) {
                
// ignore hidden files and directories
                
if (substr($filename01) != ".") {
                    
$fullfile $dirname DIRECTORY_SEPARATOR $filename;
                    
$fullname $pathinfo $filename;
                    if (
DEBUG && FALSE) {
                        print(
"Check: " $fullfile "<br>\n");
                    }
                    if (
is_readable($fullfile)) {
                        
$defaulttext 
                            
preg_replace(
                                
"/[-_.]/"" ",
                                
preg_replace("/\..{1,5}?$/"""$filename)
                            ) . 
"\n";
                        if (
DEBUG) print "default text for $filename is $defaulttext<br>\n";
                        if (
DEBUG && TRUE) {
                            print(
"type: " filetype($fullfile) . " " $fullfile "<br>\n");
                        }
                        if (
is_dir($fullfile)) {
                            
// directories go first
                            
if (DEBUG && TRUE) {
                                
dump("dir " $fullfile "<br>\n");
                            }
                            if (!isset(
$gallery["children"][$filename])) {
                                
$gallery["children"][$filename] = array();
                            }
                            
$temp = array(
                                
"dir" => TRUE,
                                
"name" => $filename,
                                
"filename" => $filename,
                                
"fullname" => $fullname,
                                
"fullfile" => $fullfile,
                                
"defaulttext" => $defaulttext,
                            );
                            if ( 
DEBUG && dump$temp"Allfiles entry" );
                            
$allfiles[] = &$temp;
                        } elseif (
strcmp(substr($filename,0,$thumblen), $thumb
                            && ! 
preg_match$thumbextregex$filename )
                            && 
is_file($fullfile) ) {
                            if (
DEBUG && TRUE) {
                                print(
"file " $fullfile "<br>\n");
                            }
                            if (
$filename == $gallery["subparams"]
                                && 
$dirname != "." ) {
                                if (
DEBUG)
                                    
dump($filename"Loading gallery options in $fullfile");
                                
$temp =& LoadGalleryOptions($fullfile);
                                
Array_fold_recursive($gallery$temp);
                            } else {
                                
$temp = array(
                                    
"file" => TRUE,
                                    
"name" => $filename,
                                    
"filename" => $filename,
                                    
"fullname" => $fullname,
                                    
"fullfile" => $fullfile,
                                    
"pathinfo" => $pathinfo,
                                    
"thumbname" => $pathinfo $thumb $filename
                                
);
                                
$allfiles[] = &$temp;
                            }
                        }
                        else if (
DEBUG && TRUE
                        {
                            print(
"unknown " $fullfile "<br>\n");
                        }
                        
$end end($allfiles);
                        if (
$end["filename"] == $filename
                            
&& ! isset($gallery["text"][$filename])) {
                            if (
DEBUG) print "Using default text for $filename<br>\n";
                            
$gallery["text"][$filename] = $defaulttext;
                        }
                    }
                    unset(
$temp);
                }
            }
            
closedir($dir);
            
usort($allfiles"filedircmp");

            
// FindTarget portion
            
$hit false;
            
$passnumber 0;
            while (! 
$hit && $passnumber <= 1) {
                
$passnumber++;
                if (
is_array($parent)
                    && ! 
array_key_exists("result"$parent) ) {
                    
$parent["result"] =& $allfiles;
                }

                
$allkeys array_reverse(array_keys($allfiles));
                foreach (
$allkeys as $index) {
                    
$currentfile =& $allfiles[$index];
                    
extract($currentfileEXTR_REFS);
        
// if $target is '', process all the items, but pass a NULL target to dirs
        // if $target is NULL, process only the last item (basically for the parent thumbnail)
        // if $target is in the current dir, only process it.
        // if $target is not in the current dir, act as if it was ''.
        // if $target has extra path info after hitting a file, ignore it.
                    
if ($targetsearch == ''
                        
|| is_null($targetsearch)
                        || 
$targetsearch === $filename)
                    {
                        
BuildFileMatch($hit$currentfile$gallery,
                            
$allfiles$index,
                            
$fileinfo$parent$prev$next,
                            
$targetrest$targetsearch);
                        if ((
is_null($targetsearch)
                            || 
$targetsearch === $filename)
                            && 
$hit)
                        {
                            
// we're done.  We've either found our file, or
                            // processed the last file.
                            
if (! $fileinfo
                                
&& $targetsearch === $filename) {
                                
$fileinfo["result"] =& $currentfile;
                                
// At this point, if we've got a match, find out whether we have a
                                //  next and/or prev entry.  Be sure to pass bogus array refs 
                                //  to the possible recursive calls, to ensure that ours don't
                                //  get nuked
                                
if (DEBUG) {
                                    
dump($allkeys"Allkeys");
                                    
dump($index"Index");
                                }
                
                                
// look for $prev
                                
if (is_array($prev)) {
                                    
reset($allkeys);
                                    while ((list(, 
$searchindex) = each($allkeys))
                                        && 
$index != $searchindex)
                                    {
                                        if (
DEBUG && FALSEdump(''"No match on $searchindex");
                                    }
                                    while (list(, 
$searchindex) = each($allkeys))
                                    {
                                        if (
array_key_exists($searchindex$allfiles)) {
                                            if (
DEBUGdump(''"Checking $searchindex for prev");
                                            
$searchfile =& $allfiles[$searchindex];
                                            
$searchhit false;
                                            
$searchfileinfo = array();
                                            
$searchparent = array();
                                            
$searchprev = array();
                                            
$searchnext = array();
                                            
$searchtarget NULL;
                                            
BuildFileMatch($searchhit$searchfile$gallery,
                                                
$allfiles$searchindex,
                                                
$searchfileinfo$searchparent$searchprev,
                                                
$searchnext$searchtarget$searchtarget);
                                            if (
$searchhit) {
                                                
$prev["result"] =& $searchfile;
                                                break;
                                            } else {
                                                
$index--;
                                            }
                                        }
                                    }
                                }

                                
// look for $next
                                
if (is_array($next)) {
                                    
$allkeys array_keys($allfiles);
                                    
reset($allkeys);
                                    while ((list(, 
$searchindex) = each($allkeys))
                                        && 
$index != $searchindex)
                                    {
                                        if (
DEBUG && FALSEdump(''"No match on $searchindex");
                                    }
                                    while (list(, 
$searchindex) = each($allkeys))
                                    {
                                        if (
array_key_exists($searchindex$allfiles)) {
                                            if (
DEBUGdump(''"Checking $searchindex for next");
                                            
$searchfile =& $allfiles[$searchindex];
                                            
$searchhit false;
                                            
$searchfileinfo = array();
                                            
$searchparent = array();
                                            
$searchprev = array();
                                            
$searchnext = array();
                                            
$searchtarget NULL;
                                            
BuildFileMatch($searchhit$searchfile$gallery,
                                                
$allfiles$searchindex,
                                                
$searchfileinfo$searchparent$searchprev,
                                                
$searchnext$searchtarget$searchtarget);
                                            if (
$searchhit) {
                                                
$next["result"] =& $searchfile;
                                                break;
                                            } else {
                                                
prev($allkeys);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }    
// target match, or null, or empty target
                
}    // foreach (array_reverse(array_keys($allfiles)) as $index)
                
if (! $hit) {
                    
$targetsearch '';
                    
$targetrest NULL;
                }    
// if (! $hit)
            
}    // while (! $hit && $passnumber <= 1)

            
if (DEBUG && 0) {
                print(
"Parent name is " $parent["result"]["name"]
                    . 
"<br>\nParent type is " gettype($parent["result"])
                    . 
"<br>\nPrev name is " $prev["result"]["name"]
                    . 
"<br>\nNext name is " $next["result"]["name"]
                    . 
"<br>\n");
            }

            return 
$allfiles;
        } else {
            return 
NULL;
        }
    }

    function 
urlencodepath($str)
    
// works like urlencode, but preserves path (ie. '/')
    
{
        
$split explode("/"$str);

        
$split array_map("urlencode"$split);

        return 
implode("/"$split);
    }

    function 
rawurlencodepath($str)
    
// works like rawurlencode, but preserves path (ie. '/')
    
{
        
$split explode("/"$str);

        
$split array_map("rawurlencode"$split);

        return 
implode("/"$split);
    }

    function 
GetThumbImgTag($fileinfo, &$gallery)
    {
        global 
$thumb$thumbparam$videothumbparam,
            
$thumbpixels$param$enable_exif;

        
extract($fileinfoEXTR_REFS);

        
$ret "";

        if (
DEBUG && FALSEdump($gallery"options in GetThumbImgTag");
        if (
array_key_exists("video"$fileinfo)
            && ! @
GetImageSize$thumbname ) ) {
            if (
DEBUG$ret .= "Video file - fake thumbnail<br>\n";
            
$messagesize MessageImageSize(VideoMessage(0), VideoFont());
            
$ret .= "<img width=\"" $messagesize["x"] ."\" "
                
"height=\"" $messagesize["y"] ."\" "
                
"src=\"" $gallery["script"] . "/"
                
rawurlencodepath($thumbname)
                . 
"?$videothumbparam=0"
                
"\" alt=\""
                
urlencode($name)
                . 
"\" title=\""
                
urlencode($name)
                . 
"\">";
        } else if (@
$thumbsize GetImageSize($thumbname))
        {
            if (
DEBUG$ret .= "Found existing thumbnail file<br>\n";
            
//$thumbwidth=$thumbsize[0];
            //$thumbheight=$thumbsize[1];
            
$thumbstring=$thumbsize[3];
            
$ret .= "<img "
                
$thumbstring " "
                
"src=\""
                
rawurlencodepath($thumbname)
                . 
"\" alt=\""
                
urlencode($name)
                . 
"\" title=\""
                
urlencode($name)
                . 
"\">";
        } elseif (
$enable_exif
            
&& function_exists"ImageCreateFromString" )
            && (
$exif = @read_exif_data($fullname))
            && 
$exif
            
&& (@$exifthumb exif_thumbnail($fullname))
            && 
$exifthumb !== false
        
)
        {
            if (
DEBUG$ret .= "Found exif thumbnail info<br>\n".strlen($exifthumb)."<br>".strlen(exif_thumbnail($fullname))."<br>\n";
            {
                
$image ImageCreateFromString($exifthumb);
                
$thumbwidth ImageSX($image);
                
$thumbheight ImageSY($image);
                list(
$thumbwidth$thumbheight)
                    = 
ScaleDown($thumbwidth$thumbheight$thumbpixels);
                
ImageDestroy($image);
            }
            
$ret .= "<img "
                
"width=\"$thumbwidth\" "
                
"height=\"$thumbheight\" "
                
"src=\"" $gallery["script"] . "/"
                
rawurlencodepath($thumbname)
                . 
"?$thumbparam="
                
urlencode($fullname)
                . 
"\" alt=\""
                
urlencode($name)
                . 
"\" title=\""
                
urlencode($name)
                . 
"\">";
            if (
DEBUG && FALSE) {
                print 
"<table><tr><td><pre>";
                
print_r ($exif);
                print 
"</pre></td></tr></table>";
            }
        } else {
            if (
DEBUG$ret .= "Manual thumb computation<br>\n";
            if (
DEBUG && true) {
                
dump($exif"Enable_exif $enable_exif");
                print(
"Length of thumbnail string: " strlen($exifthumb));
            }
            
$width=$size[0];
            
$height=$size[1];
            list(
$thumbwidth$thumbheight)
                = 
ScaleDown($width$height$thumbpixels);
            
$ret .= "<img width=\"$thumbwidth\" "
                
"height=\"$thumbheight\" "
                
"src=\"" $gallery["script"] . "/"
                
rawurlencodepath($thumbname)
                . 
"?$thumbparam="
                
urlencode($fullname)
                . 
"\" alt=\""
                
urlencode($name)
                . 
"\" title=\""
                
urlencode($name)
                . 
"\">";
        }

        return 
$ret;
    }

    function 
DisplayFileEntry(&$fileinfo$limit, &$counter, &$gallery)
    {
        global 
$thumb$thumbparam$videothumbparam,
            
$thumbpixels$param$enable_exif;

        if (
DEBUG && FALSE) {
            print(
"<pre>");
            
print_r($fileinfo);
            print(
"</pre>");
        }
        
extract($fileinfoEXTR_REFS);

        
$bgcolor="";
        if (
$counter $limit == 0)
            print 
"<tr>\n";
        if (
array_key_exists("file"$fileinfo)) {
            unset(
$exif);
            if (
is_array($size)) {
                
$sizestring "(" $size[0] . " x " $size[1] . ")\n";
            } else {
                
$sizestring "(" $size ")\n";
            }
            
$thumbtag GetThumbImgTag($fileinfo$gallery);
        } elseif (
array_key_exists("dir"$fileinfo)) {
            
$bgcolor="lightblue";
            
$thumb = &end($fileinfo["children"]);
            if (
DEBUG && FALSE) {
                print(
"thumb is: $thumb with " count($thumb) . " items<br>\n");
            }
            while (
array_key_exists("dir"$thumb)) {
                
$temp = &end($thumb["children"]);
                unset(
$thumb);
                
$thumb = &$temp;
                unset(
$temp);
                if (
DEBUG && FALSE) {
                    print(
"thumb is: $thumb with " count($thumb) . " items<br>\n");
                }
            }
            
$thumbtag GetThumbImgTag($thumb$gallery);
            
$count = array();
            foreach(
$children as $child) {
                if (
array_key_exists("file"$child)) {
                    
$count["file"]++;
                } elseif (
array_key_exists("dir"$child)) {
                    
$count["folder"]++;
                } else {
                    
$count["other"]++;
                }
            }
            foreach (
$count as $type => $child) {
                if (
$child == 1) {
                    
$count[$type] .= " " $type;
                } elseif (
$child 1) {
                    
$count[$type] .= " " $type "s";
                } else {
                    
$count[$type] = "(error on $type)";
                }
            }
            
$sizestring "(" implode(", "$count) . ")\n";
            
$gallery["text"][$name] = "<strong><em>" $gallery["text"][$name] . "</em></strong>";
        } else {
            
$sizestring "(error)\n";
        }
        print 
"<td align=\"center\" width=\"" 100/$limit "%\""
            
. ($bgcolor == "" "" " bgcolor=\"" $bgcolor "\"")
            . 
">\n";
        if (isset(
$gallery["text"][$name])) {
            print 
$gallery["text"][$name] . "<br>\n";
        } else {
            print 
"<!--No name???-->\n";
        }
        print 
"\t<a href=\"" $gallery["script"] . "?$param="
            
urlencode($fullname) . SID("&") . "\">";
        print 
$thumbtag;
        print 
"</a>";
        print 
"<br>";
        print 
$sizestring;
        print 
ExtraInfo($fullname$info$exif);
        print 
"</td>\n";
        
$counter++;
        if (
$counter $limit == 0)
            print 
"</tr>\n";
    }

    function 
SendSingleFile(&$gallery, &$fileinfo, &$prev, &$next, &$parent)
    {
        global 
$thumb$thumbparam$videothumbparam,
            
$thumbpixels$param$enable_exif,
            
$_SESSION$scalearray$scaleparam
            
$qualarray$qualparam$MYSELF,
            
$fullsizelabel$highqualitylabel;

        if (isset(
$fileinfo)) {
            
extract($fileinfoEXTR_REFS);

            if (
is_array($size)) {
                
$width=$size[0];
                
$height=$size[1];
            } elseif (
array_key_exists("video"$fileinfo)) {
                
$messagesize MessageImageSize(VideoMessage(1), VideoFont());
                
$width $messagesize["x"];
                
$height $messagesize["y"];
                unset(
$messagesize);
            } else {
                
$width $height $thumbpixels;
            }
            
$scale=$_SESSION["scale"];
            if (isset(
$scale) && is_numeric($scale)
                && 
$scale >= && $scale count($scalearray)) {
                
$thumbpixelswidth $scalearray[$scale]["width"];
                
$thumbpixelsheight $scalearray[$scale]["height"];
            } else {
                
#unset($scale);
                
$thumbpixelswidth $width;
                
$thumbpixelsheight $height;
            }
            
$qual=$_SESSION["qual"];
            if (isset(
$qual) && is_numeric($qual)
                && 
$qual >= && $qual count($qualarray)) {
                
$qual intval($qual);
            } else {
                
$qual "";
            }
            if (!isset(
$gallery["no_title"])) {
                
$gallery["title"] .= ": $name";
                print 
$gallery["head1"] . $gallery["title"] . $gallery["head2"] . "\n";
                print 
"<h1 align=\"center\">" $gallery["title"] . "</h1>\n";
                print 
ExtraInfo($name$infoNULL4) . "\n";
                if (isset(
$gallery["text"][$name])) {
                    print 
"<p align=\"center\">"
                        
$gallery["text"][$name] . "</p>\n";
                }
                if (isset(
$gallery["zoomtext"][$name])) {
                    print 
"<p align=\"center\">"
                        
$gallery["zoomtext"][$name] . "</p>\n";
                }
                
//print "<br>\n";
                
if (isset($gallery["extrahtml"])) {
                    print 
"<p align=\"center\">"
                        
$gallery["extrahtml"] . "</p>\n";
                }
            }
            
$nav "<table width=\"100%\" align=\"center\"><tr><td>\n";

            
/*
            if (array_key_exists("result", $parent)
                ) {
                $nav .= "<a href=\"" . $gallery["script"];
                if (array_key_exists("fullname", $parent["result"])) {
                    $nav .= "?$param="
                        . urlencode($parent["result"]["fullname"]) . SID("&");
                } else {
                    $nav .= SID();
                }
                $nav .= "\">";
            }
            $nav .= "Parent";
            if (array_key_exists("result", $parent)) {
                $nav .= "</a>";
            }
            $nav .= "\n";
            */

            
if (array_key_exists("result"$prev)) {
                
$nav .= "<a href=\"" $gallery["script"] . "?$param="
                    
urlencode($prev["result"]["fullname"]) . SID("&") . "\">";
            }
            
$nav .= "Previous";
            if (
array_key_exists("result"$prev)) {
                
$nav .= "</a>";
            }
            
$nav .= "\n";

            
$nav .= "<a href=\"" $gallery["index"];
            if (
array_key_exists("result"$parent)
            ) {
                
$nav .= "?$param="
                    
urlencode(dirname($fullname)) . SID("&");
            } else {
                
$nav .= SID();
            }
            
$nav .= "\">Index</a>";
            
$nav .= "\n";

            if (
array_key_exists("result"$next)) {
                
$nav .= "<a href=\"" $gallery["script"] . "?$param="
                    
urlencode($next["result"]["fullname"]) . SID("&") . "\">";
            }
            
$nav .= "Next";
            if (
array_key_exists("result"$next)) {
                
$nav .= "</a>";
            }
            
$nav .= "\n";
            
            
$nav .= "\n</td><td align=\"right\">\n";
            
$nav .= "<form method=\"POST\" action=\"$MYSELFSID("&") . "\">\n";
            
$nav .= "Max display dimensions:\n";
            
$nav .= "<select name=\"$scaleparam\" onchange=\"javascript:this.form.submit();\">\n";
            
$nav .= "<option value=\"\""
                
. (isset($scale) && $scale !== ""?"":" selected") . ">"
                
"$fullsizelabel\n";
            foreach (
$scalearray as $i => $scaleinfo) {
                
$nav .= "<option value=\"$i\""
                    
. (isset($scale) && is_numeric($scale) && $i == $scale
                        
" selected" "")
                    . 
">"
                    
$scaleinfo["width"] . "x" 
                    
$scaleinfo["height"] . "\n";
            }
            
$nav .= "</select>\n";
            
$nav .= "<select name=\"$qualparam\" onchange=\"javascript:this.form.submit();\">\n";
            
$nav .= "<option value=\"\""
                
. (isset($qual) && $qual !== "" "" " selected") . ">"
                
"$highqualitylabel\n";
            foreach (
$qualarray as $i => $qualinfo) {
                
$nav .= "<option value=\"$i\""
                    
. (isset($qual) && $i === $qual 
                        
" selected" ""
                    . 
">" $qualinfo["label"] . "\n";
            }
            
$nav .= "</select>\n";
            
$nav .= "<noscript><input type=\"Submit\" value=\"Change\"></noscript>\n";
            
$nav .= "</form>\n";
            
$nav .= "\n</td></tr></table>";

            
$imghtml="";
            
$dimension "<table width=\"100%\" align=\"center\"><tr align=\"center\"><td>\n";
            if (
array_key_exists("video"$fileinfo)) {
                
$dimension .= "(Video)";
            } else {
                
$dimension .= "($width x $height)";
                if (isset(
$scale)
                    && (
$thumbpixelswidth $width
                    
|| $thumbpixelsheight $height)) {
                    list(
$width$height)
                        = 
ScaleDown($width$height$thumbpixelswidth,
                        
$thumbpixelsheight);
                    
$dimension .= " scaled down to ($width x $height)";
                }
            }
            
$imghtml .= "<a href=\""
                
rawurlencodepath($fullname) . "\">";
            if (
array_key_exists("video"$fileinfo)) {
                if (
DEBUG) {
                    
dump($fileinfo"Video fileinfo");
                }
                
$imghtml .= "<img src=\"" $gallery["script"] . "/"
                    
rawurlencodepath($thumbname)
                    . 
"?$videothumbparam=1"
                    
"\" alt=\""
                    
urlencode($name)
                    . 
"\" title=\""
                    
urlencode($name)
                    . 
"\" "
                    
"width=\"$width\" height=\"$height\" "
                    
"border=\"1\">";
            } elseif (
is_int($qual)) {
                
$dimension .= " (" 
                    
preg_replace('/\s*\([^()]*\)/'''
                        
$qualarray[$qual]["label"]) 
                    . 
")";
                if (
DEBUG) {
                    
dump($fileinfo"fileinfo");
                }
                
// formerly "$thumbname", but these aren't really thumbs,
                // are they
                
$imghtml .= "<img src=\"" $gallery["script"] . "/"
                    
rawurlencodepath($pathinfo "scale" $width "." 
                        
"qual" $qualarray[$qual]["value"] . "."
                        
$filename
                    
)
                    . 
"?$thumbparam="
                    
urlencode($fullname) . "&$scaleparam="
                    
urlencode($scale)
                    . 
"&$qualparam="
                    
urlencode($qual)
                    . 
"\" alt=\""
                    
urlencode($name)
                    . 
"\" title=\""
                    
urlencode($name)
                    . 
"\" "
                    
"width=\"$width\" height=\"$height\" "
                    
"border=\"0\">";
            } else {
                
$imghtml .= "<img src=\""
                    
rawurlencodepath($fullname)
                    . 
"\" alt=\""
                    
urlencode($name)
                    . 
"\" "
                    
"title=\""
                    
urlencode($name)
                    . 
"\" "
                    
"width=\"$width\" height=\"$height\" border=\"0\">";
            }
             
$imghtml .= "</a>\n";
            
$dimension .= "\n</td></tr></table>";

            print 
"$nav<p>\n";
            print 
"$imghtml\n";
            print 
"$dimension\n";
            print 
"<p>\n$nav";
            print 
MyCopyright($gallery);

            return 
TRUE;
        }
        return 
FALSE;
    }

    function 
SendIndex($gallery$target)
    {
        global 
$_POST$_GET$_SESSION,
            
$_SERVER,
            
$defaultlimit$enable_exif$param;

        
$fileinfo = array();
        
$prev = array();
        
$next = array();
        
$parent = array();
        
$allfiles BuildAllFiles($gallery$fileinfo,
            
$prev$next$parent$target);
        if (
DEBUG) {
            
dump($gallery"Params after tree parsing:");
            
dump($target"Target");
            
dump($fileinfo"Fileinfo");
        }
        if (
DEBUG && true ) {
            
dump($allfiles"All files after tree parsing");
        }

        
$limit = isset($_SESSION["limit"])
            ? 
$_SESSION["limit"]
            : 
$defaultlimit;

        if (isset(
$target)
            && 
$fileinfo)
        {
            if (
array_key_exists("result"$fileinfo)) {
                
$fileinfo =& $fileinfo["result"];
            }
            if (
DEBUG) {
                print(
"Parent name is " $parent["result"]["name"]
                    . 
"<br>\nParent type is " gettype($parent["result"])
                    . 
"<br>\nPrev name is " $prev["result"]["name"]
                    . 
"<br>\nNext name is " $next["result"]["name"]
                    . 
"<br>\n");
                
/*
                print("<pre>Parent, just for comparison\n");
                print_r($parent);
                print("/pre>");
                */
            
}
            if (
array_key_exists("file"$fileinfo))
            {
                if (
DEBUG) {
                    
dump($fileinfo"fileinfo");
                }
                if (
array_key_exists("result"$parent)
                    && 
array_key_exists("fullname"$parent["result"])) {
                    unset(
$gallery);
                    
$gallery =& $parent["result"]["gallerysettings"];
                    if (
DEBUG) {
                        print(
"Directory " $parent["result"]["fullname"] . "<br>\n");
                        
dump($gallery"Gallery settings:");
                    }
                    
InitGlobalOptions($gallery);
                    if (
DEBUG) {
                        
dump($gallery"Gallery settings after:");
                    }
                }
                if (
SendSingleFile($gallery,
                    
$fileinfo$prev$next$parent)) {
                    return 
TRUE;
                }
                
/*
                foreach ($allfiles as $file) {
                    // Get sizes
                    if (strcmp(substr($file,0,$thumblen), $thumb) 
                        && is_file($file)
                        && is_readable($file)
                        && $size = GetImageSize($file, &$info)) {
                        if (isset($the_file)) {
                            // we're only repeating the loop to see if 
                            //  there's a "next"
                            $is_next = TRUE;
                            $next_file = $file;
                            break;
                        }
                        if ($file == $target) {
                            $the_file = $file;
                            $the_size = $size;
                            $the_info = $info;
                            $the_target = $counter;
                        } else {
                            $is_prev = TRUE;
                            $prev_file = $file;
                        }
                        $counter++;
                    }
                }
                */
            
} elseif (array_key_exists("dir"$fileinfo)) {
                unset(
$allfiles);
                
$allfiles =& $fileinfo["children"];
                if (
DEBUG) {
                    
dump($gallery"Global gallery settings:");
                }
                unset(
$gallery);
                
$gallery =& $fileinfo["gallerysettings"];
                if (
DEBUG) {
                    print(
"Directory " $fileinfo["fullname"] . "<br>\n");
                    
dump($gallery"Gallery settings:");
                }
                
InitGlobalOptions($gallery);
                if (
DEBUG) {
                    
dump($gallery"Gallery settings after:");
                }
            } elseif (
DEBUG) {
                
dump($fileinfo"Unknown match result type");
            }
        }
    
        
// display the index
        
if (!isset($gallery["no_title"])) {
            print 
$gallery["head1"] . $gallery["title"] . $gallery["head2"] . "\n";
            print 
"<h1 align=\"center\">" $gallery["title"] . "</h1>\n";
            if (isset(
$gallery["extrahtml"])) {
                print 
"<p align=\"center\">"
                    
$gallery["extrahtml"] . "</p>\n";
            }
            if (isset(
$gallery["extraindexhtml"])) {
                print 
"<p align=\"center\">"
                    
$gallery["extraindexhtml"] . "</p>\n";
            }
        }

        
$nav "";
        if (isset(
$fileinfo)
            && 
array_key_exists("dir"$fileinfo)) {
            if (
array_key_exists("result"$prev)) {
                
$nav .= "<a href=\"" $gallery["script"] . "?$param="
                    
urlencode($prev["result"]["fullname"]) . SID("&") . "\">";
            }
            
$nav .= "Previous";
            if (
array_key_exists("result"$prev)) {
                
$nav .= "</a>";
            }
            
$nav .= "\n";

            
$nav .= "<a href=\"" $gallery["script"];
            if (
array_key_exists("result"$parent)
                && 
array_key_exists("fullname"$parent["result"])) {
                
$nav .= "?$param="
                    
urlencode($parent["result"]["fullname"]) . SID("&");
            } else {
                
$nav .= SID();
            }
            
$nav .= "\">";
            
$nav .= "Index";
            
$nav .= "</a>";
            
$nav .= "\n";

            if (
array_key_exists("result"$next)) {
                
$nav .= "<a href=\"" $gallery["script"] . "?$param="
                    
urlencode($next["result"]["fullname"]) . SID("&") . "\">";
            }
            
$nav .= "Next";
            if (
array_key_exists("result"$next)) {
                
$nav .= "</a>";
            }
            
$nav .= "\n";
        }
        print(
$nav);

        if (isset(
$allfiles)) {
            if( 
DEBUG && true dump$allfiles"All files:" );
            print 
"<table border width=\"100%\" align=\"center\" bgcolor=\"white\">\n";
            
$counter=0;
            foreach (
$allfiles as $fileinfo) {
                
DisplayFileEntry($fileinfo$limit$counter$gallery);
            }
            if (
$counter == 0) {
                print 
"<tr><td align=\"center\">No image files found.</td></tr>\n";
            }
            print 
"</table>";
        } else {
            print 
"<h2>Error</h2>\n";
        }
        print(
$nav);
        
//<span style="display:none"></span>
        
if (function_exists("honeypot")) {
            print 
honeypot();
        } else {
            print 
"<!-- Hello spammers!  Send your crap to "
                
$_SERVER["SERVER_NAME"]
                . 
"-" $_SERVER["SERVER_PORT"]
                . 
"-"
                
str_replace(
                    
"~""X",
                    
str_replace("/""__"$_SERVER["REQUEST_URI"])
                )
                . 
"-" $_SERVER["REMOTE_ADDR"]
                . 
"-" date('y_m_j_His')
                . 
"@honeypot.castleanthrax.org -->\n";
        }
        print 
"<div style=\"position: absolute; top: " .
            
"-250px; left: -250px;\"><a " .
            
"href=\"https://www.hennis.org/horizontal.php" .
            
"\">incoming-catholic</a></div>\n";
    
        print 
MyCopyright($gallery);
        print 
"</body>\n";
        print 
"</html>\n";

    }

//////////////////////////////////////////////////
// function main()
//////////////////////////////////////////////////
    
if (! headers_sent()) {
        
SID();
        
session_start();
    }

    if (isset(
$_GET[$thumbparam])) {
        if (
DEBUG) {
            print(
"$thumbparam param is " $_GET[$thumbparam] . "<br>\n");
            print(
"stripped $thumbparam param is " stripslashes($_GET[$thumbparam]) . "<br>\n");
        }
        return 
SendThumbnail(stripslashes($_GET[$thumbparam]), $gallery);
    } elseif (isset(
$_GET[$videothumbparam])) {
        if (
DEBUG) {
            print(
"$videothumbparam param is " $_GET[$videothumbparam] . "<br>\n");
            print(
"stripped $videothumbparam param is " stripslashes($_GET[$videothumbparam]) . "<br>\n");
        }
        return 
SendVideoThumbnail($gallery$_GET[$videothumbparam]);
    } else {
        if (! 
session_is_registered("scale")) {
            
session_register("scale");
            
$_SESSION["scale"] = $gallery["DefaultScale"];
        }
        if (! 
session_is_registered("qual")) {
            
session_register("qual");
            
$_SESSION["qual"] = $gallery["DefaultQual"];
        }
        if (isset(
$_POST[$scaleparam])) {
            
$_SESSION["scale"]=$_POST[$scaleparam];
            
Header("Location: $MYSELFSID("&"));
        }
        if (isset(
$_POST[$qualparam])) {
            
$_SESSION["qual"]=$_POST[$qualparam];
            
Header("Location: $MYSELFSID("&"));
        }
        if ( isset(
$_GET["limit"])
            && 
is_numeric($_GET["limit"])
            && 
$_GET["limit"] > )
        {
            
$_SESSION["limit"] = $_GET["limit"];
        }
        return 
SendIndex($gallery$target);
    }

    function 
MyCopyright(&$gallery)
    {
        
$ret = array(
            
"<script src=\"http://js-kit.com/comments.js\"></script>\n",
            
"<p align=\"right\" style=\"font-size: small\">\n",
            (
                
array_key_exists("copyright"$gallery)
                ? 
$gallery["copyright"] . "<br>\n"
                
""
            
),
            
"autogallery.php version 1.0,\n",
            
"<a href=\"" $gallery["script"] . "/license.txt?showlicense=1\">",
            
"Copyright &copy; 2001-2003\n",
            
"</a>\n",
            
"Edward Hennis.",
            
"</p>\n",
        );
        return 
implode(""$ret);
    }

    function 
ShowLicense()
    {
        global 
$gallery;
        
InitGlobalOptions($gallery);

        print 
"<h1 align=\"center\">autogallery.php version 1.0, Copyright (C) 2001-2003 Edward Hennis.</h1>\n";
        print 
"autogallery.php comes with ABSOLUTELY NO WARRANTY.\n";
        print <<<EOL
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; either version 2 of the License, or (at your option) any later version.
EOL;
        print 
"<hr>\n";

        
$gpl = <<<EOL
The GNU General Public License (GPL)
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

    c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

NO WARRANTY

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.

    one line to give the program's name and a brief idea of what it does.
    Copyright (C)

    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; either version 2 of the License, or (at your option) any later version.

    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 along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:

    Yoyodyne, Inc., hereby disclaims all copyright interest
    in the program `Gnomovision' (which makes passes at compilers)
    written by James Hacker.

    signature of Ty Coon, 1 April 1989
    Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.
    
EOL;
        
$gpl nl2br(
            
preg_replace("/\n[ \t]+((.*(\n[ \t])?)+)\n/""<ul>\$1</ul>",
                
htmlspecialchars($gpl)
            )
        );
        print 
$gpl "\n";
        print 
"<hr>\n";
        print 
"The most current version of the GPL can probably be found\n";
        print 
"<a href=\"http://www.fsf.org/licenses/gpl.html\">here</a>\n";
        print 
"or\n";
        print 
"<a href=\"http://www.opensource.org/licenses/gpl-license.php\">here</a>\n";
        print 
"<hr>\n";
        print 
"The source code for this file is available by clicking\n";
        print 
"<a href=\"" $gallery["script"] . "/source.html?gimmesource=1\">here</a>\n";
        print 
"<hr>\n";
        print 
"The author can be reached via email at \n";
        print 
htmlspecialchars("<eah+autogallery at vaxer dot net>") . ".\n";
        print 
"I suppose I should put a postal address or some other contact\n";
        print 
"method here, but I'm not going to. :-P\n";
    }
?>