#!/usr/bin/perl
   
use CGI qw(:standard) ;

############################################
##                                        ##
##            Schlabo's Scripts           ##
##             by Andreas Jakl            ##
##      (e-mail andreas@schlabo.com)      ##
##                                        ##
##             version:  2.01a            ##
##         last modified: 17/02/02        ##
##         copyright (c) 1999-2002        ##
##                                        ##
##    latest version is available from    ##
##         http://www.schlabo.com/        ##
##                                        ##
############################################

# COPYRIGHT NOTICE:
#
# Copyright 1999-2001 Andreas Jakl.  All Rights Reserved.
#
# This program is being distributed as freeware.  It may be used and
# modified by anyone, as long as this copyright notice and the header
# above remain intact Selling the code for this program without prior
# written consent is expressly forbidden.  Obtain permission before
# redistributing this program over the Internet or in any other medium.
# In all cases copyright and header must remain intact.
#
# This program is distributed "as is" and without warranty of any
# kind, either express or implied.  (Some states do not allow the
# limitation or exclusion of liability for incidental or consequential
# damages, so this notice may not apply to you.)  In no event shall
# the author of this script, Andreas Jakl, be liable for any damages or
# losses. You use this script on your own risk.

# If your server reports that it can't find or include the config-file
# or if you have problems getting the scripts to run, change the 
# following variable to the absolute server-path of the Schlabo's Scripts-
# directory. Normally this is not necessary, but some servers don't look
# in the current directory when a file is included, so you have to specify
# it yourself. To make that easier you can use this variable instead of
# modifying each require-statement. Don't use a trailing slash ("/").
$require_path = substr($ENV{'SCRIPT_FILENAME'},0,rindex($ENV{'SCRIPT_FILENAME'},"/"));

# If you are using Microsoft IIS, set the following to 1. If you are
# using Unix/Apache, set it to 2. Setting it 0 tries to determine
# automatically, and usually works just fine; don't change it unless
# you have problems. If you use IIS yet have 500 error problems, 
# try setting the variable to 2, then try 3.
# Thanks to NewsPro ( http://amphibian.gagames.com/newspro ) for this routine!
$IIS = 0;

# You don't have to modify anything below here.
if ($IIS != 2) {
	if ($IIS == 0) {
		if ($ENV{'SERVER_SOFTWARE'} =~ m!IIS!) {
			$IIS = 1 
		}
	}
	if (($IIS) && ($0 =~ m!(.*)(\\|\/)!)) {
		chdir($1);
	}
	if ($IIS == 1) {
		print "HTTP/1.0 200 OK\n";
	}
}

if ($require_path) {
	push(@INC, $require_path);
}
require "config.pl";
require "common.pl";

$scriptname="admin";

umask (0111);

&check_referer;
&parse_query;
&get_date;
eval { &get_script_actions; };
if ($@) {
	&showerror("An error occured: $@");
}
exit;

sub get_script_actions {
	# Query and Form Actions
	$dowhat=$QUERY{'action'};
	
	if (($dowhat ne 'login') && ($dowhat ne '') && ($dowhat ne 'logout') && ($dowhat ne 'firsttime_user')) {
		&get_password;
	}
	if ($dowhat eq 'login') { &showlogin; }
	elsif ($dowhat eq 'logout') { &logout; }
	elsif ($dowhat eq 'showadmin') { &showadmin; }
	elsif ($dowhat eq 'conf_general') { &confgeneral; }
	elsif ($dowhat eq 'submit_gen') { &submitgen; } 
	elsif ($dowhat eq 'conf_potd') { &confpotd; }
	elsif ($dowhat eq 'submit_potd') { &submitpotd; }
	elsif ($dowhat eq 'conf_dl') { &confdl; }
	elsif ($dowhat eq 'submit_dl') { &submitdl; }
	elsif ($dowhat eq 'conf_sp') { &confsp; }
	elsif ($dowhat eq 'submit_sp') { &submitsp; }
	elsif ($dowhat eq 'conf_cow') { &confcow; }
	elsif ($dowhat eq 'submit_cow') { &submitcow; }
	elsif ($dowhat eq 'updates') { &checkupdates; }
	elsif ($dowhat eq 'viewiplog') { &viewiplog; }
	elsif ($dowhat eq 'firsttime_user') { &firsttime_user; }
	elsif ($dowhat eq '') {
		if ($siteurl eq 'http://www.yoursite.com/') {
			&firstrun;
		} else {
			&showlogin;
		}
	} else {
		&novalidquery;
	}
}

sub showadmin {
	&html_header;
	print "<br><font size=3 color=\"#FFCC00\"><b>Main</b></font><br><br>\n";
	$curtimecode = &calculatetimecode($y,$m,$month_day);
	if ($curtimecode > ($g_updatecheck + 30)) {
		print qq|
		<form action="$server_url$g_admin_url?action=updates" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<font size=2 face="Verdana, Arial, Helvetica" color="#FFCC00">Update Reminder</font><br><hr noshade>
		It has been more than one month since you last checked for an update of Schlabo's Scripts.<br>
		Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to do so now!<hr noshade></form>
		<br>
		|;
	}	
	print qq|
	You can use this script to configure all the scripts of Schlabo's Scripts. Choose below what you'd like to do:</p>
	|;
	if (index($images_url,"yoursite.com") > (-1)) {
		print qq|
		<form action="$server_url$g_admin_url?action=conf_general" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		It appears that the URL of the Schlabo's Scripts interface-images is not configured correctly. Please click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to specify the correct URL of them.</form>
		|;
	}
	print qq|
	</font><br><font size=2 face="Verdana, Arial, Helvetica" color="#FFCC00">Configuration</font><br><hr noshade>
	<table><tr><form action="$server_url$g_admin_url?action=conf_general" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	<input type="image" name="schlabosscripts" src="${images_url}n_general.gif" width=56 height=14 alt="General Configuration"></td></form>
	</tr>
	|;
	if ($p_installed ne "") {
		print qq|
		<tr><form action="$server_url$g_admin_url?action=conf_potd" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="potdadmin" src="${images_url}n_confpotd.gif" width=78 height=14 alt="Configure POTD-Script"></td></form></tr>
		|;
	}
	if ($d_installed ne "") {
		print qq|
		<tr><form action="$server_url$g_admin_url?action=conf_dl" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="dladmin" src="${images_url}n_confdl.gif" width=60 height=14 alt="Configure DL-Script"></td></form></tr>
		|;
	}
	if ($s_installed ne "") {
		print qq|
		<tr><form action="$server_url$g_admin_url?action=conf_sp" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="spadmin" src="${images_url}n_confsp.gif" width=60 height=14 alt="Configure SP-Script"></td></form></tr>
		|;
	}
	if ($c_installed ne "") {
		print qq|
		<tr><form action="$server_url$g_admin_url?action=conf_cow" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="cowadmin" src="${images_url}n_confcow.gif" width=76 height=14 alt="Configure COW-Script"></td></form></tr>
		|;
	}
	if (-e "admin_forum.pl") {
		print qq|
		<tr><form action="${server_url}admin_forum.pl?action=conf_xcc" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="confxcc" src="${images_url}n_confforum.gif" width=83 height=14 alt="Configure XCC Forum-Script"></td></form></tr>
		|;
	}
	print qq|
	</table>
	<br><br><font size=2 face="Verdana, Arial, Helvetica" color="#FFCC00">Other Actions</font><br><hr noshade>
	<table><tr><form action="$server_url$g_admin_users_url?action=user_manage" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	<input type="image" name="manageusers" src="${images_url}n_manage_users.gif" width=99 height=14 alt="Manage Users"></td></form>
	</tr>
	|;
	if ($trackip eq "on") {
		print qq|
		<tr><form action="$server_url$g_admin_url?action=viewiplog&viewlatest=50" method="post"><td><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		<input type="image" name="viewiplog" src="${images_url}n_iplogs.gif" width=55 height=14 alt="View IP Logs"></td></form>
		</tr>
		|;
	}
	print "</table>";

	&html_footer;
}

sub viewiplog {
	$viewlatest = $QUERY{'viewlatest'};
	&html_header;
	if ($trackip ne "on") {
		print "<br><font size=3 color=#FFCC00><b>IP-Tracking Not Activated</b></font><br><br>\n";
		print "<p>IP-Tracking is not activated, therefore it is not possible to view the logs. Please activate it in the General Configuration first.<p>\n";
		print "Press the Back-button of your browser or <a href=\"javascript: history.back()\">click here</a> to get back to the previous page.<p>";
		&html_footer;
		return;
	}
	if (-e "$trackfile") {
		open(ipfile,"<$trackfile");
		@all_data = <ipfile>;
		close(ipfile);
		$max_num = @all_data;
	} else {
		print "<br><font size=3 color=#FFCC00><b>No IP-Tracking-file found</b></font><br><br>\n";
		print "<p>The IP-Tracking-file (\"<i>$trackfile</i>\") wasn't found. If you just activated IP-Tracking it might not have been created yet as it records logging in and out.<p>\n";
		print "Press the Back-button of your browser or <a href=\"javascript: history.back()\">click here</a> to get back to the previous page.<p>";
		&html_footer;
		return;
	}
	print qq|
	<br><font size=3 color="#FFCC00"><b>IP-Tracking</b></font><br><br>
	Schlabo's Scripts can track whenever someone uses them. The logs below show the exact date, time and IP of the user who logged in/out. Resetting this log is only possible by deleting $trackfile per FTP (for security reasons), it can't be done from within the scripts.<p>|;
	if (($max_num > $viewlatest) && ($viewlatest ne "") && ($viewlatest ne "0")) {
		print qq|
		<form action="$server_url$g_admin_url?action=viewiplog&viewlatest=0" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
		On this page you can see the latest $viewlatest entries, to view the full logs click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here">.
		<p>
		|;
	}
	unless ($max_num == 0) {
		print qq|
		<br><font color="#FFCC00">Logs</font><br><hr noshade>
		</font></p><table><tr>
		<td><font face="Verdana, Arial, Helvetica" size="2"><b>Date</b></font></td>
		<td><font face="Verdana, Arial, Helvetica" size="2"><b>Time</b></font></td>
		<td><font face="Verdana, Arial, Helvetica" size="2"><b>IP</b></font></td>
		<td><font face="Verdana, Arial, Helvetica" size="2"><b>Host</b></font></td>
		<td><font face="Verdana, Arial, Helvetica" size="2"><b>Action</b></font></td>
		</tr>
		|;
		$td_open = "<td><font face=\"Verdana, Arial, Helvetica\" size=\"1\">";
		$td_close = "</font></td>\n";
		if ($viewlatest == 0) {
			$countto=0;
		} else {
			$countto = $max_num-$viewlatest;
			if ($countto < 0) {$countto=0}
		}
		for ($count=($max_num-1);$count>=$countto;$count--) {
			if (($count % 2)==0) {
				print "<tr bgcolor=#276B2E>";
			} else {
				print "<tr>";
			}
			$curline = @all_data[$count];
			($ip_date, $ip_time, $ip_address, $ip_host, $ip_action) = split (/ - /, $curline);
			print $td_open.$ip_date.$td_close.$td_open.$ip_time.$td_close.$td_open.$ip_address.$td_close.$td_open.$ip_host.$td_close.$td_open.$ip_action.$td_close;
			print "</tr>";
		}
		print "</table>";
	} else {
		print "<p><font face=\"Verdana, Arial, Helvetica\" size=\"2\"><b>Logs empty.</b></font></p>\n";
	}
	&html_footer;
		
	
}

sub confgeneral {
	&html_header;
	print qq|
	<script language="JavaScript">
	<!--
	function openWin (page) {
		myWin= open("http://www.schlabo.com/help/admin/$g_version/"+page+".shtml", "displayWindow", "width=530,height=300,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no");
	}
	// -->
	</script>
	<br><font size=3 color="#FFCC00"><b>General Configuration</b></font><br><br>
	<form action="$server_url$g_admin_url?action=submit_gen" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	|;
	&showheader("Site-Information");
	&showinputbox("sitetitle","Title of your site:");
	&showinputbox("siteurl","URL of your site:","http://www.yoursite.com/");
	&showinputbox("email_address","Your Email-Address:","yourname\@yoursite.com");
	print qq|
	<img src="${images_url}arrow.gif" width="4" height="7" align="middle">&nbsp;<b>Domain that can access Schlabo's Scripts:</b> <small>(<a href="javascript:openWin('referers1')">What's This?</a>)</small><br><small><i>(yoursite.com)</i></small><br>
	<input type="text" size="40" value="$referers[0]" name="referers1" style="font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 1px solid rgb(255,204,0)"><br><br>
	<img src="${images_url}arrow.gif" width="4" height="7" align="middle">&nbsp;<b>2nd domain that can access Schlabo's Scripts (if needed):</b> <small>(<a href="javascript:openWin('referers2')">What's This?</a>)</small><br><small><i>(mysite.com)</i></small><br>
	<input type="text" size="40" value="$referers[1]" name="referers2" style="font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 1px solid rgb(255,204,0)"><br><br>
	|;
	
	&showheader("General Script-Settings");
	unless ($server_security eq "on") {
		&showinputbox("server_url","URL of the Schlabo's Scripts-Directory:","http://www.yoursite.com/cgi-bin/schlabo/");
		&showinputbox("server_path","Server-Path to the Schlabo's Scripts-Directory:","/usr/home/yoursite/htdocs/cgi-bin/schlabo/");
		&showinputbox("server_datapath","Server-Path to the Data-Directory:","Can be the same as the scripts-path unless your server does not allow the scripts to create files in it");
	}
	&showinputbox("font_type","Font used by Schlabo's Scripts (Does not affect Admin-Scripts):","Verdana, Arial, Helvetica","1");
	&showcheckbox("trackip","Track IPs for all Admin-Scripts");
	&showcheckbox("uselocking","Use File-Locking");
	
	if (param('highlight') eq "images_url") {
		print "<a name=\"#images_url\">";
		print "</font><table border=0 width=\"100%\" bgcolor=\"#CC0000\"><tr><td><font face=\"Verdana, Arial, Helvetica\" size=2>";
	}
	&showinputbox("images_url","URL where the images needed by the Admin-Scripts are stored:","http://www.yoursite.com/images/schlabo/");
	if (param('highlight') eq "images_url") {
		print "</font></td></tr></table><font face=\"Verdana, Arial, Helvetica\" size=2>";
	}
	
	unless ($server_security eq "on") {
		&showinputbox("mailprog","The full path to sendmail or a similar program:","Don't include any parameters, for example do NOT include a -t. Most NT-Servers don't support this. - /usr/sbin/sendmail");
	}

	&showheader("Individual Scripts");
	&showcheckbox("p_installed","POTD-Script installed");
	&showcheckbox("d_installed","DL-Script installed");
	&showcheckbox("s_installed","SP-Script installed");
	&showcheckbox("c_installed","COW-Script installed");

	&showsubmit;
	
	&html_footer;
}

sub submitgen {
	$filename = "config.pl";
	if (-e "$filename") {
		open(data,"<$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		open(newconfig,">$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		
		@keywords = ("sitetitle","siteurl","email_address","font_type","trackip","uselocking","images_url","p_installed","d_installed","s_installed","c_installed");
		unless ($server_security eq "on") {
			push keywords,("server_url","server_path","server_datapath","mailprog");
		}
		$nkeywords = @keywords;
		
		for ($count=0;$count<($max_num);$count++) {
			$curline = @all_data[$count];
			$flag = 0;
			for ($checkifkeyword=0;$checkifkeyword<$nkeywords;$checkifkeyword++) {
				$curkeyword = @keywords[$checkifkeyword];
				if ((index($curline,"referers")==1) && ($flag == 0)) {
					print newconfig "\@referers = (\"".param('referers1')."\"";
					if (param('referers2') ne "") {
						print newconfig ",\"".param('referers2')."\"";
					}
					print newconfig ");\n";
					$flag = 1;
				} elsif (index($curline,$curkeyword)==1) {
					$curparam = param($curkeyword);
					$curparam =~ s/\\/\\\\/g;
					$curparam =~ s/\"/\\\"/g;
					$curparam =~ s/\@/\\\@/g;
					print newconfig "\$".$curkeyword." = \"".$curparam."\";\n";
					$flag = 1;
				}
			}
			if ($flag == 0) {
				print newconfig "$curline";
			}
		}
		
		close(newconfig);
	}
	&html_header;
	print qq|
	<br><font size=3 color="#FFCC00"><b>Saved Changes</b></font><br><br>
	<form action="$server_url$g_admin_url?action=showadmin" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	The new settings were successfully written to the config-file! Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to get back to the main page!</form>
	|;
	&html_footer;
}

sub confpotd {
	require "config_potd.pl";
	&html_header;
	print qq|
	<script language="JavaScript">
	<!--
	function openWin (page) {
		myWin= open("http://www.schlabo.com/help/potd/$p_version/"+page+".shtml", "displayWindow", "width=530,height=300,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no");
	}
	// -->
	</script>
	<br><font size=3 color="#FFCC00"><b>POTD Configuration</b></font><br><br>
	<form action="$server_url$g_admin_url?action=submit_potd" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	|;
	&showinputbox("p_script_url","Filename of the POTD-Display-Script:","potd.pl");
	&showinputbox("p_potd_url","POTD-Pictures URL:","Use this only if all/most of your POTDs are stored in the same directory");
	unless ($server_security eq "on") {
		&showinputbox("p_potd_path","POTD-Pictures Path:","The server-path to the URL you specified above, only needed for the uploading-feature");
	}
	&showcheckbox("p_notifyvisitor","Notify visitor per email when you add his POTD to the database about when it will be used");
	&showcheckbox("p_newwindow","Open POTD in a new window (requires activated Javascript)");
	&showinputbox("p_newwindow_properties","Properties of the new window:","Click on the What's This-link for an explanation of the options you have.<br>width=640, height=480, status=yes, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, titlebar=no");
		
	&showheader("Thumbnails");
	&showinputbox("p_thumbtag","Thumbnail-Tag:","The tag at the beginning of the filename of the Thumbnail to distinguish the Thumbnail from the High-Quality-Picture. Recommended: \"t_\"");
	&showinputbox("p_thumbrow","Columns in the calendar:","Depends on the width of your thumbnails. Recommended: 2 or 3");
	&showinputbox("p_thumbw","Width of the Thumbnails:","Only set this if all of your thumbnails have the same width");
	&showinputbox("p_thumbh","Height of the Thumbnails:","Only set this if all of your thumbnails have the same height");
	&showinputbox("p_thumbno","N/A-Picture URL:","If there is no POTD for the current day, display this thumbnail-picture.<br>http://www.yoursite.com/images/schlabo/potd_na.jpg");
	&showcheckbox("p_showprevious","Show previous POTD-Thumbnail instead of the N/A-Picture if none was assigned for the current day");

	&showheader("Visitor-Gallery");
	&showcheckbox("p_galleryon","Enable Visitor-POTD-Gallery");
	&showinputbox("p_galleryscript","Filename of the Gallery-script:","potd_gallery.pl");
	&showcheckbox("p_gallerydesc","Show descriptions below the thumbnails");
	&showinputbox("p_gallerycolumns","Thumbnail-Columns per Gallery-page:","The more columns per page the more thumbnails are displayed per page");
	&showinputbox("p_galleryrows","Thumbnail-Rows per Gallery-page:","The more rows per page the more thumbnails are displayed per page");
	&showinputbox("p_potdgallerytemplate","Filename of HTML-Template for Visitor-Gallery-Pages:","template_potd_gallery.txt");

	&showheader;
	&showinputbox("p_goback","Backwardsearch-Range","Just set this to 1 if you don't know what it is");
	&showinputbox("p_maxgoforward","Forwardsearch-Range:","Just set this to 1 if you don't know what it is");
	&showinputbox("p_potdtemplate","Filename of HTML-Template for POTD-Pages:","template_potd.txt");

	&showsubmit;

	&html_footer;
}

sub submitpotd {
	
	$filename = "config_potd.pl";
	if (-e "$server_path$filename") {
		open(data,"<$server_path$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		@keywords = ("p_script_url","p_potd_url","p_notifyvisitor","p_newwindow","p_newwindow_properties","p_thumbtag","p_thumbrow","p_thumbw","p_thumbh","p_thumbno","p_showprevious","p_galleryon","p_galleryscript","p_gallerydesc","p_gallerycolumns","p_galleryrows","p_goback","p_maxgoforward","p_potdtemplate","p_potdgallerytemplate");
		unless ($server_security eq "on") {
			push keywords,("p_potd_path");
		}
		$nkeywords = @keywords;

		open(newconfig,">$server_path$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		&save_settings;
		close(newconfig);
		
	}
	&html_header;
	print qq|
	<br><font size=3 color="#FFCC00"><b>Saved Changes</b></font><br><br>
	<form action="$server_url$g_admin_url?action=showadmin" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	The new settings were successfully written to the config-file! Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to get back to the main page!</form>
	<form action="$server_url$p_admin_url?action=recreatecache" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	If you changed settings regarding the thumbnail currently being displayed by the POTD-script (for example if you enabled/disabled the popup-window), you have to recreate the cache. Do so by clicking 
	<input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here">!</form>
	|;
	&html_footer;
}

sub confdl {
	require "config_dl.pl";
	
	&html_header;
	print qq|
	<script language="JavaScript">
	<!--
	function openWin (page) {
		myWin= open("http://www.schlabo.com/help/dl/$d_version/"+page+".shtml", "displayWindow", "width=530,height=300,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no");
	}
	// -->
	</script>
	<br><font size=3 color="#FFCC00"><b>DL Configuration</b></font><br><br>
	<form action="$server_url$g_admin_url?action=submit_dl" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	|;
	
	&showinputbox("d_data_file","Database-File:","dl_data.txt");
	&showinputbox("d_script_url","Filename of the Download-Script:","dl.pl");
	&showinputbox("d_dltemplate","Filename of HTML-Template for DL-Pages:","template_dl.txt");

	&showheader("Anti-Leech");
	&showcheckbox("d_antileech","Enable Leech-Protection</b> <small>- Please read before activating this option:</small><b>");
	&showcheckbox("d_leech_alert","Send Leech-Alert Emails");
	&showinputbox("d_check_referer","Check Referer:","0 = Don't check (Allow Downloads coming from every site)<br>1 = From your site and if not determinable<br>2 = Only from your site (deny all other downloads)");

	&showheader("Handling of Entries");
	&showcheckbox("d_autoadd","Auto-Add","If a file isn't found in the database: Automatically add it and allow the download (on) or deny the download (off)");
	&showcheckbox("d_notifymissing","Notify you per email when an entry is not found in the database");
	&showinputbox("d_autoalias","Alias for Auto-Added files:","Example: \"No Alias\". When set to \"auto\", the script will use the filename as Alias");
	&showcheckbox("d_autoreplace","Replace \"_\" with \" \" in Aliases","This is recommended if you use \" \"-signs in Aliases and specify the Alias instead of the URL when linking to the DL-Script");
	
	unless ($server_security eq "on") {
		&showcheckbox("d_countaliastofile","Write Alias-Counts to data-files","Only needed if you use the dl_showdc.pl-script very often on high-traffic-sites.");
		&showinputbox("d_countaliaspath","Path of the Alias-Data-Files Directory:","Some servers don't support it if this is a subdirectory of the cgi-bin. Don't forget to create and CHMOD (755) this directory yourself.");
	}
	
	&showheader("HTML-Codes");
	&showinputbox("d_showdcmessagebefore","HTML-Code in front of DC (dl_showdc.pl):","Something like: \"(Has already been downloaded \". You can also use HTML here.","1");
	&showinputbox("d_showdcmessageafter","2nd part of the HTML-Code (after the DC):","Something like: \" times.\" - After it you can add a link to the guest-logs if you want.","1");
	&showinputbox("d_showtotaldcmessagebefore","HTML-Code in front of Total DC (dl_showtotaldc.pl):","Something like: \"Total number of downloads: \"","1");
	&showinputbox("d_showtotaldcmessagemiddle","HTML-Code between Total Downloads and Available Files:","Something like: \"&lt;br&gt;Number of available Files: \"","1");
	&showinputbox("d_showtotaldcmessageafter","HTML-Code at the end of Total DC:","You can include a link to the full logs here.","1");

	&showheader("Guest-Stats");
	&showinputbox("d_gueststatus","Guest-Logs Status:","\"0\"=Activated;\"1\",\"2\",\"3\"...,x=Show Only Top x;\"-\"=Deny");
	&showinputbox("d_gueststatsscript","Filename of the GuestStats-Script:","dl_gueststats.pl");
	&showcheckbox("d_guestlinks","Link to the files from the GuestStats so that they can be downloaded directly");
	&showcheckbox("d_countguests","Count how often the Guest-Stats are accessed");
	&showinputbox("d_statstemplate","Filename of HTML-Template for Guest Stats:","template_dl_gueststats.txt");

	unless ($server_security eq "on") {
		&showheader("Uploading");
		&showinputbox("d_defaultupload_url","Default Upload-URL:","Only necessary if you use the upload-function and put most files in the same dir");
		&showinputbox("d_defaultupload_path","Default Upload-Path:","Absolute server-path to the same place the URL above points to");
	}
	
	&showsubmit;
	
	&html_footer;
}

sub submitdl {
	
	$filename = "config_dl.pl";
	if (-e "$server_path$filename") {
		open(data,"<$server_path$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		@keywords = ("d_data_file","d_script_url","d_antileech","d_leech_alert","d_check_referer","d_autoadd","d_notifymissing","d_autoalias","d_autoreplace","d_showdcmessagebefore","d_showdcmessageafter","d_showtotaldcmessagebefore","d_showtotaldcmessagemiddle","d_showtotaldcmessageafter","d_gueststatus","d_gueststatsscript","d_guestlinks","d_countguests","d_statstemplate","d_dltemplate");
		unless ($server_security eq "on") {
			push keywords,("d_countaliastofile","d_countaliaspath","d_defaultupload_url","d_defaultupload_path");
		}
		$nkeywords = @keywords;
		
		open(newconfig,">$server_path$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		&save_settings;
		close(newconfig);
		
	}
	&html_header;
	print qq|
	<br><font size=3 color="#FFCC00"><b>Saved Changes</b></font><br><br>
	<form action="$server_url$g_admin_url?action=showadmin" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	The new settings were successfully written to the config-file! Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to get back to the main page!</form>
	|;
	&html_footer;
}

sub confsp {
	require "config_sp.pl";
	&html_header;
	print qq|
	<script language="JavaScript">
	<!--
	function openWin (page) {
		myWin= open("http://www.schlabo.com/help/sp/$s_version/"+page+".shtml", "displayWindow", "width=530,height=300,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no");
	}
	// -->
	</script>
	<br><font size=3 color="#FFCC00"><b>SP Configuration</b></font><br><br>
	<form action="$server_url$g_admin_url?action=submit_sp" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	|;
	
	&showinputbox("s_script_url","Filename of the SP-Display-script:","sp.pl");
	&showinputbox("s_backlinkurl","Back-Link-URL if undeterminable/not specified:","http://www.yoursite.com/");
	&showcheckbox("s_autoreplace","Auto-replace &quot;_&quot; with &quot; &quot; in the Picture-Descriptions");
	unless ($server_security eq "on") {
		&showinputbox("s_pic_url","Pictures-URL:","Use this only if all/most of your pictures are stored in the same directory, only needed if you use the uploading-feature");
		&showinputbox("s_pic_path","Pictures-Path:","The server-path to the URL you specified above, only needed if you use the uploading-feature");
	}

	&showheader("Database");
	&showcheckbox("s_counting","Activate Picture-Display-Counting");
	&showcheckbox("s_autoadd","Auto-Add","<b>Only if counting is active</b>)<br>(If a file isn't found in the database: Automatically add it and allow the download (on) or deny the download (off)");
	&showcheckbox("s_notifymissing","Notify you per email when an entry is not found in the database");
	&showinputbox("s_data_file","Filename of the Database-File:","sp_data.txt");
	&showinputbox("s_sptemplate","Filename of HTML-Template for SP-Pages:","template_sp.txt");

	&showheader("HTML-Codes");
	&showinputbox("s_showscmessagebefore","HTML-Code in front of SC (sp_showsc.pl):","Something like: \"(Has already been shown \". You can also use HTML here.","1");
	&showinputbox("s_showscmessageafter","2nd part of the HTML-Code (after the SC):","Something like: \" times.\" - After it you can add a link to the guest-logs if you want.","1");
	&showinputbox("s_showtotalscmessagebefore","HTML-Code in front of Total SC (sp_showtotalsc.pl):","Something like: \"Total number of shown pictures: \"","1");
	&showinputbox("s_showtotalscmessagemiddle","HTML-Code between Shown Pictures and Available Pictures:","Something like: \"&lt;br&gt;Number of available pictures: \"","1");
	&showinputbox("s_showtotalscmessageafter","HTML-Code at the end of Total SC:","You can include a link to the full logs here.","1");
	
	&showheader("Guest-Stats");
	&showinputbox("s_gueststatus","Guest-Logs Status:","\"0\"=Activated;\"1\",\"2\",\"3\"...,x=Show Only Top x;\"-\"=Deny");
	&showinputbox("s_gueststatsscript","Filename of the GuestStats-Script:","sp_gueststats.pl");
	&showinputbox("s_statstemplate","Filename of HTML-Template for Guest Stats:","template_sp_gueststats.txt");

	&showsubmit;
	
	&html_footer;
}

sub submitsp {
	
	$filename = "config_sp.pl";
	if (-e "$server_path$filename") {
		open(data,"<$server_path$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		@keywords = ("s_script_url","s_backlinkurl","s_autoreplace","s_counting","s_autoadd","s_notifymissing","s_data_file","s_sptemplate","s_showscmessagebefore","s_showscmessageafter","s_showtotalscmessagebefore","s_showtotalscmessagemiddle","s_showtotalscmessageafter","s_gueststatus","s_gueststatsscript","s_statstemplate");
		unless ($server_security eq "on") {
			push keywords,("s_pic_url","s_pic_path");
		}
		$nkeywords = @keywords;
		
		open(newconfig,">$server_path$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		&save_settings;
		close(newconfig);
	}
	&html_header;
	print qq|
	<br><font size=3 color="#FFCC00"><b>Saved Changes</b></font><br><br>
	<form action="$server_url$g_admin_url?action=showadmin" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	The new settings were successfully written to the config-file! Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to get back to the main page!</form>
	|;
	&html_footer;
}

sub confcow {
	require "config_cow.pl";
	&html_header;
	print qq|
	<script language="JavaScript">
	<!--
	function openWin (page) {
		myWin= open("http://www.schlabo.com/help/cow/$c_version/"+page+".shtml", "displayWindow", "width=530,height=300,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no");
	}
	// -->
	</script>
	<br><font size=3 color="#FFCC00"><b>COW Configuration</b></font><br><br>
	<form action="$server_url$g_admin_url?action=submit_cow" method="post"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	|;
	&showinputbox("c_script_url","Filename of the COW Display-Script:","cow.pl");
	&showinputbox("c_data_file","Filename of the Database-File:","cow_data.txt");
	&showinputbox("c_cow_url","Location of the Comic-Picture-Files:","http://www.yoursite.com/images/cow/");
	&showinputbox("c_files","General Comic-Filenames:","Click on &quot;What's This?&quot; for help on how to name files");
	&showinputbox("c_extension","Filename-Extension of the Comic-Picture-Files:","jpg/gif, without a .");
	&showinputbox("c_thumbtag","Thumbnail-Tag:","The tag at the beginning of the filename of the Thumbnail to distinguish the Thumbnail from the Comic-Pictures. Recommended: \"t_\"");
	&showinputbox("c_cowtemplate","Filename of HTML-Template for COW-Pages:","template_cow.txt");

	&showsubmit;
	
	&html_footer;
}

sub submitcow {
	
	$filename = "config_cow.pl";
	if (-e "$server_path$filename") {
		open(data,"<$server_path$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		@keywords = ("c_script_url","c_data_file","c_cow_url","c_files","c_extension","c_thumbtag","c_cowtemplate");
		$nkeywords = @keywords;
		
		open(newconfig,">$server_path$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		&save_settings;
		close(newconfig);
	}
	&html_header;
	print qq|
	<br><font size=3 color="#FFCC00"><b>Saved Changes</b></font><br><br>
	<form action="$server_url$g_admin_url?action=showadmin" method="POST"><input type="hidden" name="pw" value=$param_pw><input type="hidden" name="username" value=$param_username>
	The new settings were successfully written to the config-file! Click <input type="image" name="here" src="${images_url}b_here.gif" width=35 height=16 alt="here"> to get back to the main page!</form>
	|;
	&html_footer;
}

sub checkupdates {
	# Save current timecode to config-file so that next reminder appears in one month
	$g_updatecheck = &calculatetimecode($y,$m,$month_day);
	$filename = "config.pl";
	if (-e "$filename") {
		open(data,"<$filename");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		@keywords = ("g_updatecheck");
		$nkeywords = @keywords;
		
		open(newconfig,">$server_path$filename") || &showerror("An error occured when trying to save the changes. Please make sure the script-permissions are set correctly on the server and you CHMODed the Schlabo's Scripts-directory to either 777 or 755 (depending on your server).");
		&save_settings;
		close(newconfig);		
	}
	
	# Redirect to schlabo.com
	print "Location: http://www.schlabo.com/updates.shtml?g_version=${g_version}";
	if ($p_installed eq "on") {
		require "config_potd.pl";
		print "\&p_version=${p_version}";
	}
	if ($d_installed eq "on") {
		require "config_dl.pl";
		print "\&d_version=${d_version}";
	}
	if ($s_installed eq "on") {
		require "config_sp.pl";
		print "\&s_version=${s_version}";
	}
	if ($c_installed eq "on") {
		require "config_cow.pl";
		print "\&c_version=${c_version}";
	}
	print "\n\n";
}


sub firstrun {
	print "Content-type: text/html\n\n";
	print qq|
	<html><head><title>Schlabo's Scripts v$g_version - Auto Configuration</title></head>
	<body bgcolor="#000000" text="#FFFFFF" link="#00FF00" vlink="#33CC00" alink="#66FF66">
	<p><font face="Verdana, Arial, Helvetica"><font size="3" color="#FFCC00"><b>Schlabo's Scripts - Auto Configuration</b></font><br><br>
	Please wait while the script attempts to configure itself...</font></p>
	<ul>
	|;
	
	if (($CGI::VERSION eq "3.00") || ($CGI::VERSION eq "3.01")) {
		print "<p><font face=\"Verdana, Arial, Helvetica\" size=\"2\"><b>WARNING:</b> Schlabo's Scripts require the CGI.pm-library, however on your server you have an alpha-version installed (v$CGI::VERSION) wich has a major bug in a function used by the scripts.";
		print "Please go to the <a href=\"http://stein.cshl.org/WWW/software/CGI/\">official site</a>, download the latest final version (v2.752) and install it on your server instead or tell your server-admins to do it. Otherwise adding stuff to the database won't work.</font></p></body></html>";
		return;
	}
	
	# Get the name of the General Admin-Script
	$script_name = $ENV{'SCRIPT_NAME'};
	$g_admin_url = substr($script_name,(rindex($script_name,"/")+1));
	print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Name of the general admin-script: \"<i>$g_admin_url</i>\"</font></li>\n";
	# Get the Site-URL
	$siteurl = "http://".$ENV{'HTTP_HOST'};
	if ((index($siteurl, "cgiwrap") > (-1)) || ($siteurl eq "")) {
		$siteurl = "http://$ENV{'SERVER_NAME'}/";
	}
	if (substr($siteurl,length($siteurl)-1,1) ne "/") {
		$siteurl = $siteurl."/";
	}
	print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">URL of your site: \"<i>$siteurl</i>\"</font></li>\n";
	# URL of the Schlabo's Scripts-dir
	if ((index($script_name, "cgiwrap") > (-1)) || ($script_name eq "")) {
		$server_url = "http://$ENV{'SERVER_NAME'}$ENV{'SCRIPT_NAME'}";
		$server_url =~ s/$g_admin_url//ig;
	} else {
		$left = substr($script_name,0,(rindex($script_name,"/")+1));
		$server_url = "http://".$ENV{'HTTP_HOST'}.$left;
	}
	print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">URL of the Schlabo's Scripts-directory: \"<i>$server_url</i>\"</font></li>\n";
	# Referer
	if ($ENV{'HTTP_HOST'}) {
		$referers1 = $ENV{'HTTP_HOST'};
	} else {
		$referers1 = $ENV{'SERVER_NAME'};
	}
	if ((rindex($referers1,"/")+1) eq (length($referers1))) {
		$referers1 = substr($referers1,0,(rindex($referers1,"/")));
	}
	print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Allowed Referer: \"<i>$referers1</i>\"</font></li>\n";
	# Server-Path of the Schlabo's Scripts-dir
	$correct_path = "";
	if (param('serverpath')) {
		$server_path = param('serverpath');
		&check_serverpath;
	}
	if (($correct_path eq "") && ($ENV{'PATH_TRANSLATED'})) {
		$server_path = $ENV{'PATH_TRANSLATED'};
		&check_serverpath;
	}
	if ($correct_path eq "") {
		$server_path = $ENV{'SCRIPT_FILENAME'};
		&check_serverpath;
	}
	if ($correct_path eq "") {
		$server_path = "$ENV{'DOCUMENT_ROOT'}$ENV{'SCRIPT_NAME'}";
		&check_serverpath;
	}
	if ($correct_path eq "") {
		# Wasn't able to find server-path
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Unable to determine server-path to the scripts.</b><br>";
		print "You can specify the correct server-path to the scripts yourself by handing it to the scripts with a parameter.";
		print "Run AutoConfig again with an URL like this one (replace the server-path with the path to the scripts on your server. Ask your server-administrator if you don't know it):<br>\n<i>";
		print $server_url.$g_admin_url."?serverpath=/path/to/schlabosscripts/</i></font></li>\n";
		print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
		return;
	}
	$server_path = $correct_path;
	$server_datapath = $server_path;
	unless ($server_security eq "on") {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Server-Path of the Schlabo's Scripts-directory: \"<i>$server_path</i>\"</font></li>\n";
	}
	# Try to find other Schlabo's Scripts-Stuff
	$g_admin_users_url = "admin_users.pl";
	unless (-e "${server_path}$g_admin_users_url") {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Admin-Users-Script (admin_users.pl) <i><b>not</b> found</i>. Please make sure that you uploaded all files to the same directory (except the images) and that you CHMODed them and the directory to 755 (or 777, some servers only like one of those).</font></li>\n";
		print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
		return;
	}
	
	# Try to find the images
	$document_root = $ENV{'DOCUMENT_ROOT'};
	if (!$document_root) {
		$document_root = $server_path;
		$document_root =~ s!(\/cgi).*$!!;
	}
	if ((rindex($document_root,"/")+1) ne (length($document_root))) {
		$document_root = $document_root."/";
	}
	$ifound == 0;
	if (-e "${document_root}g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl;
	} elsif (-e "${document_root}images/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/";
	} elsif (-e "${document_root}images/schlabo/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/schlabo/";
	} elsif (-e "${document_root}images/layout/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/layout/";
	} elsif (-e "${document_root}/htdocs/images/schlabo/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/schlabo/";
	} elsif (-e "${document_root}/public_html/images/schlabo/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/schlabo/";
	} elsif (-e "${document_root}/htdocs/images/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/";
	} elsif (-e "${document_root}/public_html/images/g_logo.gif") {
		$ifound = 1;
		$images_url = $siteurl."images/";
	} elsif (-e "${server_path}g_logo.gif") {
		$ifound = 2;
		$images_url = $server_url;
	} elsif (-e "${server_path}images/g_logo.gif") {
		$ifound = 2;
		$images_url = $server_url."images/";
	}
	if ($ifound == 1) {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Images found at: \"<i>$images_url</i>\"</font></li>\n";
	} elsif ($ifound == 2) {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Images found at: \"<i>$images_url</i>\".<br><i><b>WARNING:</b> Many servers don't support displaying images from the CGI-Directory. If you don't see any images in the Schlabo's Scripts, try putting them somewhere else.</i></font></li>\n";
	} else {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Images were <b>NOT</b> found. Please specify the URL of the Schlabo's Scripts-Images-Directory yourself. For more information on how to do that <a href=\"http://www.schlabo.com/support/troubleshooting.shtml#images\" target=\"_blank\">click here</a>.</font></li>\n";
		$images_url = $siteurl."images/schlabo/";
	}
	# Determine if the POTD-Script is installed
	if (-e "${server_path}potd_admin.pl") {
		$p_installed = "on";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">POTD-Script <i>found</i>.</font></li>\n";
	} else {
		$p_installed = "";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">POTD-Script <i><b>not</b> found</i>.</font></li>\n";
	}
	# Determine if the DL-Script is installed
	if (-e "${server_path}dl_admin.pl") {
		$d_installed = "on";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">DL-Script <i>found</i>.</font></li>\n";
	} else {
		$d_installed = "";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">DL-Script <i><b>not</b> found</i>.</font></li>\n";
	}
	# Determine if the SP-Script is installed
	if (-e "${server_path}sp_admin.pl") {
		$s_installed = "on";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">SP-Script <i>found</i>.</font></li>\n";
	} else {
		$s_installed = "";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">SP-Script <i><b>not</b> found</i>.</font></li>\n";
	}
	# Determine if the COW-Script is installed
	if (-e "${server_path}cow_admin.pl") {
		$c_installed = "on";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">COW-Script <i>found</i>.</font></li>\n";
	} else {
		$c_installed = "";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">COW-Script <i><b>not</b> found</i>.</font></li>\n";
	}
	# Test use of crypt();
	if (param('crypted_pw') eq "off") {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Warning: You have deactivated Password-Encryption.</b></font></li>\n";
		$crypted_passwords = "";
		$new_password_crypted = "";
	} else {
		$crypted_passwords = "on";
		my $cryptone = crypt("test123", "p4");
		my $crypttwo = crypt("test123", $cryptone);
		my $cryptthree = crypt("not5same", $cryptone);
		my $cryptfour = crypt('', $cryptone);
		if ($cryptone ne $crypttwo || $cryptone eq $cryptthree || $cryptone eq $cryptfour) {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Error in crypt() implementation of your server: $cryptone | $crypttwo | $cryptthree | $cryptfour - Contact your server-admin. Password-Encryption has been deactivated.</b></font></li>\n";
			$crypted_passwords = "";
			$new_password_crypted = "";
		} else {
			# Create an empty (crpyted) password
			$new_password_crypted = crypt("", join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
		}
	}
	# Test write/read-permissions
	unless (open(testfile,">${server_datapath}deleteme")) {
		close(testfile);
		unless (-e "deleteme") {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: The server doesn't allow the script to create new files (for example database-files). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
			print "to write to this directory. Make sure that you CHMODed the Schlabo's Scripts-directory to 755, or try 777 (some servers only like one of those settings). If your server doesn't allow the script creating files in the scripts-directory, ";
			print "you can also create a data-directory somewhere else on your server, CHMOD it to 777 and specify it in the General Configuration.<br>";
			print "Please note - even though the scripts will continue the configuration, you will NOT be able to use them without fixing this issue!</b></font></li>\n";
			print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION CONTINUES</font>";
		}
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: The script tried to create a new file and open it. It was successful in creating however an error occured with opening it. Make sure that you CHMODed the Schlabo's Scripts-directory to 755, or try 777 (some servers only like one of those settings). If your server doesn't allow the script creating files in the scripts-directory, ";
		print "you can also create a data-directory somewhere else on your server, CHMOD it to 777 and specify it in the General Configuration.<br>";
		print "Please note - even though the scripts will continue the configuration, you will NOT be able to use them without fixing this issue!</b></font></li>\n";
		print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION CONTINUES</font>";
	}
	close(testfile);
	unless (unlink 'deleteme') {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Note:</b> Unable to delete the file the script used to test permissions on the server. Please manually delete the file called \"deleteme\" in the Schlabo's Scripts-directory, however if it stays there it doesn't harm anyone. $_</font></li>\n";
	}
	unless (open(testfile,"<${server_path}config.pl")) {
		close(testfile);
		unless (-e "${server_path}config.pl") {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Couldn't open a Schlabo's Scripts-file (config.pl) for reading, the script can't find it. Please make sure that you uploaded all files to the same directory (except the image-files) and that you CHMODed the directory and all files to 755 (also try 777, some servers only like one of those settings).</b></font></li>\n";
			print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
			return;
		}
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Couldn't open a Schlabo's Scripts-file (config.pl) for reading, however the file appears to exist. Please make sure that you CHMODed the directory and all files to 755 (also try 777, some servers only like one of those settings).</b></font></li>\n";
		print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
		return;
	}
	close(testfile);
	
	# Email-Address
	$email_address = $ENV{'SERVER_ADMIN'};
	print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">Contact-Address: \"<i>$email_address</i>\"</font></li>\n";
	# Timecode for Update-Reminder System
	$g_updatecheck = &calculatetimecode($y,$m,$month_day);
	
	# Write Config-File
	if (-e "${server_path}config.pl") {
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">General Configuration-File <i>found</i>.</font></li>\n";
		open(data,"<${server_path}config.pl");      # Put contents of file into an array
		@all_data = <data>;
		close(data);
		$max_num = @all_data;
		
		unless (open(newconfig,">${server_path}config.pl")) {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Unable to save changes to an existing file (in this case config.pl). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
			print "to write to this directory or to modify files. Make sure that you CHMODed the Schlabo's Scripts-directory and all files in it to 755, or try 777 (some servers only like one of those settings).</b></font></li>\n";
			print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
			return;
		}
		
		@keywords = ("g_admin_url","siteurl","email_address","server_url","server_path","server_datapath","images_url","g_updatecheck","p_installed","d_installed","s_installed","c_installed","crypted_passwords");
		$nkeywords = @keywords;
		
		for ($count=0;$count<($max_num);$count++) {
			$curline = @all_data[$count];
			$flag = 0;
			for ($checkifkeyword=0;$checkifkeyword<$nkeywords;$checkifkeyword++) {
				$curkeyword = @keywords[$checkifkeyword];
				
				if ((index($curline,"referers")==1) && ($flag == 0)) {
					print newconfig "\@referers = (\"$referers1\");\n";
					$flag = 1;
				} elsif ((index($curline,"user_names")==1) && ($flag == 0)) {
					print newconfig "\@user_names = (\"\");\n";
					$flag = 1;
				} elsif ((index($curline,"user_passwords")==1) && ($flag == 0)) {
					print newconfig "\@user_passwords = (\"$new_password_crypted\");\n";
					$flag = 1;
				} elsif ((index($curline,"user_access_g")==1) && ($flag == 0)) {
					print newconfig "\@user_access_g = (\"on\");\n";
					$flag = 1;
				} elsif	(index($curline,$curkeyword)==1) {
					$curparam = ${$curkeyword};
					$curparam =~ s/\\/\\\\/g;
					$curparam =~ s/\"/\\\"/g;
					$curparam =~ s/\@/\\\@/g;
					print newconfig "\$".$curkeyword." = \"".$curparam."\";\n";
					$flag = 1;
				}
			}
			if ($flag == 0) {
				print newconfig "$curline";
			}
		}
		
		close(newconfig);
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">General Configuration-File successfully written.</font></li>\n";
	} else {
		print "<p><font face=\"Verdana, Arial, Helvetica\" size=\"2\"><b>WARNING:</b> The general configuration-file (config.pl) wasn't found. Please make sure that you put ALL of the files that came with Schlabo's Scripts (except the images) into the SAME directory! After you did that, start this script again.</font></p></body></html>";
		return;
	}
	# Configure POTD-Script
	if ($p_installed eq "on") {
		if ($ifound ne "0") { $p_thumbno = ${images_url}."potd_na_160x120.gif"; }
		$p_potd_url = $siteurl."images/potd/";
		$p_potd_path = $document_root."images/potd/";
		if (-e "${server_path}config_potd.pl") {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">POTD Configuration-File <i>found</i>.</font></li>\n";
			open(data,"<${server_path}config_potd.pl");      # Put contents of file into an array
			@all_data = <data>;
			close(data);
			$max_num = @all_data;
			
			@keywords = ("p_potd_url","p_potd_path","p_thumbno");
			$nkeywords = @keywords;
			
			unless (open(newconfig,">${server_path}config_potd.pl")) {
				print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Unable to save changes to an existing file (in this case config_potd.pl). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
				print "to write to this directory or to modify files. Make sure that you CHMODed the Schlabo's Scripts-directory and all files in it to 755, or try 777 (some servers only like one of those settings).</b></font></li>\n";
				print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
				return;
			}			
			
			
			&save_settings;
			close(newconfig);
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">POTD Configuration-File successfully written.</font></li>\n";
		} else {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>WARNING:</b> The POTD configuration-file (config_potd.pl) wasn't found. Please make sure that you put ALL of the files that came with Schlabo's Scripts (except the images) into the SAME directory!</font></li>";
		}
	}
	
	# Configure DL-Script
	if ($d_installed eq "on") {
		$d_showdcmessageafter = " times. <a href=\"".$server_url."dl_gueststats.pl\">View full logs</a>)</i></font>";
		$d_showtotaldcmessageafter = "<br>(<a href=\"".$server_url."dl_gueststats.pl\">View full logs</a>)";
		$d_countaliaspath = $document_root."dl_data/";
		$d_defaultupload_url = $siteurl."files/";
		$d_defaultupload_path = $document_root."files/";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">DL-Messages configured</font></li>";
		if (-e "${server_path}config_dl.pl") {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">DL Configuration-File <i>found</i>.</font></li>\n";
			open(data,"<${server_path}config_dl.pl");      # Put contents of file into an array
			@all_data = <data>;
			close(data);
			$max_num = @all_data;
			
			@keywords = ("d_countaliaspath","d_showdcmessageafter","d_showtotaldcmessageafter","d_defaultupload_url","d_defaultupload_path");
			$nkeywords = @keywords;
			
			unless (open(newconfig,">${server_path}config_dl.pl")) {
				print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Unable to save changes to an existing file (in this case config_dl.pl). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
				print "to write to this directory or to modify files. Make sure that you CHMODed the Schlabo's Scripts-directory and all files in it to 755, or try 777 (some servers only like one of those settings).</b></font></li>\n";
				print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
				return;
			}
			
			&save_settings;
			close(newconfig);
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">DL Configuration-File successfully written.</font></li>\n";
		} else {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>WARNING:</b> The DL configuration-file (config_potd.pl) wasn't found. Please make sure that you put ALL of the files that came with Schlabo's Scripts (except the images) into the SAME directory!</font></li>";
		}
	}
	
	
	# Configure SP-Script
	if ($s_installed eq "on") {
		$s_backlinkurl = $siteurl;
		$s_pic_url = $siteurl."images/";
		$s_pic_path = $document_root."images/";
		$s_showscmessageafter = " times. <a href=\"".$server_url."sp_gueststats.pl\">View full logs</a>)</i></font>";
		$s_showtotalscmessageafter = "<br>(<a href=\"".$server_url."sp_gueststats.pl\">View full logs</a>)";
		print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">SP Variables <i>set</i>.</font></li>\n";
		if (-e "${server_path}config_sp.pl") {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">SP Configuration-File <i>found</i>.</font></li>\n";
			open(data,"<${server_path}config_sp.pl");      # Put contents of file into an array
			@all_data = <data>;
			close(data);
			$max_num = @all_data;
			
			@keywords = ("s_backlinkurl","s_pic_url","s_pic_path","s_showscmessageafter","s_showtotalscmessageafter");
			$nkeywords = @keywords;
			
			unless (open(newconfig,">${server_path}config_sp.pl")) {
				print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>Error: Unable to save changes to an existing file (in this case config_sp.pl). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
				print "to write to this directory or to modify files. Make sure that you CHMODed the Schlabo's Scripts-directory and all files in it to 755, or try 777 (some servers only like one of those settings).</b></font></li>\n";
				print "</ul><font face=\"Verdana, Arial, Helvetica\" size=\"2\" color=red>INSTALLATION HALTED</font>";
				return;
			}			
			
			&save_settings;
			close(newconfig);
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\">SP Configuration-File successfully written.</font></li>\n";
		} else {
			print "<li><font face=\"Verdana, Arial, Helvetica\" size=\"1\"><b>WARNING:</b> The SP configuration-file (config_sp.pl) wasn't found. Please make sure that you put ALL of the files that came with Schlabo's Scripts (except the images) into the SAME directory!</font></li>";
		}
	}
		
	print qq|
	</ul>
	<p><font face="Verdana, Arial, Helvetica"><font size="3" color="#FFCC00"><b>Success!</b></font><br><br>
	<font size="2">Auto-Configuration was successful. The script is now ready to run on your server!<br>
	If any of the things above is wrong you can correct them using the General Admin-Script. Don't forget
	to create your username and password (Right now there is NO password and NO username).<br>
	<b><a href="${server_url}${g_admin_users_url}?action=user_edit_form&firsttime=1&user_which=0">Enter Schlabo's Scripts...</a></b></font></p>
	</body>
	</html>
	|;
	
}

sub check_serverpath {
	$server_path =~ s/$g_admin_url//ig;
	unless (((lc(substr($server_path,length($server_path)-1,1))) eq "\\") || ((lc(substr($server_path,length($server_path)-1,1))) eq "/")) {
		# Check if NT or Linux-path
		if (index($server_path,"/") == (-1)) {
			$server_path.="\\";
		} else {
			$server_path.="/";
		}
	}
	if (-e "${server_path}${g_admin_url}") {
		$correct_path = $server_path;
	}
}

sub save_settings {
	for ($count=0;$count<($max_num);$count++) {
		$curline = @all_data[$count];
		$flag = 0;
		for ($checkifkeyword=0;$checkifkeyword<$nkeywords;$checkifkeyword++) {
			$curkeyword = @keywords[$checkifkeyword];
			
			if (index($curline,$curkeyword)==1) {
				if (param($curkeyword) ne "") {
					$curparam = param($curkeyword);
				} else {
					$curparam = ${$curkeyword};
				}
				$curparam =~ s/\\/\\\\/g;
				$curparam =~ s/\"/\\\"/g;
				$curparam =~ s/\@/\\\@/g;
				print newconfig "\$".$curkeyword." = \"".$curparam."\";\n";
				$flag = 1;
			}
		}
		if ($flag == 0) {
			print newconfig "$curline";
		}
	}
}

sub firsttime_user {
	print "Content-type: text/html\n\n";
	print qq|
	<html><head><title>Schlabo's Scripts v$g_version - Create Empty User</title></head>
	<body bgcolor="#000000" text="#FFFFFF" link="#00FF00" vlink="#33CC00" alink="#66FF66">
	<p><font face="Verdana, Arial, Helvetica"><font size="3" color="#FFCC00"><b>Schlabo's Scripts - Create Empty User</b></font><br><br>
	Checking if this procedure is necessary...<br><br>
	|;
	$user_numbers = @user_names;
	if (($user_numbers == 0) || (($user_numbers == 1) && ($user_names[0] eq ""))) {
		$new_password_crypted = crypt("", join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
		if (-e "${server_path}config.pl") {
			open(data,"<${server_path}config.pl");      # Put contents of file into an array
			@all_data = <data>;
			close(data);
			$max_num = @all_data;
			
			unless (open(newconfig,">${server_path}config.pl")) {
				print "<b>Error: Unable to save changes to an existing file (in this case config.pl). If you're on a UNIX-Server it's likely that the script doesn't have permission ";
				print "to write to this directory or to modify files. Make sure that you CHMODed the Schlabo's Scripts-directory and all files in it to 755, or try 777 (some servers only like one of those settings).</b>\n";
				print "<font color=red>PROCESS HALTED</font></body></html>";
				return;
			}
						
			for ($count=0;$count<($max_num);$count++) {
				$curline = @all_data[$count];
				if (index($curline,"user_names")==1) {
					print newconfig "\@user_names = (\"\");\n";
				} elsif (index($curline,"user_passwords")==1) {
					print newconfig "\@user_passwords = (\"$new_password_crypted\");\n";
				} elsif (index($curline,"user_access_g")==1) {
					print newconfig "\@user_access_g = (\"on\");\n";
				} else {
					print newconfig "$curline";
				}
			}
			
			close(newconfig);
			print "Default user successfully generated. The new user has NO username and NO password, assign them in the User Management.<br>";
			print "<b><a href=\"${server_url}${g_admin_users_url}?action=login\">Enter Schlabo's Scripts...</a></b></font>\n";
		} else {
			print "<b>WARNING:</b> The general configuration-file (config.pl) wasn't found. Please make sure that you put ALL of the files that came with Schlabo's Scripts (except the images) into the SAME directory! After you did that, start this script again.</font>";
			return;
		}
	} else {
		print "Creating an empty user is not allowed, one or more users do already exist.<br><b>Process aborted</b>.</font></p>\n";
	}
	print "</body></html>";
}

sub calculatetimecode {
	$ctc = (($_[0] - 2000) * 365) + $_[2];
	if ($_[1]>1) {
		for ($ctc_count=0;$ctc_count<($_[1]-1);$ctc_count++) {
			$ctc = $ctc + $months_days[$ctc_count];
		}
	}
	return($ctc);
}

sub showinputbox {
	local($variablename,$title,$description,$htmlcontent) = @_;
	print "<img src=\"${images_url}arrow.gif\" width=\"4\" height=\"7\" align=\"middle\">&nbsp;<b>$title</b> <small>(<a href=\"javascript:openWin('$variablename')\">What's This?</a>)</small>";
	if ($description) {
		print "<br><small><i>($description)</i></small><br>";
	}
	unless ($htmlcontent) {
		print "\n<input type=\"text\" size=\"40\" value=\"${$variablename}\" name=\"$variablename\" style=\"font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 1px solid rgb(255,204,0)\"><br><br>\n";
	} else {
		print "\n<input type=\"text\" size=\"40\" value=\'${$variablename}\' name=\"$variablename\" style=\"font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 1px solid rgb(255,204,0)\"><br><br>\n";
	}
}

sub showheader {
	local($title) = @_;
	print "<font color=\"#FFCC00\">$title</font><br><hr noshade>\n";
}

sub showcheckbox {
	local($variablename,$title,$description) = @_;
	print "<img src=\"${images_url}arrow.gif\" width=\"4\" height=\"7\" align=\"middle\">&nbsp;<input type=\"checkbox\" name=\"$variablename\"";
	unless (${$variablename} eq "") { print " checked" }
	print ">&nbsp;<b>$title</b> <small>(<a href=\"javascript:openWin('$variablename')\">What's This?</a>)</small>";
	if ($description) {
		print "<br><small><i>($description)</i></small>";
	}
	print "</input><br><br>\n";
}

sub showsubmit {
	print qq|
	<br><font color="#FFCC00">Submit</font><br><hr noshade>
	<input type="submit" name="submit" value="Save Changes" style="font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 2px solid rgb(255,204,0)">&nbsp;
	<input type="reset" name="reset" value="Reset" style="font-family: Verdana,Arial,Helvetica; font-size: 13; background-color: rgb(0,0,0); color: rgb(255,255,255); border: 2px solid rgb(255,204,0)">
	</form>
	|;
}

sub init_questions {
	
	$question[0] = "How to I login to the scripts?";
	$question[1] = "How do the templates work?";
	$question[2] = "Is there a way to see if I'm using the latest version?";
	$question[3] = "What's the use of File-Locking?";
	$question[4] = "Why would I want to track IPs?";
	$question[5] = "Why does the script need to know my email-address?";
	$question[6] = "How do I configure the script for sending emails?";
	$question[7] = "Aren't Cookies a Security-Risk?";
	$question[8] = "Are the scripts compatible to PHP?";
	$question[9] = "Where can I get support?";
	
}

