<?
/*
	GIS is a freeware image gallery. It uses php-gd or imagemagick to make thumbnails and previews. If you have a standard installation of 
	apache php4 and imagemagick or php-gd GIS will work. If you want to use imagemagick the webbserver must have the shell-command "convert".
	convert is a part of imagemagick.
	
	GIS Homepage: http://gis.gussoh.com/

	GIS is covered by the GPL Licence.
	GIS is primarly maintained by Gustav "Gussoh" Sohtell.
	Version 2 was mostly done in January 2004.
	Work on what is now called GIS was started in 2001.
*/

/*      
        CONFIGURATION HELP:
        
        The configuration you find in this file is the configuration that will be used if there is no other setting in the "gis.conf.php"-file.
        If you want to keep any special setting across version upgrades you should put the setting inside gis.conf.php instead.
        
        As an example I'll set the quality-setting to 100, the use_previews-setting to true and the usertag-setting to "Hello World":
        
        These settings in gis.conf.php would look like:
                quality = 100
                usertag = "Hello World"
                use_previews = yes
                ;All the usual ways of setting a configuration key works but always use "=" between key and value.
                ;These lines are comments in the configuration-file.
                
               	;This is how you use groups
                [upload]
                	enabled = true
               		password = "god"
                
        These settings in index.php would look like:
                $conf['quality'] = 100;
                $conf['usertag'] = "Hello World";
                $conf['use_previews'] = true;
                // As this is PHP-code the rules are much stricter. Quotes around strings and ";" at the end of each setting.
                // These lines are comments in PHP

		// Groups:
		$conf['upload']['enabled'] = true;
		$conf['upload']['password'] = "god";
                
        If a setting exists in both index.php and gis.conf.php, the setting in gis.conf.php will be used!
        
*/
        /* If you want to use the config file - the location of it should be specified below. like: define('CONFIG_FILE', 'location-of-gis.conf.php') 
        remember to use double slashes on windows (c:\\www\\gis\\_imagesystem\\gis.conf.php) 
        the first row in a configfile should be ";<?php die(" You are not allowed to read this file! ;"); ?>" without the outer quotes */
        define('CONFIG_FILE', '.gis/gis.conf.php');

	/* Start dir. Defines the root of web archive. Start dir also needs to be specified in a define-constant */
	define('START_DIR', '.'); /* Webserver must be able to link to files in this location */
        define('MODULES', ''); /* Modules to add. Example: define('MODULES', '.gis/googleModule.php .gis/testModule.php'); Each module filename separated by spaces */
        
/*      CONFIGURATION:  */

umask(007);

$conf["helpful"] = true; /* Popups help-messages */
$conf["style"] = "gis.css"; /* use your own css-stylesheet */
$conf["user_tag"] = ""; /* Written at top of the archive, use <pre>text</pre> if you use ascii-art */

/* Special icons */
$conf["icons"]["folder"] = "folder.gif";
$conf["icons"]["folder_unreadable"] = "folder_unreadable.gif";
$conf["icons"]["folder_up"] = "folder_up.gif";
$conf["icons"]["folder_open"] = "folder_open.gif";
$conf["icons"]["empty"] = "icon_empty.gif";

/* Icons, lower case extension. If you make additions - please send them to me and I'll add them to the default release */
$conf["icons"]["doc"] = "icon_doc.gif";
$conf["icons"]["gif"] = "icon_gif.gif";
$conf["icons"]["aac"] = "icon_itunes.gif";
$conf["icons"]["jpg"] = "icon_jpg.gif";
$conf["icons"]["jpeg"] = "icon_jpg.gif";
$conf["icons"]["avi"] = "icon_movie.gif";
$conf["icons"]["mpg"] = "icon_movie.gif";
$conf["icons"]["mpeg"] = "icon_movie.gif";
$conf["icons"]["mp4"] = "icon_quicktime.gif";
$conf["icons"]["mp3"] = "icon_mp3.gif";
$conf["icons"]["mp2"] = "icon_mp3.gif";
$conf["icons"]["nfo"] = "icon_nfo.gif";
$conf["icons"]["png"] = "icon_png.gif";
$conf["icons"]["ppt"] = "icon_ppt.gif";
$conf["icons"]["mov"] = "icon_quicktime.gif";
$conf["icons"]["rm"] = "icon_realone.gif";
$conf["icons"]["ram"] = "icon_realone.gif";
$conf["icons"]["rtf"] = "icon_rtf.gif";
$conf["icons"]["tif"] = "icon_tif.gif";
$conf["icons"]["tiff"] = "icon_tif.gif";
$conf["icons"]["txt"] = "icon_txt.gif";
$conf["icons"]["text"] = "icon_txt.gif";
$conf["icons"]["log"] = "icon_txt.gif";
$conf["icons"]["pls"] = "icon_winamp.gif";
$conf["icons"]["m3u"] = "icon_winamp.gif";
$conf["icons"]["wmv"] = "icon_windowsmedia.gif";
$conf["icons"]["wma"] = "icon_windowsmedia.gif";

$conf["previous_arrow"] = "arrow_previous.gif";
$conf["next_arrow"] = "arrow_next.gif";
$conf["up_arrow"] = "arrow_up.gif";

$conf["gallery_name"] = "terminal.se Image Gallery";
$conf["layout"] = "gis2"; /* "gis1" will give you the old layout, "gis2" will give you the new one. No other defined (so far). gis1 is faster than gis2 */

$conf["thumbnail_max_width"] = 150;
$conf["thumbnail_max_height"] = 100;
$conf["thumbnail_image_quality"] = 80;
$conf["preview_max_width"] = 800;
$conf["preview_max_height"] = 600;
$conf["preview_image_quality"] = 80;

$conf["image_columns"] = 2; /* Number of columns with images, Set to 0 to make the web browser autowrap, any other numbers than 1 or 0 seem to bug in mozilla */
$conf["column_width"] = 200; /* Width of each image column in pixels, this should be greater than max_width of the thumbnails */
$conf["column_height"] = 150; /* Height of each image row in pixels, this should be greater than max_height of the thumbnails */

$conf["thumbnails_per_page"] = 0; /* Number of thumbnails per page, set to 0 for no pages */

$conf["click_on_image"] = 1; /* Click on a preview-image takes you:   0) not a link   1) back to archive    2) to fullsize image */
$conf["click_on_thumbnail"] = 1; /* Click on a thumbnail takes you:	0) not a link	1) to preview	2) popups preview in popup - dont set "click_on_image" to 1 if popups are used */

$conf["popup_width"] = 0; /* Width of popupbox for previes (if used). Set to 0 to make dynamic (previw_maxwidth + ~30)*/
$conf["popup_height"] = 0; /* Height of popupbox for previews (is used). Set to 0 to make dynamic (preview_maxheight + ~100)*/

$conf["date_format"] = "H:i:s, d F Y"; /* Timestamp format as in function date() found on php.net */
$conf["hide_directories_starting_with"] = "."; /* each string separated by spaces */
$conf["hide_files_starting_with"] = "."; /* separated by spaces */
$conf["hide_files_ending_with"] = ".php"; /* if you want to hide only index.php, write "index.php" instead of only ".php" */
$conf["follow_links"] = true;
$conf["version"] = "2.01";
$conf["system_dir"] = ".gis"; /* name of subdirectory containing icons if in maindir, but also thumbnails, comments and counters. */

$conf["image_filename_format"] = "%filename %descriptionAndComment"; /* Usually written below the image, set it to "" for nothing. Valid strings are: %filename, %filesize, %descriptionAndComment. The last will display something like D/C if both description and comment exists */
$conf["file_filename_format"] = "%filename&nbsp;(%filesize)"; /* File list format. Valid strings are %filename and %filesize */

$conf["thumbnail_allowed_tags"] = "<b><i><u>"; /* Tags allowed in the description in thumbnail view */
$conf["preview_allowed_tags"] = "<b><i><u>"; /* Tags allowed in descriptions in previews*/
$conf["filesize_units"] = "B KiB MiB GiB TiB"; /* "Bytes Kilobytes Megabytes Gigabytes Terabytes" Each unit separated by spaces, maxsize is usually 2GB */

$conf["not_images"] = "avi mpg mpeg txt"; /* extensions that aren't images but supported by imagemagick (or gd). Separated by spaces. All in lowercase! */
$conf["only_these_are_images"] = "jpeg jpg gif bmp png tif tiff"; /* if this is set to anything, only the extensions here are marked as images. if it says "jpg gif png" then only these three images are counted as images (unless there already is a thumbnail for the file) Each extension should be separated by spaces */
$conf["these_are_images"] = ""; /* If you are having PROBLEMS with GIS not understanding that these extensions ARE REALLY images then add them here. Each extension separated by space. */
$conf["description_end"] = ".desc.txt"; /* $image.description.txt */
$conf["thumbnail_end"] = ".thumb.jpg"; /* $image.jpg.thumb.jpg. Also specifies wich imagetype to use for thumbnails if using Imagemagick */
$conf["preview_end"] = ".prev.jpg"; /* $image.jpg.prev.jpg. Also specifies wich imagetype to use for previews if using Imagemagick*/
$conf["comments_end"] = ".comments.txt"; /* %image.comment.txt */
$conf["archive_comments_filename"] = "comments.txt"; /* Filename for achive comments, put in system_dir */
$conf["archive_description_filename"] = "description.txt"; /* Filename for archive descriptions, put in system_dir */

$conf["desription_thumbnail_maxlength"] = 0; /* longer strings will be cut from thumbnail description. If set to 1, full description is displayed. If set to 0, no characters are displayed. This option does not work if "thumbnail_allowed_tags" is set */

$conf["sort_directories"] = 1; /* Sort order of directories, 0) As in filesystem  1) Sort by natural-case-insensitive order  2) (1) but reversed  3) simple sort() */
$conf["sort_files"] = 1; /* Sort order of files, 0) As in filesystem  1) Sort by natural-case-insensitive order  2) (1) but reversed  3) simple sort() */
$conf["sort_images"] = 1; /* Sort order of images, 0) As in filesystem  1) Sort by natural-case-insensitive order  2) (1) but reversed  3) simple sort() */

$conf["use_archive_descriptions"] = true; /* descriptions for a whole archive */
$conf["use_image_descriptions"] = true; /* descriptions for a single image */
$conf["use_previews"] = true; /* show and create preview-files */
$conf["use_archive_comments"] = true; /* show and submit comments for a whole archive */
$conf["use_preview_comments"] = false; /* show and submit comments for a single picture */

$conf["max_execution_time"] = 30; /* Time in seconds allowed for resizeing each image (if using GD). If safemode is on, this has no effect */
$conf["imagemagick_output"] = "/dev/null"; /* Output from imagemagick is written here. Specify a file for logging from IM */
$conf["true_color_and_resample_off_with_gd"] = false; /* Makes thumbnails and previews without true color and resampling when using GD2. Good on slow machines. */

$conf["path_to_imagemagick_convert"] = ""; /* set to "blablabla" to disable imagemagick or to a correct path if convert cannot be found */
$conf["write_htaccess"] = false; /* writes a ".htaccess"-file in each system_dir containing "Options -Indexes" */
$conf["log_comment_host"] = 2; /* 0) does not log ip/host for comments   1) logs md5()-sum of ip/host   2) log ip/hostname in commentfile */
$conf["header"] = "Content-Type: text/html; charset=UTF-8"; /* Header default: "Content-type: text/html; charset=UTF-8" - specifing charset */
$conf["encode_comments_to_utf8"] = false; /* encodes comments to UTF-8, this should be set if a UTF-8-header is sent and comments are not submitted by UTF-8-browser */
$conf["encode_descriptions_to_utf8"] = true; /* encodes thumbnailes to UTF-8, this should be set if a UTF-8-header is sent and descriptions are not submitted by UTF-8-browser (probably not) */

/* Upload Settings */
$conf["upload"]["enabled"] = false; /* Enable upload feature (If you only want this in one folder use a gis.conf.php-file in that folder's .gis-folder) */
$conf["upload"]["password"] = ""; /* The upload password, remove for no password. The password is crypted if "password_crypted_level" is set to 1 or 2 */
$conf["upload"]["password_crypted_level"] = 0; /* if set to 0 - the password written here is plaintext. 1: the password an md5()-sum 2: the password is crypt(). Plaintext if omitted */
$conf["upload"]["allowed_files"] = "log txt jpeg jpg gif bmp png tif tiff mp3 avi mpg mpeg mov swf"; /* Allowed file extensions. If omitted the "disallowed_files"-setting is used instead */
$conf["upload"]["disallowed_files"] = "exe vbs doc pif scr bat"; /* if "allowed_files is not set then this will be used to filter out bad files */
$conf["upload"]["allow_new_folder"] = true; /* Allow creation of new folders */
$conf["upload"]["new_folder_text"] = ""; /* Text to tell the user what the textinput does, This is useful if you want the user to enter his/hers nick or similar. Example: "Nickname:</b><br>(new folder)<b>" */
$conf["upload"]["new_folder_error_text"] = ""; /* Error message when user tries to create a folder with disallowed characters. Example: "Your nickname contains disallowed characters." */
$conf["upload"]["allowed_characters"] = "abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ1234567890-_()[]{}!¤%&=+§½,. ";

/*      END OF CONFIGURATION    */
/*      LOAD MODULES            */

if(MODULES) {
        $modules = explode(' ', MODULES);
        foreach($modules as $module)
                require_once($module);
}

/*      END OF LOAD MODUES      */
/*      FUNCTIONS:      */

if(!function_exists("printUsertag")) {
        function printUsertag() {
                if(getConfig("user_tag")) {
                        echo("<table><tr><td>" . getConfig("user_tag") . "</td></tr></table>");
                }
        }
}

if(!function_exists("fileExistsAndIsReadable")) {
        function fileExistsAndIsReadable($file) {
                if(file_exists($file)) {
                        if(is_readable($file)) {
                                return true;
                        }
                        help("File '" . substr($file, strlen(START_DIR)) . "' exists but the web server cannot read it.");
                }
                return false;
        }
}

if(!function_exists("readableByGD")) {
        function readableByGD($extension) {
                /* Modified function from php.net */
                $aPossibleImageTypeBits = array(
                        /*IMG_GIF=>'gif',*/
                        IMG_JPG=>'jpg',
                        IMG_PNG=>'png',
                        IMG_WBMP=>'bmp'
                );
        
                foreach($aPossibleImageTypeBits as $iImageTypeBits => $sImageTypeString) {
                        if(imagetypes() & $iImageTypeBits) {
                                $aSupportedTypes[] = $sImageTypeString;
                        }
                }
        
                return in_array(strtolower($extension), $aSupportedTypes);
        }
}

if(!function_exists("readableByImagemagick")) {
        function readableByImagemagick($extension) {
                static $types;
                static $done;
                if(!$done) {
			if(getConfig("path_to_imagemagick_convert"))
				$convertPath = getConfig("path_to_imagemagick_convert") . "/";

			/* Get Imagemagick Version */
			$versionText = shell_exec($convertPath . "convert -version");
			$versionStartPos = strpos($versionText, "ImageMagick ") + strlen("ImageMagick ");
			$versionEndPos = strpos($versionText, " ", $versionStartPos);
			$version = substr($versionText, $versionStartPos, $versionEndPos - $versionStartPos);
			
                        $formats = explode("\n",(shell_exec($convertPath . "convert -list format")));
                        $done = true;
                        if(is_array($formats)) {
                                foreach($formats as $format) {
                                	$formatArray = str_word_count($format, 1);
                                	if($version < 6)
                                		$word = 0;
                                	else
                                		$word = 1;
                                	
                                	if(trim($formatArray[$word]) && strtoupper($formatArray[$word]) == $formatArray[$word])	
						$types[] = $formatArray[$word];
				}
			
				/* Seem as if Imagemagick 6 does not list jpg - added manually */
				if($version >= 6 && is_array($types))
					$types[] = "JPG";
			
			}
			
			/* Old Algorithm for Imagemagick 5 ONLY */
			/*if(getConfig("path_to_imagemagick_convert"))
				$convertPath = getConfig("path_to_imagemagick_convert") . "/";

                        $formats = explode("\n",(shell_exec($convertPath . "convert -list format")));
                        $done = true;
                        if(is_array($formats))
                                foreach($formats as $format)
                                        if($temp = str_replace("*", "", trim(substr($format,0,strpos($format, "  r")))))
                                                if(strtoupper($temp) == strtoupper($temp))
                                                        $types[] = $temp;*/
                }
		
		if(!is_array($types)) {
			help("Could not list supported Imagemagick formats. Imagemagick 5.x and 6.x is supported.");
			return false;
		}
                return in_array(strtoupper($extension), $types);
        }
}

if(!function_exists("imagemagickInstalled")) {
        function imagemagickInstalled() {
                static $set;
                static $returnCode;
        
                if(!$set) {
                        if(getOS() != "UNIX") { /* needs to be fixed if imagemagick is run under windows */
                                return false;
                        }
			if(getConfig("path_to_imagemagick_convert"))
				$convertPath = getConfig("path_to_imagemagick_convert") . "/";

                        $system = system($convertPath . "convert > " . getConfig("imagemagick_output"), $returnCode);
                        $set = true;
                }
                if($returnCode === 0) {
                        return true;
                }
                else
                        return false;
        }
}

if(!function_exists("gdInstalled")) {
        function gdInstalled() {
                static $done;
                static $gdInstalled;
                
                if(!$done) {
                        $done = true;
                        $gdInstalled = (extension_loaded("gd") || (!ini_get("safe_mode") && dl("gd.so")));	
                }
                
                return $gdInstalled;
        }
}

if(!function_exists("isImage")) {
        function isImage($filename) {
                $extension = end(explode(".", $filename));
	
		$areImages = explode(" ", getConfig("these_are_images"));
		if(is_array($areImages))
			if(in_array(strtolower($extension), $areImages))
				return true;
                        
                $notImages = explode(" ", getConfig("not_images"));
                if(is_array($notImages))
                        if(in_array(strtolower($extension), $notImages))
                                return false;
                
                $onlyTheseAreImages = explode(" ", getConfig("only_these_are_images"));
                if(is_array($onlyTheseAreImages))
                        if(!in_array(strtolower($extension), $onlyTheseAreImages))
                                return false;
                
                if(imagemagickInstalled())
                        return readableByImagemagick($extension);
                
                if(gdInstalled())
                        return readableByGD($extension);
        
                help("No imagemanager is installed. You either need php-gd (gd2 is better) or imagemagick. Safe mode has to be turned off (php.ini) to use imagemagick and convert must me shell-executable.");
                return false;
        }
}

if(!function_exists("getDir")) {
        function getDir() { /* get fixed url from get (makes url safe(er?)) !! DO NOT USE getConfig() IN THIS FUNCTION. (getConfig() uses getDir())*/
                $dir = getVariable("dir");
                if(!$dir && getVariable("direc"))
                        $dir = "/" . getVariable("direc");
                
                switch(true) { /* faulty dirs */
                        case substr_count($dir, ".."):
                        return false;
                }      
                
                while(substr_count($dir, "//")) /* Replaces all //, /// and /////... with / */
                        $dir = str_replace("//", "/", $dir);
                
                $dir = START_DIR . $dir;
                
                if(substr_count($dir, "..")) {
                        return START_DIR;
                }
                
                return $dir;
        }
}

if(!function_exists("printListDirectories")) {
        function printListDirectories($strDir = false, $level = 0) {
                if(!$strDir) {
                        if(getConfig("layout") == "gis1")
                                $strDir = getDir() ? getDir() : START_DIR;
                        else
                                $strDir = START_DIR;
                }
                
                $hideDirectoriesStartingWith = getConfig("hide_directories_starting_with");
                $hideDirectoriesStartingWith = explode(" ", $hideDirectoriesStartingWith); /* make an array of the strings */
                $follow_links = getConfig("follow_links");
                $systemDir = getConfig("system_dir");
                $startDir = START_DIR;
                $folderUnreadableIcon = getConfig("folder_unreadable", "icons");
                $folderIcon = getConfig("folder", "icons");
                $folderUpIcon = getConfig("folder_up", "icons");
                $folderOpenIcon = getConfig("folder_open", "icons");
                /* define("UNREADABLE_FILE", "<§UNREADABLE/$>"); NOT FINISHED!! */
                
                if(!fileExistsAndIsReadable($systemDir . "/" . $folderUpIcon))
                        $folderUpIcon = false;
                
                if(!fileExistsAndIsReadable($systemDir . "/" . $folderIcon))
                        $folderIcon = false;

                if(!fileExistsAndIsReadable($systemDir . "/" . $folderOpenIcon))
                        $folderOpenIcon = false;
                
                if(!fileExistsAndIsReadable($systemDir . "/" . $folderUnreadableIcon))
                        $folderUnreadableIcon = false;
        
                
                if(getOS() == "UNIX" && substr($strDir, -1) != "/" || getOS() == "Windows" && substr($strDir, -1) != "\\")
                        $strDir = $strDir . "/";
                
                if ($dir = @opendir($strDir)) {
                        
                        if($level == 0 && getConfig("layout") != "gis1") { /* make pseudo-root-dir containing gallery name */
                                echo("<a href=\"" . $_SERVER['PHP_SELF'] . "\">");
                                if(getDir() == START_DIR) {
                                        if($folderOpenIcon)
                                                echo("<img src=\"" . $systemDir . "/" . $folderOpenIcon . "\">&nbsp;");
                                        elseif($folderIcon)
                                                echo("<img src=\"" . $systemDir . "/" . $folderIcon . "\">&nbsp;");
                                }
                                elseif($folderIcon)
                                        echo("<img src=\"" . $systemDir . "/" . $folderIcon . "\">&nbsp;");
                                        
                                echo(getConfig("gallery_name") . "</a><br>\n");
                                $level++;
                        }
                        
                        if(getConfig("layout") == "gis1") {
                                if(getDir() != START_DIR) {
					/* .. - link */
                                        $link = substr(getDir(), strlen(START_DIR));
                                        $link = "?dir=" . urlencode(substr($link, 0, strrpos($link, "/"))); /* can be made into one substr */
					
                                        if($link == "?dir=")
						$link = "";

					echo("<a href=\"" . $_SERVER['PHP_SELF'] . $link . "\">");
                                        if($folderUpIcon)
                                                echo("<img src=\"" . $systemDir . "/" . $folderUpIcon . "\">&nbsp;");
                                        echo("up</a><br>");
                                }
                        }
                        
                        while(false !== ($file = readdir($dir))) {
                                $hide = false;
                                if(@is_dir($strDir . "/" . $file) && $file != "." && $file != "..") {
                                        if(is_array($hideDirectoriesStartingWith)) {
                                                foreach($hideDirectoriesStartingWith as $start) {
                                                        if(strlen($start) && substr($file, 0, strlen($start)) == $start) {
                                                                $hide = true;
                                                        }
                                                }
                                        }
        
                                        if(@is_readable($strDir . "/" . $file)) {
                                                if(!$follow_links && is_link($strDir . "/" . $file)) {
                                                        $hide = true;
                                                }
                                                if(!$hide) {
                                                        $directories[] = $file;
                                                        
                                                }
                                        }
                                        else {
                                                if(!$hide) {
                                                        $directories["<§UNREADABLE/$>" . $file] = $file;
                                                }
                                        }
                                }
                        }
                        
                        if(is_array($directories)) {
                                if(getConfig("sort_directories")) {
                                	switch(getConfig("sort_directories")) {
                                		case 1:
                                			natcasesort($directories);
                                			break;
                                		case 2:
                                			natcasesort($directories);
			                                $directories = array_reverse($directories);
                                			break;
                                		case 3:
                                			sort($directories);
                                			break;
                                	}
                                }
                                
                                foreach($directories as $key => $file) {
                                        
                                        for($i = 0; $i < $level; $i++) {
                                                echo("&nbsp;&nbsp;&nbsp;");
                                        }
                                                                        
                                        if(substr($key, 0, strlen("<§UNREADABLE/$>")) == "<§UNREADABLE/$>") {
                                                echo("<span class=unreadable>");
                                                if($folderUnreadableIcon)
                                                        echo("<img src=\"" . $systemDir. "/" . $folderUnreadableIcon . "\">&nbsp;");
                                                echo($file . "</span><br>\n");
                                        }
                                        else {
                                                $link = substr($strDir . $file,strlen($startDir));
                                                echo("<a href=\"" . $_SERVER['PHP_SELF'] . "?dir=" . urlencode($link) . "\">");
                                                
                                                if($link == substr(getDir(), strlen(START_DIR))) {
                                                        if($folderOpenIcon)
                                                                echo("<img src=\"" . $systemDir . "/" . $folderOpenIcon . "\">&nbsp;");
                                                        elseif($folderIcon)
                                                                echo("<img src=\"" . $systemDir . "/" . $folderIcon . "\">&nbsp;");
                                                }
                                                elseif($folderIcon) {
                                                        echo("<img src=\"" . $systemDir . "/" . $folderIcon . "\">&nbsp;");
                                                }
                                                                
                                                echo($file . "</a><br>");
                                                if(getConfig("layout") != "gis1")
                                                        printListDirectories($strDir . $file . "/", $level + 1);
                                        }
                                }
                        }
                        unset($directories);
                }
                else {
                        /* echo("<b>Could not read directory " . substr($strDir, strlen(START_DIR)) . "</b>"); */
                }
        }
}

if(!function_exists("createImage")) {
        function createImage($image, $type) { /* Create thumbnails or Preview-pictures $type can be "preview" or "thumbnail" */
                @set_time_limit(getConfig("max_execution_time"));
                flush();
		$fromFile = getDir() . "/" . $image;
                if(!fileExistsAndIsReadable($fromFile)) {
                        return false;
                }
                $toFile = getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig($type . "_end");
                if(!is_dir(getDir() . "/" . getConfig("system_dir") . "/")) {
                        if(is_writeable(getDir() . "/")) {
                                mkdir(getDir() . "/" . getConfig("system_dir") . "/", 0775);
				if(getConfig("write_htaccess") && is_writeable(getDir() . "/" . getConfig("system_dir") . "/")) {
       	                                $fp = fopen(getDir() . "/" . getConfig("system_dir") . "/" . ".htaccess", "w");
               	                        fwrite($fp, "Options -Indexes\n<Files gis.conf*>\n\torder deny,allow\n\tdeny from all\n</Files>");
                       	                fclose($fp);
				}
                        }
                        else {
                                help("The web server cannot write to this directory: '" . substr(getDir(), strlen(START_DIR)) . "/'.");
                                return false;
                        }
                }
                
                if(!is_writeable(getDir() . "/" . getConfig("system_dir") . "/")) {
                        help("The web server cannot write to this directory: '" . substr(getDir(), strlen(START_DIR)) . "/" . getConfig("system_dir") . "/'.");
                }
                else {
                        if(imagemagickInstalled()) {
				if(getConfig("path_to_imagemagick_convert"))
					$convertPath = getConfig("path_to_imagemagick_convert") . "/";

                                $system = system($convertPath . "convert -thumbnail " . getConfig($type . "_max_width") . "x" . getConfig($type . "_max_height") . " -quality " . getConfig($type . "_image_quality") . " " . escapeshellarg($fromFile) . " " . escapeshellarg($toFile), $returnCode);
                                if($returnCode !== 0) {
                                        help("Something went wrong creating $type for '$image', return code: $returnCode");
                                }
                        }
                        elseif(gdInstalled()) {
                                $imageSize = getImageSize($fromFile);
                                $wider = ($imageSize[0] > getConfig($type . "_max_width"));
                                $higher = ($imageSize[1] > getConfig($type . "_max_height"));
                                if($wider || $higher) {
                                        if($wider && !$higher) {
                                                $width = $imageSize[0] / ($rate = $imageSize[0] / getConfig($type . "_max_width"));
                                                $height = $imageSize[1] / $rate;
                                        }
                                        elseif($higher && !$wider) {
                                                $height = $imageSize[1] / ($rate = $imageSize[1] / getConfig($type . "_max_height"));
                                                $width = $imageSize[0] / $rate;
                                        }
                                        else {
                                                if($imageSize[0] / getConfig($type . "_max_width") > $imageSize[1] / getConfig($type . "_max_height")) {
                                                        $width = $imageSize[0] / ($rate = $imageSize[0] / getConfig($type . "_max_width"));
                                                        $height = $imageSize[1] / $rate;
                                                }
                                                else {					
                                                        $height = $imageSize[1] / ($rate = $imageSize[1] / getConfig($type . "_max_height"));
                                                        $width = $imageSize[0] / $rate;
                                                }
                                        }
                                }
                                else {
                                	$width = $imageSize[0];
                                	$height = $imageSize[1];
                                }
                                
                                $width = round($width);
                                $height = round($height);
                        					
                                $extension = end(explode(".", $image));
                                switch(strtolower($extension)) {
                                        case "jpg":
                                                $origImage = imageCreateFromJPEG($fromFile);
                                                break;
                                        case "gif":
                                                $origImage = imageCreateFromGIF($fromFile);
                                                break;
                                        case "png":
                                                $origImage = imageCreateFromGIF($fromFile);
                                                break;
                                        case "bmp":
                                                $origImage = imageCreateFromGIF($fromFile);
                                                break;
                                        default:
                                                help("GD does not know what type of image '$image' is.");
                                }
                                if(function_exists("imagecopyresampled") && !getConfig("true_color_and_resample_off_with_gd")) { /* GD2 */
                                        $targetImage = imagecreatetruecolor($width, $height);
                                        imagecopyresampled($targetImage, $origImage, 0, 0, 0, 0, $width, $height, $imageSize[0], $imageSize[1]);
                                }
                                else { /* GD1 setting "slow machine" */
                                        $targetImage = imagecreate($width, $height);
                                        imagecopyresized($targetImage, $origImage, 0, 0, 0, 0, $width, $height, $imageSize[0], $imageSize[1]);
                                }
                                
                                imagejpeg($targetImage, $toFile, getConfig($type . "_image_quality"));
                        }
                        else {
                                help("Neither GD or ImageMagick can be found to make $type" . "s!");
                        }
                }
        }
}

if(!function_exists("printComments")) {
        function printComments($image = false) {
                if(substr_count($image, ".."))
                        return false;
                
		if(!$image && !getConfig("use_archive_comments"))
			return false;

		if($image && !getConfig("use_preview_comments"))
			return false;

                if($image) {
                
	                if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"))) {
	                        $commentFile = file(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"));
	                        if(count($commentFile) >= 4) {
	                                for($i = 0; $i < count($commentFile); $i = $i + 4) { /* Loop through each comment */
	                                        $name = strip_tags(trim($commentFile[$i]));
	                                        $comment = strip_tags(trim($commentFile[$i + 1]));
	                                        $timestamp = strip_tags(trim($commentFile[$i + 2]));
						if(getConfig("encode_comments_to_utf8")) {
							$comment = utf8_encode($comment);
							$name = utf8_encode($name);
						}

	                                        if(!$comment || !$name || !$timestamp )
	                                                return false;
	                                        
	                                        if($timestamp != intval($timestamp))
	                                                return false;
	                                        
	                                        $comments[$timestamp] = array("name" => $name, "date" => date(getConfig("date_format"), $timestamp), "comment" => $comment);
	                        	}
	                        }
	        	}
                }
                else {
	                if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename"))) {
	                        $commentFile = file(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename"));
	                        if(count($commentFile) >= 4) {
	                                for($i = 0; $i < count($commentFile); $i = $i + 4) { /* Loop through each comment */
	                                        $name = strip_tags(trim($commentFile[$i]));
	                                        $comment = strip_tags(trim($commentFile[$i + 1]));
	                                        $timestamp = strip_tags(trim($commentFile[$i + 2]));
						if(getConfig("encode_comments_to_utf8")) {
							$comment = utf8_encode($comment);
							$name = utf8_encode($name);
						}
	                                        
	                                        if(!$comment || !$name || !$timestamp )
	                                                return false;
	                                        
	                                        if($timestamp != intval($timestamp))
	                                                return false;
	                                        
	                                        $comments[$timestamp] = array("name" => $name, "date" => date(getConfig("date_format"), $timestamp), "comment" => $comment);
	                                }	                                
	                        }
	        	}
                }
		
		if(is_array($comments)) {
	                krsort($comments); /* Sort by timestamp desc */
	                                
        	        echo("<br><div class=commentsDiv><b>Comments:</b><br>");
	                foreach($comments as $comment) {
		                if($className == "commentDivEven")
			                $className = "commentDivOdd";
		        	else
			                $className = "commentDivEven";
		                                        
			        echo("<div class=$className><b>Name:</b> " . $comment['name'] . "&nbsp;&nbsp;<b>Date:</b> " . $comment['date'] . "<br>");
				echo("<b>Comment: </b><div class=commentDiv>" . stripslashes($comment['comment']) . "</div></div>");
		        }
		        echo("</div>");
		}
        }
}

if(!function_exists("printCommentSubmit")) {
        function printCommentSubmit($image = false) {
                if(substr_count($image, ".."))
                        return false;

		if($image && !getConfig("use_preview_comments"))
			return false;

		if(!$image && !getConfig("use_archive_comments"))
			return false;

                echo("<script language=javascript>
                function chrLeft() {
                        if(document.comment.comment.value.length > 1024)
                                alert('Comment is too long.');
                                
                }
                </script>");
		if($image)
	                $link = $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "&prev=" . urlencode($image);
		else
			$link = $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR)));

                echo("<form name=comment action=\"" . $link . "\" method=post>");
                if($image)
			echo("<b>Submit your comment to this picture:</b>");
		else
			echo("<b>Submit your comment to these pictures:</b>");
                echo("<table><tr><td><b>Name:</b></td><td><input class=textinput type=text name=name maxlength=25></td></tr>");
                echo("<tr><td><b>Comment:</b><br>(max 1024 chr)</td><td><textarea class=textarea name=comment rows=3 cols=30 onKeyUp=chrLeft()></textarea></td></tr>");
                echo("<tr><td> </td><td><input class=submitinput type=submit value=Send></td></tr></table>");
                echo("</form>");
        }
}

if(!function_exists("collectComment")) {
        function collectComment($image = false) {
                if(fileExistsAndIsReadable(getDir() . "/" . $image) && (($image && getConfig("use_preview_comments") || (!$image && getConfig("use_archive_comments"))))) {
                        if(($name = trim(getVariable("name"))) && ($comment = trim(getVariable("comment"))) && strlen($name) <= 25 && strlen($comment) <= 1024) {
                                $timestamp = time();
                                if(getenv("HTTP_CLIENT_IP"))
                                        $ip=getenv("HTTP_CLIENT_IP");
                                else
                                        $ip=getenv("REMOTE_ADDR");
                                
                                switch(getConfig("log_comment_host")) {
                                        case 0:
                                                $ip = "Not Logged";
                                                break;
                                        case 1:
                                                $ip = md5($ip);
                                                break;
                                }
                                
                                $comment = str_replace("\n", "", $comment);
                                
                                if($name != strip_tags($name) || $comment != strip_tags($comment)) {
                                	echo("<script language=javascript>alert('Your comment or name contained HTML. This is not allowed.');</script>");
                                	return false;
                                }
                                
                                if($image) {
	                                if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"))) { /* Check that last comment isnt the same */
        	                                $commentFile = file(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"));
                	                        if(trim($commentFile[count($commentFile) - 3]) == $comment)
                        	                        return false;
                                	}
                                
	                                if(is_writeable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end")) || is_writeable(getDir() . "/" . getConfig("system_dir") . "/")) {
        	                                $fp = fopen(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"), "a+");
                	                        fwrite($fp, "$name\n$comment\n$timestamp\n$ip\n");
                        	                fclose($fp);
                                	}
	                                else {
        	                                help("Web server cannot write comment to file: '" . substr(getDir(), strlen(START_DIR)) . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end") . "'");
                	                }
                	        }
                	        else {
                	        	if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename"))) { /* check last comment */
                	        		$commentFile = file(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename"));
                	        		if(trim($commentFile[count($commentFile) - 3]) == $comment)
                	        			return false;
                	        	}
                	        	
                	        	if(is_writeable(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename")) || is_writeable(getDir() . "/" . getConfig("system_dir") . "/")) {
                	        		$fp = fopen(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_comments_filename"), "a+");
                	                        fwrite($fp, "$name\n$comment\n$timestamp\n$ip\n");
                        	                fclose($fp);
	
                	        	}
                	        }
			}
                }
        }
}

if(!function_exists("getDescription")) {
        function getDescription($image = false, $when = false) { /* get a description, $when can be either "thumbnail" or "preview" */
				/* $image and $when will be false if called for archive description */
		if(!$when)
			$when = "preview";
		
                if(substr_count($image, ".."))
                        return false;
                
                if($image && !getConfig("use_image_descriptions"))
                	return false;
                
                if(!$image && !getConfig("use_archive_descriptions"))
                	return false;
               	
               	if($image && !fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("description_end")))
               		return false;

               	if(!$image && !fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_description_filename")))
               		return false;
               	
               	
		if($image)
	                $descriptionArray = file(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("description_end"));
		else
			$descriptionArray = file(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("archive_description_filename"));
			
                $descriptionFileContent = implode("", $descriptionArray);
                $description = substr($descriptionFileContent, strpos($descriptionFileContent, "<description>"));
                if(substr_count($description, "</description>"))
                	$description = trim(substr($description, 0, strpos($description, "</description>")));
        		
                if(getConfig("encode_descriptions_to_utf8"))
                        $description = utf8_encode($description);
                        
                if($when == "thumbnail") {
                        $description = strip_tags($description, getConfig("thumbnail_allowed_tags"));
        			
                        $maxLength = getConfig("desription_thumbnail_maxlength");
                        if($maxLength == 0)
                                return false;
                        if($maxLength == 1)
                                return $description;
                        	
                        if(strlen(strip_tags($description)) > $maxLength + 3 && !strlen(getConfig("thumbnail_allowed_tags")))
                                return substr($description, 0, $maxLength) . "...";
                        else
                	        return $description;
                }
                else {
                	if($image)
		                return strip_tags($description, getConfig("preview_allowed_tags"));
		        else
		        	return "<table cellpadding=0 cellspacing=0><tr><td><div class=archiveDescriptionDiv>" . strip_tags($description, getConfig("preview_allowed_tags")) . "</div></td></tr></table>";
                }
                return false;
        }
}

if(!function_exists("printPreview")) {
        function printPreview() {
                $previewFile = getVariable("prev");
                $previewFile = getDir() . "/" . getConfig("system_dir") . "/" . $previewFile . getConfig("preview_end");
                if(fileExistsAndIsReadable($previewFile)) {
                        $images = getFileList("Images");
                        $number = array_search(getVariable("prev"), $images) + 1;
                        
                        if($number - 2 == -1)
                                $previousImage = $images[count($images) - 1];
                        else
                                $previousImage = $images[$number - 2];
                        
                        if($number == count($images))
                                $nextImage = $images[0];
                        else
                                $nextImage = $images[$number];
                        
                        if(getConfig("next_arrow") && fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("next_arrow")))
                                $nextArrow = "<img alt=\"Next image\" src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("next_arrow") . "\">";
                        else
                                $nextArrow = "Next";
        
                        if(getConfig("previous_arrow") && fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("previous_arrow")))
                                $previousArrow = "<img alt=\"Previous image\" src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("previous_arrow") . "\">";
                        else
                                $previousArrow = "Previous";
                        
                        if(getConfig("click_on_thumbnail") != 2) { /* is not a popupbox */
	                        if(getConfig("up_arrow") && fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("up_arrow")))
        	                        $upArrow = "<img alt=\"Back to thumbnails\" src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("up_arrow") . "\"> Back";
                	        else
                        	        $upArrow = "Back";
                        }
                        
                        echo("<div class=navigationdiv>");
                                
                        echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "&prev=" . urlencode($previousImage) . "\">$previousArrow</a>&nbsp;");
                        echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "&prev=" . urlencode($nextImage) . "\">$nextArrow</a>&nbsp;&nbsp;");
                        echo(" " . $number . "/" . count($images) . " ");                        
                        echo("&nbsp;&nbsp;<b>" . getVariable("prev") . "</b>&nbsp;&nbsp;");
                        echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "\"><b>$upArrow</b></a>&nbsp;&nbsp;");
                        
                        if(function_exists("getimagesize")) {
                                $imageSize = getimagesize(getDir() . "/" . getVariable("prev"));
                                if($imageSize[0])
                                        $imageDimensions = $imageSize[0] . "x" . $imageSize[1];
                        }
                        
                        echo(" <a href=\"" . getDir() . "/" . getVariable("prev") . "\">Fullsize image ($imageDimensions " . getNiceFilesize(getDir() . "/" . getVariable("prev")) . ")</a>");
        
                        echo("</div>");
                        $previewClass = "class=preview ";
        
                        switch(getConfig("click_on_image")) {
                                case 1:
                                        echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "\">");
                                        break;
                                
                                case 2:
                                        echo(" <a href=\"" . getDir() . "/" . getVariable("prev") . "\">");
                                        break;
                        }
                        echo("<img $previewClass" . "src=\"$previewFile\" alt=\"" . getDescription(getVariable("prev"), "preview") . "\">");
                        if(getConfig("click_on_image"))
                                echo("</a>");
                        
                        echo("<div class=descriptiondiv>");
                        echo(getDescription(getVariable("prev"), "preview"));		
                        echo("</div>");
                        
                        collectComment(getVariable("prev"));	
                        printComments(getVariable("prev"));
                        printCommentSubmit(getVariable("prev"));
                }
                else {
                        echo("<b>Sorry, the file you are looking for isn't here. Click <a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . substr(getDir(), strlen(START_DIR)) . "\">here</a> to return to filelisting.</b>");
                }
        }
}

if(!function_exists("getNiceFileSize")) {
        function getNiceFilesize($file) {
                                $unitType = explode(" ", getConfig("filesize_units"));
                                $filesize = filesize($file);
                                for ($i = 0; $filesize >= 1024; $i++)
                                        $filesize /= 1024;
                                return round ($filesize) . $unitType[$i];
        }
}

if(!function_exists("printPageChooser")) {
	function printPageChooser($imagePages, $allImages) {
		if(getConfig("thumbnails_per_page") && count($allImages) > getConfig("thumbnails_per_page")) { /* Pages needed*/
			echo("Pages: ");
			if(is_array($imagePages[getVariable("page") - 1])) {
				if(getConfig("previous_arrow") && fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("previous_arrow")))
					$previousArrow = "<img src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("previous_arrow") . "\" alt=\"Previous page\">";
				else
					$previousArrow = "Previous";
				
				echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . substr(getDir(), strlen(START_DIR)) . "&page=" . (getVariable("page") - 1) . "\">$previousArrow</a> ");
			}
			for($i = 0; $i < count($imagePages); $i++) {
				if(!$i) {
					$link = $_SERVER["PHP_SELF"] . "?dir=" . substr(getDir(), strlen(START_DIR));
				}
				else {
					$link = $_SERVER["PHP_SELF"] . "?dir=" . substr(getDir(), strlen(START_DIR)) . "&page=$i";
				}
				echo(" <a href=\"" . $link . "\">");
				if(getVariable("page") == $i)
					echo("<span class=choosedPage>" . ($i + 1) . "</span>");
				else
					echo($i + 1);
				echo("</a> ");
			}
			if(is_array($imagePages[getVariable("page") + 1])) {
				if(getConfig("next_arrow") && fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("next_arrow")))
					$nextArrow = "<img src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("next_arrow") . "\" alt=\"Next Page\">";
				else
					$nextArrow = "Next";
				
				echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . substr(getDir(), strlen(START_DIR)) . "&page=" . (getVariable("page") + 1) . "\">$nextArrow</a>");
			}
			
			echo("<br>&nbsp;<br>");
		}
	}
}

if(!function_exists("printListImages")) {
        function printListImages() {
                if(end(explode("/", getDir())) == getConfig("system_dir")) {
                        echo("<b>Bad directory!</b>");
                        return false;
                }
                $allImages = getFileList("Images");
                if(getConfig("thumbnails_per_page") && count($allImages) > getConfig("thumbnails_per_page")) { /* Pages needed */
			$imagePages = array_chunk($allImages, getConfig("thumbnails_per_page"));

	                if(!is_array($imagePages[getVariable("page")])) { /* page does not exist */
        	        	$images = $imagePages[0];
	                }
	                else {
		                $images = $imagePages[getVariable("page")];
		        }
                }
                else
                	$images = $allImages;
	        
	        printPageChooser($imagePages, $allImages);
	  	
                if(is_array($images)) {
			echo("<table cellspacing=0 cellpadding=0><tr><td>");
                        foreach($images as $image) {
                                if(!fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("thumbnail_end"))) {
                                        createImage($image, "thumbnail");
                                }
                                if(getConfig("use_previews") && isimage($image) && !fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("preview_end"))) {
                                        createImage($image, "preview");
                                }
        
                                $floatStyle = "style=\"float:left; width: " . getConfig("column_width") . "; height: " . getConfig("column_height") . "\"";
                                $column++;
                                if(getConfig("image_columns") && $column >= getConfig("image_columns")) {
                                        $floatStyle = "style=\"width: " . getConfig("column_width") . "; height: " . getConfig("column_height") . "\"";
                                        $column = 0;
                                }
                                
                                $filesize = getNiceFilesize(getDir() . "/" . $image);
                                
                                $descriptionAndComment = "";
                                if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("description_end"))) {
                                        $descriptionAndComment = "(D";
                                }
                                if(fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("comments_end"))) {
                                        if($descriptionAndComment)
                                                $descriptionAndComment .= "/C)";
                                        else
                                                $descriptionAndComment = "(C)";
                                }
                                elseif($descriptionAndComment)
                                        $descriptionAndComment .= ")";
                                
                                $filename = $image;	
                                $filenameFormat = str_replace("%filename", $filename, getConfig("image_filename_format"));
                                $filenameFormat = str_replace("%descriptionAndComment", $descriptionAndComment, $filenameFormat);
                                $filenameFormat = str_replace("%filesize", $filesize, $filenameFormat);
                                
                                if($imageDiv == "imageDivEven")
                                        $imageDiv = "imageDivOdd";
                                else
                                        $imageDiv = "imageDivEven";
                                
                                echo("\n<div $floatStyle class=" . $imageDiv . ">");
                                echo("<table cellspacing=0 cellpadding=0><tr><td>");
                                if(isimage($image) && getConfig("use_previews"))
                                	switch(getConfig("click_on_thumbnail")) {
                                		case 1:
                                        		echo("<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "&prev=" . urlencode($image) . "\">");
                                        		break;
                                        	
                                        	case 2:
                                        		if(getConfig("popup_width"))
                                        			$popupWidth = getConfig("popup_width");
                                        		else
                                        			$popupWidth = getConfig("preview_max_width") + 30;
                                        			
                                        		if(getConfig("popup_height"))
                                        			$popupHeight = getConfig("popup_height");
                                        		else
                                        			$popupHeight = getConfig("preview_max_height") + 100;
                                        		
                                        		echo("<a href=# onClick=\"window.open('" . $_SERVER["PHP_SELF"] . "?dir=" . urlencode(substr(getDir(), strlen(START_DIR))) . "&page=" . getVariable("page") . "&prev=" . urlencode($image) . "', 'Preview','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,width=$popupWidth,height=$popupHeight');\">");
                                        		break;
					}
                                else
                                        echo("<a href=\"" . getDir() . "/" . $image . "\">");
                                echo("<img src=\"" . getDir() . "/" . getConfig("system_dir") . "/" . $image . getConfig("thumbnail_end") . "\" class=thumbnail>");

                                if(getConfig("click_on_thumbnail")) /* Do not end link if it is no link */
                                	echo("</a>");
                                
                                echo("</td><td><div class=thumbnailDescriptionDiv>" . getDescription($image, "thumbnail") . "</div></td></tr><tr><td colspan=2>$filenameFormat</td></tr></table></div>\n");
                        }
			echo("</td></tr><tr><td>");
			
  			printPageChooser($imagePages, $allImages);
			
			echo("<table><tr><td valign=top>");
			if(getConfig("use_archive_comments")) {
				collectComment();
				printComments();
				printCommentSubmit();
			}
			echo("</td><td valign=top>");
	                printImageSubmit();
	                echo("</td></tr></table>");
			
			echo("</td></tr></table>");
                }
                else {
                        echo("No images found");
                        if(is_dir(getDir())) /* Dont put uploadbox in unreadable folders */
	                        printImageSubmit();
                }
        }
}

if(!function_exists("printImageSubmit")) {
	function printImageSubmit() {
		if(!getConfig("enabled", "upload", false))
			return false;
		$unitType = explode(" ", getConfig("filesize_units"));
		if(!$maxSize = getConfig("maxsize", "upload", false))
			$maxSize = ini_get("post_max_size");
		
		if(!is_int($maxSize)) {
			$unitTypeStart = substr($maxSize, strlen(intval($maxSize)), 1);
			if($unitTypeStart == "K" || $unitTypeStart == "k")
				$maxSize *= 1024;
			elseif($unitTypeStart == "M" || $unitTypeStart == "m")
				$maxSize *= 1024*1024;
			elseif($unitTypeStart == "G" || $unitTypeStart == "g")
				$maxSize *= 1024*1024*1024;			
			elseif($unitTypeStart == "T" || $unitTypeStart == "t")
				$maxSize *= 1024*1024*1024*1024;			
		}

		for ($i = 0; $maxSize >= 1024; $i++)
       	        	$maxSize /= 1024;
               	$maxSizeStr = round($maxSize) . $unitType[$i];	

                echo("<form name=images enctype=\"multipart/form-data\" method=post>");
		echo("<b>Upload your images:</b>");
                echo("<table>");
		if(getConfig("password", "upload", false))
			echo("<tr><td><b>Password:</b></td><td><input class=textinput type=password name=uploadimagep></td></tr>");
                echo("<tr><td><b>File:</b><br>(max $maxSizeStr)</td><td><input type=file name=uploadimagefile class=textinput></td></tr>");

		if(getConfig("allow_new_folder", "upload", false)) {
			if(!$newFolderText = getConfig("new_folder_text", "upload", false))
				$newFolderText = "<b>New Folder:</b>";
			echo("<tr><td><b>$newFolderText</b></td><td><input type=text name=uploadimagefolder class=textinput></td></tr>");
		}
                echo("<tr><td> </td><td><input class=submitinput type=submit value=Upload></td></tr></table>");
                echo("</form>");

	}
}

if(!function_exists("collectImages")) {
	function collectImages() {
		if(!getConfig("enabled", "upload", false))
			return false;

		$uploadedArray = getVariable("uploadimagefile", "files"); /* Make a nice array */
		
		if(!$uploadedArray['tmp_name']) /* any uploaded file? */
			return false;
			
		$password = getConfig("password", "upload", false);
		if(strlen($password)) {
			$userpassword = getVariable("uploadimagep");
			switch(getConfig("password_crypted_level", "upload", false)) {
				case 1:
					if(md5($userpassword) == $password)
						break;
					else {
						error("Wrong password!");
						return false;
						break;
					}
				case 2:
					if(crypt($userpassword, $password) == $password)
						break;
					else {
						error("Wrong password!");
						return false;
						break;
					}
				default:
					if($userpassword == $password)
						break;
					else {
						error("Wrong password!");
						return false;
						break;
					}
			}
		}
		
		$unitType = explode(" ", getConfig("filesize_units")); /* Get file max size */
		if(!$maxSize = getConfig("maxsize", "upload", false))
			$maxSize = ini_get("post_max_size");
		
		if(!is_int($maxSize)) {
			$unitTypeStart = substr($maxSize, strlen(intval($maxSize)), 1);
			if($unitTypeStart == "K" || $unitTypeStart == "k")
				$maxSize *= 1024;
			elseif($unitTypeStart == "M" || $unitTypeStart == "m")
				$maxSize *= 1024*1024;
			elseif($unitTypeStart == "G" || $unitTypeStart == "g")
				$maxSize *= 1024*1024*1024;			
			elseif($unitTypeStart == "T" || $unitTypeStart == "t")
				$maxSize *= 1024*1024*1024*1024;			
		}

		if($uploadedArray["size"] > $maxSize) { /* check size */
			error("Uploaded file too big!");
			return false;
		}
		
		if(getConfig("allowed_characters", "upload", false)) {
			$allowedCharacters = getConfig("allowed_characters", "upload");
			$filename = $uploadedArray['name'];
			for($i = 0; $i < strlen($filename); $i++) {
				if(strpos($allowedCharacters, $filename{$i}) === false) {
					error("Filename contains disallowed charachters.");
					return false;
				}
			}
			$filename = getVariable("uploadimagefolder");
			for($i = 0; $i < strlen($filename); $i++) {
				if(strpos($allowedCharacters, $filename{$i}) === false) {
					if(getConfig("new_folder_error_text", "upload", false))
						error(getConfig("new_folder_error_text", "upload", false));
					else
						error("Directory name contains disallowed charachters.");
					return false;
				}
			}
		}
		else {
			help("You dont have the 'allowed_characters'-setting. This will probably produce errors.");
			return false;
		}
		
		/* If zipfile... Function open_zip only works in some php-versions.
		if(function_exists("zip_open"))
			if($uploadedArray['type'] != "application/x-zip-compressed" && $uploadedArray['type'] != "application/zip") {
				if($zip = zip_open($uploadedArray['tmp_name'])) {
				
				}
				else {
					error("Cannot read zipfile!");
				}
			}
		*/
		
		if(!checkUploadedExtension($uploadedArray['name'])) { /* check extension */
			error("File not accepted!");
			return false;
		}
		
		if(substr($uploadedArray['name'], -1) == ".") {
			error("File cannot start with '.'");
			return false;
		}
		
		if(getVariable("uploadimagefolder") && getConfig("allow_new_folder", "upload", false)) {
			if(getVariable("uploadimagefolder") == getConfig("system_dir")) { /* Dont upload files to system_dir */
				error("Bad directory name.");
				return false;
			}
			if(substr(getVariable("uploadimagefolder"), -1) == ".") {
				error("Directory cannot start with '.'");
				return false;
			}
			if(!file_exists(getDir() . "/" . getVariable("uploadimagefolder"))) {
				if(!@mkdir(getDir() . "/" . getVariable("uploadimagefolder"), 0775)) {
					error("Error creating directory!");
					return false;
				}
			}
		}
		if(file_exists(getDir() . "/" . getVariable("uploadimagefolder") . "/" . $uploadedArray['name'])) {
			error("File already exists!");
			return false;
		}
		if(!is_writable(getDir() . "/" . getVariable("uploadimagefolder") . "/")) {
			help("Web server cannot write the uploaded file. Check permissions.");
			//No return false, more errorinfo is printed by "move_uploaded_file"
		}
		
		if(!move_uploaded_file($uploadedArray['tmp_name'], getDir() . "/" . getVariable("uploadimagefolder") . "/" . $uploadedArray['name'])) {
			error("Cannot move the uploaded file.");
		}
		else {
			/* File successfully uploaded */
		}
	}
}

if(!function_exists("checkUploadedExtension")) {
	function checkUploadedExtension($file) {
		$extension = strtolower(end(explode(".", $file))); /* take extension of file and make it lower case */
		
		if(getConfig("allowed_files", "upload", false)) {
			$allowedExtensions = explode(" ", strtolower(getConfig("allowed_files", "upload", false)));
			if(in_array($extension, $allowedExtensions))
				return true;
			else
				return false;
		}
		elseif(getConfig("disallowed_files", "upload", false)) {
			$disallowedExtensions = explode(" ", strtolower(getConfig("disallowed_files", "upload")));
			if(in_array($extension, $disallowedExtensions))
				return false;
			else
				return true;
		}
		elseif(!getConfig("allow_all_filetypes", "upload", false)) {
			help("You probably dont want to accept ALL uploaded filetypes. Set the disallowed_files-setting or even better; set the allowed_files-setting. If you REALLY want to accept all filetypes then set the allow_all_filetypes-setting to true.");
			return false;
		}
		
		return true;
	}
}

if(!function_exists("printListFiles")) {
        function printListFiles() {
		if(end(explode("/", getDir())) == getConfig("system_dir")) {
                        return false;
                }

                $files = getFileList("Files");
                if(is_array($files)) {
                        foreach($files as $file) {
                    		if($fileDiv == "fileDivOdd")
                    			$fileDiv = "fileDivEven";
                    		else
                    			$fileDiv = "fileDivOdd";
								
                                $extension = end(explode(".", $file));
                                echo("<div class=$fileDiv>");
                                if(getConfig(strtolower($extension), "icons", false))
                                        echo("<img src=\"" . START_DIR . "/" . getConfig("system_dir") . "/" . getConfig(strtolower($extension), "icons", false) . "\">&nbsp;");
                                else
                                        if(fileExistsAndIsReadable(START_DIR . "/" . getConfig("system_dir") . "/" . getConfig("empty", "icons", false)))
                                                echo("<img src=\"" . getConfig("system_dir") . "/" . getConfig("empty", "icons", false) . "\">&nbsp;");

                                $filesize = getNiceFilesize(getDir() . "/" .  $file);
				
				$filenameFormat = getConfig("file_filename_format");
				$filenameFormat = str_replace("%filename", $file, $filenameFormat);
				$filenameFormat = str_replace("%filesize", $filesize, $filenameFormat);

                                echo("<a href=\"" . getDir() . "/" .  $file . "\">$filenameFormat</a></div>");
                        }
                }
                else {
                        /* no files found */
                }
                
        }
}

if(!function_exists("getFileList")) {
        function getFileList($type) { /* Returns array with files. if $type is "Images" image-files are returned. if $type is "Files" non-images are returned */
                $strDir = getDir();
                $hideFilesStartingWith = explode(" ", getConfig("hide_files_starting_with")); /* Make an array of startings */
                $hideFilesEndingWith = explode(" ", getConfig("hide_files_ending_with")); /* Make an array of endings */
                if(!$strDir)
                        if(!$strDir = START_DIR)
                                $strDir = ".";
                
                if ($dir = @opendir($strDir)) {
                        while(false !== ($file = readdir($dir))) {
                                $hide = false;
                                if($file == "." || $file == "..")
                                        $hide = true;
        
                                if(!$hide && is_array($hideFilesStartingWith)) {
                                        foreach($hideFilesStartingWith as $start) {
                                                if(strlen($start) && substr($file, 0, strlen($start)) == $start) {
                                                        $hide = true;
                                                }
                                        }
                                }
        	
                                if(!$hide && is_array($hideFilesEndingWith)) {
                                        foreach($hideFilesEndingWith as $end) {
                                                if(strlen($end) && substr($file, strlen($end) * -1) == $end) {
                                                        $hide = true;
                                                }
                                        }
                                }
        	
                                
                                if(!$hide) {
                                        if(!is_dir($strDir . "/" . $file)) {
                                                $files[] = $file;
                                        }
                                }
                        }
                        
                        if(is_array($files)) {
                                foreach($files as $file) {				
                                        if($type == "Images" && (isImage($file) || fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . $file . getConfig("thumbnail_end")))) {
                                                $images[] = $file;
                                        }
                                        elseif($type == "Files" && !isImage($file)) {
                                                $notImages[] = $file;
                                        }
                                        else {
                                                $allFiles[] = $file;
                                        }
                                }
                        }
                        else {
                                /* No files found in folder */
                        }
                }
                else {
                        $errorDir = substr($strDir, strlen(START_DIR));
                        if($type == "Images") { /* Show only once */
                                echo("<b>Directory '$errorDir' could not be read.</b><br>");
                                return false;
                        }
                }
                
                if($type == "Images") {
                        if(is_array($images)) {
	                        switch(getConfig("sort_images")) {
		                        case 1:
		                        	natcasesort($images);
		                        	break;
		                        case 2:
		                               	natcasesort($images);
				                $images = array_reverse($images);
		                        	break;
		                        case 3:
		                        	sort($images);
		                        	break;
		        	}
                        }
			return $images;
                }
                elseif($type == "Files") {
                	if(is_array($notImages)) {
	                        switch(getConfig("sort_files")) {
		                        case 1:
		                        	natcasesort($notImages);
		                        	break;
		                        case 2:
		                               	natcasesort($notImages);
				                $notImages = array_reverse($notImages);
		                        	break;
		                        case 3:
		                        	sort($notImages);
		                        	break;
		                }
		        }
                        return $notImages;
                }
                else
                        return $allFiles;
        }
}

if(!function_exists("printHeader")) {
        function printHeader() {
                if(getOS() == "UNIX")
                        $directorySeparator = "/";
                if(getOS() == "Windows")
                        $directorySeparator = "\\";
                
                $title = end(explode($directorySeparator, getDir()));
		if($title == START_DIR)
			$title = getConfig("gallery_name");
                
                if(getConfig("header"))
                        header(getConfig("header"));
                
                echo("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
                <html>
                <head>
                " . getStyle() . "
                <title>GIS : " . $title . "</title>\n</head><body>\n");
        }
}

if(!function_exists("printFooter")) {
        function printFooter() {
                echo("<b><a href=\"http://gis.gussoh.com/\">GIS " . getConfig("version") . "</a></b>");
                echo("</body>\n</html>");
        }
}

if(!function_exists("getVariable")) {
        function getVariable($name, $type = false) { /* Used to fetch a GET, POST or a globally registered variable  !! use getConfig() to get configurations !! */
							/* use getVariable($name, "files") to get a file! */
                /* Use getDir() to get the "dir"-variable! */
		
		if($type == "get")
			return $_GET["$name"];
		elseif($type == "post")
			return $_POST["$name"];
		elseif($type == "files")
			return $_FILES["$name"];
		elseif($type)
			help("$type is not defined in function getDir()");
		
                if($_POST[$name])
                        return $_POST[$name];
                
                if($_GET[$name])
                        return urldecode($_GET[$name]);
                
                global $$name;
                if($$name)
                        return urldecode($$name);
        }
}

if(!function_exists("getConfig")) {
        function getConfig($key, $group = false, $help = true) { /* Used to get a Configuration-value */
                global $conf;
                global $conffile;
                global $archiveConfig;	
                static $triedConffile;
                static $triedArchiveConfig;
                
                if(!isset($conffile) && !$triedConffile) {
                        $triedConffile = true;
                        if(fileExistsAndIsReadable(CONFIG_FILE)) {
                        	if(strtolower(end(explode(".", CONFIG_FILE))) == "php") {
	                        	$file = file(CONFIG_FILE);
	                        	if(substr($file[0], 0, 6) != ";<?php") {
	                        		$file = implode("\n", $file);
	                        		if(strpos($file, "password"))
		                        		help("Your " . CONFIG_FILE . " is not protected. The first line should be ';<?php die('You are not allowed to read this file! ;'); ?>' without the first surrounding single quotes.");
	                        	}
	                        }
                                $conffile = parse_ini_file(CONFIG_FILE, true);
                        }
                }
        
                if(!isset($archiveConfig) && !$triedArchiveConfig) {
                        $triedArchiveConfig = true;
                        if(getDir() && fileExistsAndIsReadable(getDir() . "/" . CONFIG_FILE))
                        	if(strtolower(end(explode(".", getDir() . "/" . CONFIG_FILE))) == "php") {
	                        	$file = file(getDir() . "/" . CONFIG_FILE);
	                        	if(substr($file[0], 0, 6) != ";<?php") {
	                        		$file = implode("\n", $file);
	                        		if(strpos($file, "password"))
		                        		help("Your " . getDir() . "/" . CONFIG_FILE . " is not protected. The first line should be ';<?php die('You are not allowed to read this file! ;'); ?>' without the first surrounding single quotes.");
	                        	}
	                        }
                                $archiveConfig = parse_ini_file(getDir() . "/" . CONFIG_FILE, true);
                }
                
                if($group) {
                        if(isset($archiveConfig[$group][$key]))
                                return $archiveConfig[$group][$key];
                        elseif(isset($conffile[$group][$key]))
                                return $conffile[$group][$key];
                        elseif(isset($conf[$group][$key]))
                                return $conf[$group][$key];
                        else {
                                if($help)
                                        help("Setting '$key' in group '$group' does not exist!");
                                return false;
                        }
                }
                else {
                        if(isset($archiveConfig[$key]))
                                return $archiveConfig[$key];
                        elseif(isset($conffile[$key]))
                                return $conffile[$key];
                        elseif(isset($conf[$key]))
                                return $conf[$key];
                        else
                                if($help)
                                        help("Setting '$key' does not exist!");
        
                        return false;
                }
        
                return false;
        }
}

if(!function_exists("getOS")) {
        function getOS() { /* Not done, returns "UNIX" */
                return "UNIX";
                return "Windows";
                /* php_uname() is a good function ;) */
        }
}

if(!function_exists("getStyle")) {
        function getStyle() {
                if(getConfig("style") && getDir() && fileExistsAndIsReadable(getDir() . "/" . getConfig("system_dir") . "/" . getConfig("style")))
                        return "<link rel=stylesheet href=\"" . getDir() . "/" . getConfig("system_dir") . "/" . getConfig("style") . "\">";
        
                if(fileExistsAndIsReadable(getConfig("system_dir") . "/" . getConfig("style")) && getConfig("system_dir") . "/" . getConfig("style") != "/")
                        return "<link rel=stylesheet href=\"" . getConfig("system_dir") . "/" . getConfig("style") . "\">";
                else
                        return "
                        <style>
                                body {background-color: black; font-family: verdana, arial, helvetica, sans-serif; font-size: 11px; color: white}
                                td {font-size: 11px;}
                                img {border: 0;}
                                a {color: white; border: 0; text-decoration: none}
                                a:visited {color: #BBBBBB}
                                a:hover {color: #EEEEEE; text-decoration: underline}
                                
                                .unreadable { color: #666666 }
                                
                                .imageDivOdd { }
                                .imageDivEven { }
                                                                
                                .thumbnaildescriptiondiv { }
                                .archiveDescriptionDiv { font-size: 20px; margin: 20px; font-wieght: bold; }
                                
                                .directoryDiv {width: 270; }
                                
                                .fileDivEven { width: 160; background-color: #222222 }
                                .fileDivOdd { width: 160; }
                                
                                .descriptionDiv { background-color: #111111; padding: 4px; border: 1px dashed #666666; }
                                .navigationDiv { background-color: #111111; padding: 4px; border: 1px dashed #666666; }
                                
                                .thumbnail { border-top: 1px solid #AAAAAA; border-left: 1px solid #BBBBBB; border-right: 1px solid #555555; border-bottom: 1px solid #666666; }
                                .preview { border-left: 1px dashed #666666; border-right: 1px dashed #666666;}
                                
                                .commentDivOdd { background-color: #000000; border: 1px dashed #666666; color: #CCCCCC }
                                .commentDivEven { background-color: #222222; color: #CCCCCC }
                                .commentDiv { padding: 4px; color: #FFFFFF }
                                
                                .choosedPage { background-color: #AAAAAA; color: black; padding: 2px }
                                
                                .submitinput {color: white; background-color: black; border: 1px dashed #666666; width:200px; }
                                .textinput {color:white; background-color: black; border: 1px dashed #666666; font-family: verdana, arial, helvetica, sans-serif; font-size: 11px; width: 200px }

                                textarea {color:white; background-color: black; border: 1px dashed #666666; font-family: verdana, arial, helvetica, sans-serif; font-size: 11px; width: 200px; }
                        </style>
                        ";
        }
}

if(!function_exists("help")) {
        function help($message) { /* Pushes a helpmessage to the helpmessagelist */
                if(!getConfig("helpful")) {
                        return false;
                }
                global $helpMessages; /* global array with all collected help messages */
                if(!(is_array($helpMessages) && in_array($message, $helpMessages))) /* Help message is not added if it already exists */
                        $helpMessages[] = $message;
        }
}

if(!function_exists("printHelp")) {
        function printHelp() { /* Displays all help messages collected on the page */
                global $helpMessages;
                if(is_array($helpMessages)) {
                        foreach($helpMessages as $helpMessage)
                                $helpMessagesStr .= "\\n" . $helpMessage . "\\n";
                        
                        echo("<script language=javascript>alert(\"Help: $helpMessagesStr \\nSetting 'helpful' to false turns off help. \\nMore help can sometimes be found on http://gis.gussoh.com/\")</script>");
                }
        }
}

if(!function_exists("error")) {
        function error($message) { /* Pushes a errormessage to the errormessagelist */
                global $errorMessages; /* global array with all collected error messages */
                if(!(is_array($errorMessages) && in_array($message, $errorMessages))) /* error message is not added if it already exists */
                        $errorMessages[] = $message;
        }
}

if(!function_exists("printErrors")) {
        function printErrors() { /* Displays all error messages collected on the page */
                global $errorMessages;
                if(is_array($errorMessages)) {
                        foreach($errorMessages as $errorMessage)
                                $errorMessagesStr .= "\\n" . $errorMessage . "\\n";
                        
                        echo("<script language=javascript>alert(\"Error: $errorMessagesStr\")</script>");
                }
        }
}

if(!function_exists("printMain")) {
        function printMain() {
                $layout = getConfig("layout");
                printUsertag();
		collectImages(); /* Store uploaded files */
                
                if($layout == "gis1") {
                        if(getVariable("prev")) {
                                echo("<table><td valign=top>");
                                printPreview();
                                echo("</td></tr></table>");
                        }
                        else {
				echo(getDescription());
                                echo("<div class=directoryDiv>");
				printListDirectories();
				echo("</div>");
                                printListFiles();
                                echo("<br><table cellspacing=0 cellpadding=0><tr><td>");
                                printListImages();
                                echo("</td></tr></table>");
                        }
                }
                else { /* GIS 2 layout */
                        if(getVariable("prev")) {
                        	if(getConfig("click_on_thumbnail") != 2) { /* it is not a popup window */
	                                echo("<table><td valign=top>"); /* Directory listing start*/
	                                echo("<div class=directoryDiv>");
					printListDirectories();
	                                echo("</div>");
					echo("</td><td> </td><td valign=top>"); /* Directory listing stops, preview starts */
				}
				else {
					echo("<table><td valign=top>");
				}
                                printPreview();
                                echo("</td></tr></table>"); /* preview stops */
                        }
                        else {
                                echo("<table><td valign=top>");
                                echo("<div class=directoryDiv>");
                                printListDirectories();
                                echo("</div>");
				echo("</td><td valign=top>");
                                echo("<table><tr><td colspan=2>" . getDescription() . "</td><tr><td valign=top>");
				printListFiles();
				echo("</td><td valign=top>");
                                printListImages();
				echo("</td></tr></table>");
                                echo("</td></tr></table>");
                        }
                }
        }
}

if(!function_exists("runGIS")) {
        function runGIS() {
                @set_time_limit(getConfig("max_execution_time"));
                printHeader();
                printMain();
                printHelp();
                printErrors();
                printFooter();
        }
}

/*      END OF FUNCTIONS */

/*      RUN GIS */
        
	runGIS();

/*      END OF RUN GIS  */

?>
