#!/usr/bin/perl



          # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
          #                                                         #
          #         File: simpleforum_pro.cgi                       #
          #         Name: SimpleForum Pro v4.0                      #
          #         Author: Daan Deconinck                          #
          #         E-mail: daan.deconinck@pandora.be               #
          #         Date: 10/12/2002 (DD/MM/YYYY)                   #
          #         Last Update: 16/11/2003 (DD/MM/YYYY)            #
          #                                                         #
          #         This script is made to work on all HTTP         #
          #         servers supporting CGI, and requires no         #
          #         modules to be installed.                        #
          #                                                         #
          #         This software cannot be edited or modified      #
          #         by anyone without the explicit permission       #
          #         from the author. See "Terms of use.txt".        #
          #                                                         #
          #         SimpleForum Pro                                 #
          #         ©2003 Daan Deconinck                            #
          #                                                         #
          # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #



# # # # # # # # # #
#                 #
#    F O R U M    #
#                 #
# # # # # # # # # #


# # # # # # # CONSTANTS / CONFIG # # # # # # # # # # # # # # # # # # # # # #

#The dir where SimpleForum will place all its files in, likely you won't want to change this line.
#(example: $simpleforum_dir = "simpleforum_files";)
$simpleforum_dir = "../simpleforum_files";

#The rest of the configurations can be done through the Admin area on the forum. Time to start 'r up :)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


# # # # # # # MAIN # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# Do not change anything below
# See "Terms of use.txt" that came with the download for more info

use CGI;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use lib ".";

&start;
if ($qs) {
	if ($qs =~ /login/ and !$logged_in) {
		# log in
		&login;
	} elsif ($qs eq "logout") {
		#log out
		&logout;
	} elsif (param('pmsg')) {
		#private messaging
		&private_messages;
	} elsif (param('user_settings') and $logged_in) {
		# user preferences
		&user_settings;
	} elsif (param('pid')) {
		print_profile(param('pid'));
	} elsif ($qs =~ /topic_id=(\d*)/s and $forum_id) {
		#print a topic
		$topic_id = $1;
		&page_start;
		&print_topic;
		&page_end;
	} elsif ($qs =~ /admin/) {
		&admin;
		&page_end;
	} elsif ($qs =~ /search/) {
		&page_start;
		&search;
		&page_end;
	} elsif ($qs =~ /help/) {
		&page_start;
		&help;
		&page_end;
	} elsif ($forum_id) {
		#print topic index for this forum section
		&page_start;
		&print_topic_index;
		&page_end;
	} elsif ($qs =~ /register/ and ($user eq "guest" or $admin_access)) {
		# register new user
		&register;
	} else {
		#invalid query string
		print redirect("$script_name");
	}
} else {
	#index
	&page_start;
	&print_forum_index;
	&page_end;
}


# # # # # # SUBROUTINES # # # # # # # # # # # # # # # # # # # # # # # # # #

sub page_start {
#self-explanatory
#Don't touch this line!
print header;
$header_printed = 1;
	$referer = url(-path_info=>1,-query=>1);
	$qs_referer = $referer;
	$qs_referer =~ s/\&/\$/sg;
if ($menu_display eq "text") {
	if (!$logged_in) {
		$login_menu = "<a href='$script_name?login&ref=$qs_referer'>$lang_log_in</a> | <a>Inloggen niet meer nodig</a>";
	} else {
		$login_menu = "<a href='$script_name?fid=$forum_id&user_settings=1'>$lang_personal</a> | <a href='$script_name?logout'>$lang_log_out</a>";
	}
	if ($admin_access) { $admin_menu = " | <a href='$script_name?fid=$forum_id&admin=1'>$lang_admin</a>"; }

	if ($qs =~ /admin/) {
		if ($forum_id) {
			$menu = "<$standardfont>$forum_name</font><br><br><a href='$home_url'>$home_name</a> | <a href='$script_name'>$lang_forum_index</a> | <a href='$script_name?fid=$forum_id'>$forum_name</a> | <a href='$script_name?fid=$forum_id&search'>$lang_search</a> | <a href='$script_name?fid=$forum_id&help'>$lang_help</a>$admin_menu | $login_menu";
		} else {
			$menu = "<$standardfont>$subtitle</font><br><br><a href='$home_url'>$home_name</a> | <a href='$script_name'>$lang_forum_index</a> | <a href='$script_name?fid=$forum_id&search'>$lang_search</a> | <a href='$script_name?fid=$forum_id&help'>$lang_help</a>$admin_menu | $login_menu";
		}
	} else {
		if ($forum_id) {
			$menu = "<$standardfont>$forum_name</font><br><br><a href='$home_url'>$home_name</a> | <a href='$script_name?fid=$forum_id&search'>$lang_search</a> | <a href='$script_name?fid=$forum_id&help'>$lang_help</a>$admin_menu | $login_menu";
		} else {
			$menu = "<$standardfont>$subtitle</font><br><br><a href='$home_url'>$home_name</a> | <a href='$script_name?fid=$forum_id&search'>$lang_search</a> | <a href='$script_name?fid=$forum_id&help'>$lang_help</a>$admin_menu | $login_menu";
		}
	}
} else {
	if (!$logged_in) {
		$login_menu = <<HTML;
			<td><a href="$script_name?login&ref=$qs_referer" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_login','','$images_dir/menu/$menu_display/btn_login_f2.gif',1);"><img name="btn_login" src="$images_dir/menu/$menu_display/btn_login.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?register" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_register','','$images_dir/menu/$menu_display/btn_register_f2.gif',1);"><img name="btn_register" src="$images_dir/menu/$menu_display/btn_register.gif" border="0" alt=""></a></td>
HTML
	} else {
		$login_menu = <<HTML;
			<td><a href="$script_name?fid=$forum_id&user_settings=1" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_personal','','$images_dir/menu/$menu_display/btn_personal_f2.gif',1);"><img name="btn_personal" src="$images_dir/menu/$menu_display/btn_personal.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?logout" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_logout','','$images_dir/menu/$menu_display/btn_logout_f2.gif',1);"><img name="btn_logout" src="$images_dir/menu/$menu_display/btn_logout.gif" border="0" alt=""></a></td>
HTML
	}
	if ($admin_access) { $admin_menu = "<td><a href=\"$script_name?fid=$forum_id&admin=1\" onMouseOut=\"MM_swapImgRestore();\" onMouseOver=\"MM_swapImage('btn_admin','','$images_dir/menu/$menu_display/btn_admin_f2.gif',1);\"><img name=\"btn_admin\" src=\"$images_dir/menu/$menu_display/btn_admin.gif\" border=\"0\" alt=\"\"></a></td>"; }

	if ($qs =~ /admin/) {
		if ($forum_id) {
			$menu = <<HTML;
			<$standardfont>$forum_name</font><br><br>
			<table><tr>
			<td><a href="$home_url" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_home','','$images_dir/menu/$menu_display/btn_home_f2.gif',1);"><img name="btn_home" src="$images_dir/menu/$menu_display/btn_home.gif" border="0" alt=""></a></td>
			<td><a href="$script_name" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_index','','$images_dir/menu/$menu_display/btn_index_f2.gif',1);"><img name="btn_index" src="$images_dir/menu/$menu_display/btn_index.gif" border="0" alt=""></a></td>
           		<td><a href="$script_name?fid=$forum_id&search" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_search','','$images_dir/menu/$menu_display/btn_search_f2.gif',1);"><img name="btn_search" src="$images_dir/menu/$menu_display/btn_search.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&help" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_help','','$images_dir/menu/$menu_display/btn_help_f2.gif',1);"><img name="btn_help" src="$images_dir/menu/$menu_display/btn_help.gif" border="0" alt=""></a></td>
			$admin_menu
			$login_menu
			</tr><table>
HTML
		} else {
			$menu = <<HTML;
			<$standardfont>$subtitle</font><br><br>
			<table><tr>
			<td><a href="$home_url" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_home','','$images_dir/menu/$menu_display/btn_home_f2.gif',1);"><img name="btn_home" src="$images_dir/menu/$menu_display/btn_home.gif" border="0" alt=""></a></td>
			<td><a href="$script_name" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_index','','$images_dir/menu/$menu_display/btn_index_f2.gif',1);"><img name="btn_index" src="$images_dir/menu/$menu_display/btn_index.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&search" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_search','','$images_dir/menu/$menu_display/btn_search_f2.gif',1);"><img name="btn_search" src="$images_dir/menu/$menu_display/btn_search.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&help" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_help','','$images_dir/menu/$menu_display/btn_help_f2.gif',1);"><img name="btn_help" src="$images_dir/menu/$menu_display/btn_help.gif" border="0" alt=""></a></td>
			$admin_menu
			$login_menu
			</tr></table>
HTML
		}
	} else {
		if ($forum_id) {
			$menu = <<HTML;
			<$standardfont>$forum_name</font><br><br>
			<table><tr>
			<td><a href="$home_url" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_home','','$images_dir/menu/$menu_display/btn_home_f2.gif',1);"><img name="btn_home" src="$images_dir/menu/$menu_display/btn_home.gif" border="0" alt=""></a></td>
    			<td><a href="$script_name?fid=$forum_id&search" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_search','','$images_dir/menu/$menu_display/btn_search_f2.gif',1);"><img name="btn_search" src="$images_dir/menu/$menu_display/btn_search.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&help" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_help','','$images_dir/menu/$menu_display/btn_help_f2.gif',1);"><img name="btn_help" src="$images_dir/menu/$menu_display/btn_help.gif" border="0" alt=""></a></td>
			$admin_menu
			$login_menu
			</tr></table>
HTML
		} else {
			$menu = <<HTML;
			<$standardfont>$subtitle</font><br><br>
			<table><tr>
			<td><a href="$home_url" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_home','','$images_dir/menu/$menu_display/btn_home_f2.gif',1);"><img name="btn_home" src="$images_dir/menu/$menu_display/btn_home.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&search" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_search','','$images_dir/menu/$menu_display/btn_search_f2.gif',1);"><img name="btn_search" src="$images_dir/menu/$menu_display/btn_search.gif" border="0" alt=""></a></td>
			<td><a href="$script_name?fid=$forum_id&help" onMouseOut="MM_swapImgRestore();" onMouseOver="MM_swapImage('btn_help','','$images_dir/menu/$menu_display/btn_help_f2.gif',1);"><img name="btn_help" src="$images_dir/menu/$menu_display/btn_help.gif" border="0" alt=""></a></td>
			$admin_menu
			$login_menu
			</tr></table>
HTML
		}
	}
	$menu_buttons_head_script = <<SCRIPT;
<script language="JavaScript">
<!-- hide
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

// stop hiding -->
</script>
SCRIPT
	$menu_buttons_body_script = <<SCRIPT;
  <script language="JavaScript">
  <!-- hide
  if (document.images) {
  btn_home_f2 = new Image(); btn_home_f2.src = "$images_dir/menu/$menu_display/btn_home_f2.gif";
  btn_home_f1 = new Image(); btn_home_f1.src = "$images_dir/menu/$menu_display/btn_home.gif";
  btn_index_f2 = new Image(); btn_index_f2.src = "$images_dir/menu/$menu_display/btn_index_f2.gif";
  btn_index_f1 = new Image(); btn_index_f1.src = "$images_dir/menu/$menu_display/btn_index.gif";
  btn_search_f2 = new Image(); btn_search_f2.src = "$images_dir/menu/$menu_display/btn_search_f2.gif";
  btn_search_f1 = new Image(); btn_search_f1.src = "$images_dir/menu/$menu_display/btn_search.gif";
  btn_help_f2 = new Image(); btn_help_f2.src = "$images_dir/menu/$menu_display/btn_help_f2.gif";
  btn_help_f1 = new Image(); btn_help_f1.src = "$images_dir/menu/$menu_display/btn_help.gif";
  btn_admin_f2 = new Image(); btn_admin_f2.src = "$images_dir/menu/$menu_display/btn_admin_f2.gif";
  btn_admin_f1 = new Image(); btn_admin_f1.src = "$images_dir/menu/$menu_display/btn_admin.gif";
  btn_login_f2 = new Image(); btn_login_f2.src = "$images_dir/menu/$menu_display/btn_login_f2.gif";
  btn_login_f1 = new Image(); btn_login_f1.src = "$images_dir/menu/$menu_display/btn_login.gif";
  btn_logout_f2 = new Image(); btn_logout_f2.src = "$images_dir/menu/$menu_display/btn_logout_f2.gif";
  btn_logout_f1 = new Image(); btn_logout_f1.src = "$images_dir/menu/$menu_display/btn_logout.gif";
  btn_register_f2 = new Image(); btn_register_f2.src = "$images_dir/menu/$menu_display/btn_register_f2.gif";
  btn_register_f1 = new Image(); btn_register_f1.src = "$images_dir/menu/$menu_display/btn_register.gif";
  btn_personal_f2 = new Image(); btn_personal_f2.src = "$images_dir/menu/$menu_display/btn_personal_f2.gif";
  btn_personal_f1 = new Image(); btn_personal_f1.src = "$images_dir/menu/$menu_display/btn_personal.gif";
  }
  // stop hiding -->
  </script>
SCRIPT
}

# # # # HTML # # # #
print <<HTML;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>
<meta http-equiv="content-type" content="text/html;charset=$lang_charset">
<meta name="author" content="Daan Deconinck">
<meta name="description" content="A SimpleForum forum">
<meta name="keywords" content="perl, script, forum, cgi">
<meta name="robots" content="all">
<META name="revisit-after" content="1 days">
<META name="copyright" content="2003">
<title>$title</title>
$menu_buttons_head_script
</head>

<style type='text/css'>
<!--

/* The general font for your forum -- Values are determined in the Admin Area */
	.standardfont,body,td,th,input,submit,select,textarea,caption	{font-family:$fontface; font-size:$fontsize\pt; color:$fontcolor;}

/* The big font for your forum -- This is the standardfont size + 1pt */
	.bigfont 	{font-family:$fontface; font-size:$bigsize\pt; color:$fontcolor;}

/* The small font for your forum -- Values are determined in the Admin Area */
	.smallfont 	{font-family:$fontface; font-size:$fontsizesmall\pt; color:$fontcolor;}

/* Makes text invisible */
	.hidden { display: none; }

A {text-decoration:none;}
	A:Link 		{color:$link_color;text-decoration:none;}
	A:Hover 	{color:$link_hover_color;text-decoration:none;}
	A:active 	{color:$link_color;text-decoration:none;}
	A:visited	{color:$visited_link_color;text-decoration:none;}
	A:visited:link  {color:$visited_link_color;text-decoration:none;}
	A:visited:hover	{color:$link_hover_color;text-decoration:none;}

/* Form elements */
input,submit,select,textarea {
	background: $backgroundcolor;
	border: 1px $fontcolor solid;
	margin: 1px 1px}
.checkbox,.radio {
	border: 0px;
	margin: 0px 0px}
-->
</style>

<script language="JavaScript" type="text/javascript">
<!--
function divHide(id,mode)
{
    if (document.getElementById)
    {
        if(mode == 'show')
        {
          document.getElementById(id).style.display = 'block';
        }
        else
        {
          document.getElementById(id).style.display = 'none';
        }
    }
    else if(document.all)
    {
        if(mode == 'show')
        {
          document.all[id].style.display = '';
        }
        else
        {
          document.all[id].style.display = 'none';
        }
    }
}

HTML

if ($smileys eq "on" and !$qs) {
#preload the smileys, only when in forum index (to increase speed in other parts)
print "<!-- Begin Preload of Smileys\n\n";
	#preload the smileys
	if (-e "$smileys_dir") {
		open_dir($smileys_dir);
		foreach $image(@files) {
			chomp $image;
			if ($image =~ /\.gif$/s) {
				$smileys_preload_count++;
				print "image$smileys_preload_count = new Image();\nimage$smileys_preload_count.src = \"$smileys_dir/$image\";\n";
			}
		}
	}
print "// End -->\n\n";
}

print <<HTML;
function window_open(filename, x, y)
{
windowops = eval("'width=" + x + ",height=" + y + "'");
window.open(filename, 'simpleforum', windowops);
return;
}
//-->
</script>

$pmsg_popup_script

<body bgcolor="$backgroundcolor" background='$backgroundimage' bgproperties='fixed' $onload>
$menu_buttons_body_script
HTML
if (!$no_title) {
	print <<HTML;
	<center><font size='+2'><b>$title</b></font>
	<br><$smallfont>$menu</font></center><br>
HTML
}
# # # END HTML # # #
}


sub print_forum_index {
	open_dir($simpleforum_dir);

	print <<HTML;
	<center>
	<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor">
	<caption>
		<table border='0' width='100%' cellspacing=0 cellpadding=0>
			<tr>
				<td align='left' valign='bottom'><$bigfont><b>.: $lang_forum_index :.</b></font></td>
				<td align='right'>
HTML
	print &select_a_forum;
	print <<HTML;
			</td>
			</tr>
		</table>
	</caption>
	<tr>
		<td bgcolor="$tablecolor1" width='30'>&nbsp;</td>
		<td bgcolor="$tablecolor1" align='left'><font style='font-size:$bigsize\pt'><b>$lang_forum</b></font></td>
		<td bgcolor="$tablecolor2" align='center' width='50'><font style='font-size:$bigsize\pt'><b>$lang_topics</b></td>
		<td bgcolor="$tablecolor2" align='center' width='170'><font style='font-size:$bigsize\pt'><b>$lang_last_post</b></td>
	</tr>
HTML

	foreach $file(sort(@files)) {
		$topic_amount = 0;
		if ($file =~ /^(forum_(\d*))$/) {
			$forum_amount++;
			$forum_dir = $1;
			$fid = $2;
			open(INFO, "< $simpleforum_dir/$forum_dir/forum.info") or dienice("Couldn't open $simpleforum_dir/$forum_dir/forum.info: $!");
			$forum_info = join '', <INFO>;
			close INFO;
			if ($forum_info =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = add_html($1); }
			if ($forum_info =~ /<forum_more>(.*?)<\/forum_more>/s) { $forum_more = add_html($1); }
			if ($forum_info =~ /<forum_mods>(.*?)<\/forum_mods>/s) { $forum_mods = $1; }
			@forum_moderators = split(/\|/,$forum_mods);
			$forum_moderators = ""; $modcomma = "";
			foreach $forum_moderator(sort @forum_moderators) {
				open(PRF, "< $users_dir/$forum_moderator.prf");
				flock PRF, 2;
				while (<PRF>) {
					if (/<user_name>(.*?)<\/user_name>/) {
						$forum_moderators .= "$modcomma $1";
						$modcomma = ",";
					}
				}
				close PRF;
			}
			if ($forum_moderators) { $forum_moderators = "<br>\n<$smallfont><i>$lang_moderator: $forum_moderators</i></font>"; }

			opendir(FDIR, "$simpleforum_dir/$forum_dir") or dienice("Couldn't open FDIR: $!"); @forumdir_files = readdir FDIR; closedir FDIR;
			foreach $ffile(@forumdir_files) {
				if ($ffile =~ /^(\d*).topic$/) {
					$topic_amount++;
					($mtime) = (stat("$simpleforum_dir/$forum_dir/$ffile")) [9];
					push @topic_files, "$mtime\|$ffile";
				}
			}

			@topic_files = reverse(sort(@topic_files));

			$last_topic = $topic_files[0];
			($mtime,$last_topic) = split(/\|/, $last_topic);

			if ($last_topic) {
				open(LTOPIC, "< $simpleforum_dir/$forum_dir/$last_topic") or dienice("Couldn't open LTOPIC ($last_topic): $!");
					$ltopic_content = join '', <LTOPIC>;
				close LTOPIC;
				if ($ltopic_content =~ /.*(<post>.*?<name>(.*?)<\/name>.*?<time>(\d*)<\/time>.*?<\/post>).*?$/s) {
					$ltopic_content = $1; # cut down ltopic_content to only the very last post in the topic
					$last_posted_name = $2;
					$last_posted_time = $3;
					if (-e "$users_dir/$last_posted_name.prf" and $ltopic_content !~ /<status>guest<\/status>/s) {
						open PRF, "$users_dir/$last_posted_name.prf";
							while (<PRF>) {
								if (/<user_name>(.*?)<\/user_name>/) {
									$last_posted_name = "<a href=\"$script_name?pid=$last_posted_name\">$1</a>";
								}
							}
						close PRF;
					}
					$last_posted_name = "<br>\n$lang_by ".$last_posted_name;

					date_time($last_posted_time);
					$forum_index_date = "$date @ $hour:$min $ampm";
				}
			} else {
				$last_posted_name = "";
				$forum_index_date = $lang_no_topics_yet;
				$last_posted_time = "";
			}
			if ($last_posted_time > $oldvisit) { $icon = "newpost_small.gif"; } else { $icon = "post_small.gif"; }

			print <<HTML;
			<tr>
				<td bgcolor="$tablecolor1" align='center'><a href='$script_name?fid=$fid'><img src='$images_dir/post_icons/$icon' border='0'></a></td>
				<td bgcolor="$tablecolor1" align='left'><font style='font-size:$bigsize\pt'><b><a href='$script_name?fid=$fid'>$forum_name</a></b></font><br>\n$forum_more$forum_moderators</td>
				<td bgcolor="$tablecolor2" align='center'>$topic_amount</td>
				<td bgcolor="$tablecolor2" align='center'>$forum_index_date$last_posted_name</td>
			</tr>
HTML
			$at_least_one_forum_printed = 1;
			$last_posted_time = "";
			$last_posted_name = "";
			$last_topic = "";
			$set = "";
			@topic_files = ();
			$new = "";
		}
	}
	if (!$at_least_one_forum_printed) {
		print <<HTML;
		<tr>
			<td colspan=4 bgcolor='$tablecolor1'><i>$lang_no_forums_yet_long</i></td>
		</tr>
HTML
	}
	print "</table>\n";
#	if ($forum_amount > 2) {
#		print "<div style='width:$tablewidth;' align='right'>$select_a_forum</div>\n\n";
#	} else { print "<br>\n"; }
	print "<br>";
	#print statistics
	&statistics;
}


sub print_topic_index {
	#get all the topic files

		open_dir($topic_dir);

		@topics = @files;

		#filter the topic files from the files in topic_dir
		foreach $tpc(@topics) {
			if ($tpc =~ /(.*?).topic$/s) {
				($mtime) = (stat("$topic_dir/$tpc")) [9];
				push @lastmodifiedtopics, "$mtime\|$tpc";
			}
		}
		@topics = ();
		foreach $lastmodifiedtopic(reverse(sort(@lastmodifiedtopics))) {

			$lastmodifiedtopic =~ s/(.*?)\|(.*?).topic/$2.topic/s;
			push @available_topics, $lastmodifiedtopic;
		}


		#we only need a certain amount of topics to print on our index
		$page = param('page');
		if ($page == 0) { $page++; }
		$startnumber = ($page - 1) * $topics_per_page;
		$less_than = $startnumber + $topics_per_page;
		for ($startnumber; $startnumber < $less_than; $startnumber++) {
			push(@topics,$available_topics[$startnumber]);
		}



		# # # # print all the topics in subroutine print_topic_list
		&print_topic_list;
		# # # # end of topiclist

		$lastpage = ($#available_topics + 1) / $topics_per_page;
		if ($lastpage != int($lastpage)) { $lastpage = int($lastpage) + 1; }
		#$lastpage = " <a href='$script_name?fid=$forum_id&page=$lastpage'>last &raquo;&raquo;</a>";
		$amount_of_pages = $lastpage;
		if ($page > 1) { $previouspage = $page - 1;}
		if ($page < (($#available_topics + 1) / $topics_per_page)) { $nextpage = $page + 1; }
		if ($nextpage) {$nextpage = "<a href='$script_name?fid=$forum_id&page=".$nextpage."'>$lang_next &raquo;</a>"; } else {$nextpage = "$lang_next &raquo;";}
		if ($previouspage) { $previouspage = "<a href='$script_name?fid=$forum_id&page=".$previouspage."'>&laquo; $lang_previous</a> - "; } else {$previouspage = "&laquo; $lang_previous - ";}

		# # # # HTML # # # #
		if ($topics_per_page > 5) {
			print <<HTML;
			<table border='0' cellspacing='0' cellpadding='0' width='$tablewidth'>
			<tr>
				<td align='left'>
				<$smallfont>$previouspage $nextpage<br>\n($page $lang_out_of $amount_of_pages)</font>
				</td>
			</tr>
			</table>
HTML
		}
		if ($topic_index_statistics eq "yes") { print "<BR>"; &statistics; }
	# # # END HTML # # #

}


sub print_topic_list {
	if ($qs =~ /search/) { $forum_name = "Search"; }
	# # # # HTML # # # #
	print <<HTML;
	<center>
    <table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor='$tablecolor3'>
    <caption>
		<table border='0' width='100%' cellspacing=0 cellpadding=0>
			<tr>
				<td align='left' valign='bottom'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <i>$forum_name</i></b></font></td>
				<td align='right'>
HTML
			print &select_a_forum;
			print <<HTML;
			</td>
			</tr>
		</table>
	</caption>
    	<tr>
    		<th bgcolor="$tablecolor1" align='middle' width='30'>&nbsp;</th>
    		<th bgcolor="$tablecolor1" align='left'>$lang_topic</th>
    		<th bgcolor="$tablecolor2" align='center' width='70'>$lang_replies</th>
    		<th bgcolor="$tablecolor2" align='center' width='120'>$lang_author</th>
    		<th bgcolor="$tablecolor2" align='center' width='70'>$lang_views</th>
    		<th bgcolor="$tablecolor2" align='center' width='180'>$lang_last_post</th>
    	</tr>
HTML
	# # # END HTML # # #
#open, read and print topic content

		foreach $topic(@topics) {
			if ($topic =~ /^(forum_(\d*))\/(\d*\.topic)$/s) { #this only happens when you perform a search
				$topic_dir = "$simpleforum_dir/$1";
				$forum_id = $2;
				$topic = $3;
				$highlight = "&highlight=$searchkey";
			}
			if ($topic =~ /(.*?).topic$/sg) {
				$topic_id = $1;
				$topic_replies = 0;
				#open the topic
				open(TOPIC,"< $topic_dir/$topic") or dienice("Couldn't open $topic_dir/$topic: $!");
				$topic_content = join '', <TOPIC>;
				close TOPIC;
				open(STATS,"< $simpleforum_dir/viewcount.sf");
				$stats_content = join '', <STATS>;
				close STATS;

				#get necessary content
				if ($topic_content =~ /<name>(.*?)<\/name>/s) {
					$topic_name = $1;
					# if this is a known user, get his real user name
					if (-e "$users_dir/$topic_name.prf") {
						open PRF, "$users_dir/$topic_name.prf";
							while (<PRF>) {
								if (/<user_name>(.*?)<\/user_name>/) {
									$topic_name = "<a href=\"$script_name?pid=$topic_name\">$1</a>";
								}
							}
						close PRF;

					}
				}
				if ($topic_content =~ /<subject>(.*?)<\/subject>/s) {
					$topic_subject = $1;
				}
				if ($stats_content =~ /<$topic_id>(.*?)\n/s) {
					$topic_views = $1;
				} else { $topic_views = 0; }
				if ($topic_content =~ /(.*)<name>(.*?)<\/name>(.*?)<time>(.*?)<\/time>(.*?)$/s) {
					$topic_lastpost_name = $2;
					$topic_lastpost_time = $4;
				}
				#find out how many replies on the topic
				while ($topic_content =~ /<post>/sg) {
					$topic_replies++;
				}
				$topic_replies--;

				if ($topic_lastpost_time > $oldvisit) {
					#new topic
					if ($topic_replies > ($popularnumb - 1)) {
						#popular
						$icon = "newpopular_small.gif";
					} else {
						#not popular
						$icon = "newpost_small.gif";
					}
				} else {
					#old topic
					if ($topic_replies > ($popularnumb - 1)) {
						#popular
						$icon = "popular_small.gif";
					} else {
						#not popular
						$icon = "post_small.gif";
					}
				}

				#if the lastpost sender is a known user, get the username from profile
				if (-e "$users_dir/$topic_lastpost_name.prf") {
					open PRF, "$users_dir/$topic_lastpost_name.prf";
						while (<PRF>) {
							if (/<user_name>(.*?)<\/user_name>/) {
								$topic_lastpost_name = "<a href=\"$script_name?pid=$topic_lastpost_name\">$1</a>";
							}
						}
					close PRF;
				}

				#page navigation
				$amount_of_pages = ($topic_replies + 1) / $posts_per_page;
				if ($amount_of_pages != int($amount_of_pages)) {
					$amount_of_pages = int($amount_of_pages) + 1;
				}
				if ($amount_of_pages > 1) {
					$page_navigation = "<$smallfont><br>&nbsp;&raquo; ";
					for ($i = 1; $i <= $amount_of_pages; $i++) {
						$page_navigation .= "<a href='$script_name?fid=$forum_id&topic_id=$topic_id&page=$i'>$i</a> ";
					}
					$i--;
					$page_navigation .= "<a href='$script_name?fid=$forum_id&topic_id=$topic_id&page=$i'>$lang_last</a></td>";
				} else {
					$page_navigation = "";
				}

				#print the shiz :)
				date_time($topic_lastpost_time);

				$topic_subject = add_html($topic_subject);
				# # # # HTML # # # #
				print <<HTML;
				<tr>
					<td align='center'><a href='$script_name?fid=$forum_id&topic_id=$topic_id$highlight'><img src='$images_dir/post_icons/$icon' border='0'></a></td>
					<td><a href='$script_name?fid=$forum_id&topic_id=$topic_id$highlight'>$topic_subject</a>$page_navigation</td>
					<td align='center'>$topic_replies</td>
					<td align='center'>$topic_name</td>
					<td align='center'>$topic_views</td>
					<td align='center'><$smallfont>$date \@ $hour:$min $ampm<br>$lang_by $topic_lastpost_name</td>
				</tr>

HTML
			# # # END HTML # # #

			}
		}
		if (!$topic_id) {
			#no topics posted
			print <<HTML;
			<tr>
				<td colspan=6><i>$lang_no_topics_yet_long</i></td>
			</tr>
HTML
		}
		print "</table>";
}


sub print_topic {
	# close or re-open a topic
	if (param('action') eq "close" or param('action') eq "open" and ($admin_access or $moderator_access)) {
		open(TPC, "+>> $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic file: $!");
		flock TPC, 2;
		seek TPC, 0, 0;
		$tpc_content = join '', <TPC>;
		truncate TPC, 0;
		if (param('action') eq "close") { print TPC "<CLOSED>\n\n"; }
		else { $tpc_content =~ s/<CLOSED>\n\n//sg; }
		print TPC $tpc_content;
		close TPC;
	}

	# unsubscribe to a topic
	if (param('action') eq "unsubscribe") {
		open (TOPIC, "+>> $topic_dir/$topic_id.topic") or dienice("Couldn't open $topic_dir/$topic_id.topic");
		flock TOPIC, 2;
		seek TOPIC, 0, 0;
		$tpc_content = join '', <TOPIC>;
		seek TOPIC, 0, 0;
		truncate TOPIC, 0;
		$tpc_content =~ s/<subscribe>(.*?)\|$user<\/subscribe>\n/<subscribe>$1<\/subscribe>\n/s;
		$tpc_content =~ s/<subscribe>$user\|(.*?)<\/subscribe>\n/<subscribe>$1<\/subscribe>\n/s;
		$tpc_content =~ s/<subscribe>$user<\/subscribe>\n/<subscribe><\/subscribe>\n/s;
		$tpc_content =~ s/<subscribe>(.*?)\|$user\|(.*?)<\/subscribe>\n/<subscribe>$1\|$2<\/subscribe>\n/s;
		print TOPIC $tpc_content;
		close TOPIC;
	}

	#open the specific topic
	open(TOPIC,"< $topic_dir/$topic_id.topic") or dienice("Couldn't open $topic_dir/$topic_id.topic");
	$topic_content = join '', <TOPIC>;
	close TOPIC;


	#write stats for the topic
	open (STATS, "+>> $simpleforum_dir/viewcount.sf") or dienice("Couldn't open viewcount file: $!");
	flock STATS, 2;
	seek STATS, 0, 0;
	$stats_content = join '', <STATS>;
	seek STATS, 0, 0;
	truncate STATS, 0;
	if ($stats_content =~ /<$topic_id>(\d*)\n/) {
		$views = $1 + 1;
		$stats_content =~ s/<$topic_id>(\d*)\n/<$topic_id>$views\n/sg;
	} else {
		print STATS "<$topic_id>1\n";
	}
	print STATS $stats_content;
	close STATS;

	#if this is a read-only forum, act as if the topic is a "CLOSED" topic, EXCEPT if you have admin access
	open (FORUMINFO, "< $simpleforum_dir/forum_$forum_id/forum.info") or dienice("Couldn't open forum.info file for reading: $!");
	$forum_info = join '', <FORUMINFO>;
	close FORUMINFO;
	if ($forum_info =~ /<forum_perm>(.*?)<\/forum_perm>/s) { $forum_perm = $1; }
	if ($forum_perm eq "read-only" and !$admin_access and !$moderator_access) { $topic_closed = 1; }

	if ($topic_content =~ /<subject>(.*?)<\/subject>/s) { $topic_title = $1; }
	$original_topic_title = $topic_title;
	$topic_title = add_html($topic_title);

	# # # # HTML # # # #
	print <<HTML;
	<center>
	<table border='0' width='$tablewidth' cellspacing=0 cellpadding=0>
			<tr><td align='left' valign='top'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a> &raquo; <i>$lang_topic: $topic_title</i></b></font>
			<td align='right' valign='top'>
HTML
			print &select_a_forum;
			print <<HTML;
			<$smallfont><br>
			</tr>

		</table>
	</caption>

HTML
	# # # END HTML # # #

	# check if this is a closed topic
	if ($topic_content =~ /<CLOSED>/s) { $topic_closed = 1; }

	# check if the user is subscribed to this topic
	if ($topic_content =~ /<subscribe>(.*?)<\/subscribe>\n/ and $logged_in) { $subscribe = $1; if ($subscribe =~ /^$user$/ or $subscribe =~ /^$user\|(.*)/ or $subscribe =~ /(.*)\|$user$/) { $user_subscribed = 1; } }

	if ($qs =~ /page=(\d*)/s) {
		$page_start = $1;
		$topic_start = ($page_start * $posts_per_page) - ($posts_per_page - 1);
	} else {
		$topic_start = 1;
	}

	$topic_end = $posts_per_page + $topic_start;

	while ($topic_content =~ /<post>(.*?)<\/post>/sg) {
		#reset vars
		$post_user = ""; $post_avatar = ""; $post_title = ""; $post_posts = ""; $post_status = "";

		$post_number++;
		#get necessary content and print it
		if ($post_number >= $topic_start and $post_number < $topic_end) {
			$post_amount++;
			$post_content = $1;
			if ($post_content =~ /<name>(.*?)<\/name>/sg) {
				$post_name = $1;
			}
			if ($post_content =~ /<status>(.*?)<\/status>/sg) {
				$post_status = $1;
			}
			if ($post_content =~ /<email>(.*?)<\/email>/sg) {
				$post_email = $1;
			}
			if ($post_content =~ /<subject>(.*?)<\/subject>/sg) {
				$post_subject = $1;
			}
			if ($post_content =~ /<time>(.*?)<\/time>/sg) {
				$post_time = $1;
			}
			if ($post_content =~ /<message>(.*?)<\/message>/sg) {
				$post_message = $1;
			}
			if ($post_content =~ /<signature>(.*?)<\/signature>/sg) {
				$post_signature = $1;
			}

			if (-e "$users_dir/$post_name\.prf" and ($post_status ne "guest" and $post_status)) {
				$post_user = $post_name;
				# This is a known user! Get his avatar, name, post-amount, ...
				open(POST_PROFILE, "< $users_dir/$post_user\.prf");
					flock POST_PROFILE, 2;
					$post_profile = join '', <POST_PROFILE>;
				close POST_PROFILE;
				if ($post_profile =~ /<user_name>(.*?)<\/user_name>\n/s) {
					$post_name = "<a href=\"$script_name?pid=$post_user\">$1</a>";
				}
				if ($post_profile =~ /<user_avatar>(.*?)<\/user_avatar>\n/s) {
					$post_avatar = $1;
				}
				if ($post_profile =~ /<user_posts>(.*?)<\/user_posts>\n/s) {
					$post_posts = $1;
				}
				if ($post_profile =~ /<user_title>(.*?)<\/user_title>\n/s) {
					$post_title = $1;
				}
			} else {
				$post_title = $lang_guest;
			}

			$post_subject = add_html($post_subject); #add smileys, images, url's, ...
			$post_message = add_html($post_message);

			# highlight words
			if (param('highlight')) {
				$highlight = param('highlight');
				$post_message =~ s/($highlight)/<b><font color='$link_color'>$1<\/font><\/b>/sgi;
				$post_subject =~ s/($highlight)/<b><font color='$link_color'>$1<\/font><\/b>/sgi;
			}

			#This line takes care of the color switching
			if ($tablecolor eq $tablecolor1) { $tablecolor = $tablecolor2; } else { $tablecolor = $tablecolor1; }

			#These lines add the link to the email address to the Author's name
			if ($post_email and $show_email_addresses eq "on" and !$logged_in) {
				if ($post_email =~ /\@/s) { $post_email = "mailto:$post_email"; } else { $blanktarget = "target='_blank'"; }
				$post_name = "<a href='$post_email' $blanktarget>$post_name</a>";
			}

			#Make $post_time "readable" ;)
			date_time($post_time);

			#if the topic isn't closed, allow people to post a quoted reply (a reply to a specific topic)
			if (!$topic_closed) { $reply_to_this_post = "<a href='$script_name?fid=$forum_id&topic_id=$topic_id&reply=$post_time'>$lang_reply</a>"; }

			#print the quick delete link
			if ($admin_access or $moderator_access) {
				$quickdel_link = "| <a href='$script_name?fid=$forum_id&topic_id=$topic_id&quickdel=$post_time'>$lang_delete</a>";
			}

			# the edit link
			if ($post_user eq $user or $admin_access or $moderator_access) {
				$edit_this_post = "| <a href='$script_name?fid=$forum_id&topic_id=$topic_id&edit=$post_time'>$lang_edit</a>";
			}

			# the move topic & delete entire topic form/link
			if ($admin_access or $moderator_access) {
			if (!$move_topic_printed) {
			open_dir($simpleforum_dir);

			$move_topic = <<HTML;
			<div id='move_topic_link'><br><a href="javascript:divHide('move_topic_form','show');divHide('move_topic_link','hide');">$lang_move_topic</a><br><a href="javascript:divHide('confirm_delete','show');divHide('move_topic_link','hide');">$lang_delete_topic</a></div>
			<div id='move_topic_form' class='hidden'><br>
			<select name="fid" onChange="location.href=this.options[this.selectedIndex].value" size="1" style='font-family:$fontface; font-size:$fontsizesmall\pt; background-color:$backgroundcolor; color:$fontcolor;'>
			<option value="$script_name?fid=$forum_id&topic_id=$topic_id" selected>&raquo; $lang_move_topic_to</option>
HTML


			foreach $file(sort(@files)) {
				if ($file =~ /^(forum_(\d*))$/) {
					$forum_dir = $1;
					$fid = $2;
					open(INFO, "< $simpleforum_dir/$forum_dir/forum.info") or dienice("Couldn't open $simpleforum_dir/$forum_dir/forum.info: $!");
					$forum_info = join '', <INFO>;
					close INFO;
					if ($forum_info =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = add_html($1); }
					if ($forum_info =~ /<forum_more>(.*?)<\/forum_more>/s) { $forum_more = add_html($1); }
					$move_topic .= <<HTML;
					<option value="$script_name?fid=$forum_id&move_topic=$fid&topic_id=$topic_id">$forum_name</option>
HTML
				}
			}
			$move_topic .= <<HTML;
			</select></div>
			<div id='confirm_delete' class='hidden'><br>$lang_delete_entire_topic?<br><a href='$script_name?fid=$forum_id&topic_id=$topic_id&quickdel=1'>$lang_yes</a> | <a href="javascript:divHide('move_topic_link','show');divHide('confirm_delete','hide');">$lang_no</a></div>
HTML
			$move_topic_printed = 1;
			} else { $move_topic = ""; }
			}

			# border color switching for new posts
			if ($post_time > $oldvisit) { $borderstyle = "style='border-color:#FF0000;'"; } else { $borderstyle = ""; }

			# determine the user's title
			if (!$post_title and $enable_user_titles eq "on") {
				if ($post_posts < $title_lvl2_posts) { $post_title = $title_lvl1; }
				elsif ($post_posts < $title_lvl3_posts) { $post_title = $title_lvl2; }
				elsif ($post_posts < $title_lvl4_posts) { $post_title = $title_lvl3; }
				elsif ($post_posts < $title_lvl5_posts) { $post_title = $title_lvl4; }
				elsif ($post_posts < $title_lvl6_posts) { $post_title = $title_lvl5; }
				elsif ($post_posts) { $post_title = $title_lvl6; }
			}

			# the signature
			if ($post_signature) {
				$post_signature = &add_html($post_signature."\n");
				$print_signature = "<br>_________________<br>$post_signature";
			} else { $print_signature = ""; }

			#Here we print ONE post from the entire topic, in a loop (while)
			# # # # HTML # # # #
			print <<HTML;
			<br>
			<table width='$tablewidth' border='0' cellspacing='0' cellpadding='0'><tr><td><div align='right'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div></td></tr></table>
			<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor" $borderstyle>
			<tr>
				<td align='left' width='150' valign='top'>
					<$bigfont><b>$post_name</b></font>
HTML
			# if $post_title exists and user titles are enabled
			if ($post_title and $enable_user_titles eq "on") { print "<br><$smallfont>$post_title</font>"; }
			if ($post_posts) { print "<br><$smallfont>$lang_posts: $post_posts</font>"; }
			print <<HTML;
					<br>
					<$smallfont><br>$reply_to_this_post $edit_this_post $quickdel_link $move_topic
					</font>
HTML
			if ($post_avatar) { print "<br><br><img src='$post_avatar' height='70' width='70'>"; }
			print <<HTML;
				</td>
				<td valign='top'>
					<$bigfont><b>$post_subject</b>
					<hr>
					$post_message
					$print_signature
				</tr>
			</tr>
			</table>
HTML
			# # # END HTML # # #
		}
	}

	#close topic link
	if (($admin_access or $moderator_access) and !$topic_closed) {
		$close_topic_text = "<td align='right'><$smallfont><a href='$script_name?fid=$forum_id&topic_id=$topic_id&action=close'>$lang_close $lang_topic</a></font></td>";
	} elsif ($admin_access or $moderator_access) {
		$close_topic_text = "<td align='right'><$smallfont><a href='$script_name?fid=$forum_id&topic_id=$topic_id&action=open'>$lang_open $lang_topic</a></font></td>";
	}

	#page navigation
	$amount_of_pages = $post_number / $posts_per_page;
	if ($amount_of_pages != int($amount_of_pages)) {
		$amount_of_pages = int($amount_of_pages) + 1;
	}
	if ($amount_of_pages > 1) {
		$page_navigation = "<td align='left'><$smallfont>$lang_page: ";
		for ($i = 1; $i <= $amount_of_pages; $i++) {
			if ($i eq $page_start) {
				$page_navigation .= "$i ";
			} else {
				$page_navigation .= "<a href='$script_name?fid=$forum_id&topic_id=$topic_id&page=$i'>$i</a> ";
			}
		}
		$i--;
		$page_navigation .= "<a href='$script_name?fid=$forum_id&topic_id=$topic_id&page=$i'>last</a></td>";
	}

	#topic table end (close topic, page navigation)
	if ($close_topic_text or $page_navigation) {
		print <<HTML;
		<table border='0' width='$tablewidth' cellspacing='0' cellpadding='0'>
			<tr>
				$page_navigation
				$close_topic_text
			</tr>
		</table>
HTML
	}

	if ($post_amount > 2) {
		print "<div align='right' style='width:$tablewidth;'>".&select_a_forum."</div>";
	} else {
		print "<br>\n";
	}
		# # # # HTML # # # #
	print "<a href='javascript:history.go(-1);'>$lang_back</a><br>";

	# check guest access; if read-only the user is not allowed to post
	if ($user eq "guest" and $guest_access eq "read-only") {
		print "<br><div align='center'><table border='0' width='70%'><tr><td align='center'>
		<$smallfont>[ To post a reply, please <a href='$script_name?login&ref=$qs_referer'>$lang_log_in</a> or <a href='$script_name?register'>$lang_register</a> ]
		</td></tr></table>
		</div>";
		return undef;
	}

	if (!$topic_closed and $post_number < $topic_end) {
		print <<HTML;
		<br><b>$lang_post_a_reply</b></p>
		</center>
HTML
		# # # END HTML # # #
		&post_form("reply_id=$topic_id"); #we use the same form for posting replies as for writing new topics
	}
}

sub print_profile {
	#print a requested user profile
	my($profile_id) = @_;

	if (!$profile_id or !-e "$users_dir/$profile_id\.prf") { dienice("Incorrect profile request"); }

	# read profile
	open(PROFILE, "< $users_dir/$profile_id\.prf") or dienice($!);
		@profile_content = <PROFILE>;
		$profile_content = join '', @profile_content;
	close PROFILE;

	# parse profile
	$profile_content =~ s/<user_(.*?)>(.*?)<\/user_(.*?)>\n/<profile_$1>$2<\/profile_$3>\n/sg;

	foreach $line (@profile_content) {
		chomp $line;
		$line =~ s/<user_(.*?)>(.*?)<\/user_(.*?)>/<profile_$1>$2<\/profile_$3>/sg;
		if ($line =~ /^<(profile_.*?)>(.*?)<\/(profile_.*?)>$/) {
			# a single-line variable
			$$1 = $2;
		}
	}
	if ($profile_content =~ /<profile_interests>(.*?)<\/profile_interests>\n/s) {
		$profile_interests = $1;
		$profile_interests =~ s/\n/<br>/sg;
	}

	# print profile
	open(FC, "< $simpleforum_dir/stats.sf") or die "Could not open stats: $!";
	$fc_text = join '', <FC>;
	close FC;
	if ($fc_text =~ /<msg_amount>(.*?)<\/msg_amount>/) { $forum_totalposts = $1; }
	$percent_of_total = sprintf("%.2f",($profile_posts/$forum_totalposts)*100);
	$posts_per_day = sprintf("%.2f",($profile_posts/((time - $profile_joindate)/86400)));
	$forumstats = "<$smallfont>[$percent_of_total% $lang_of_total / $posts_per_day $lang_posts_per_day]";

	&page_start;
	print <<HTML;
	<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <i>$lang_profiles</i></b></font></div>
	<center><br>
	<table border=1 cellspacing=0 cellpadding='10' bordercolorlight='gray' bordercolordark='#000000'>
		<CAPTION ALIGN=TOP STYLE="text-align:right" ><$bigfont><b>.: $profile_name :.</b></font></CAPTION>
		<tr>
			<!-- TD FOR AVATAR AND CONTACT -->
			<td valign='top'>
				<table border=0 cellspacing=0 cellpadding=0>
					<tr>
						<!-- TD for avatar -->
						<td align='center' valign='top'>
							<b>$lang_avatar</b>
							<br><br>
HTML
if ($profile_avatar) { print "<img src='$profile_avatar' width=100 height=100 border='0'>"; } else { print "<table border=1><tr><td height=100 width=100 valign='middle' align='center'>$lang_none</td></tr></table>"; }
	print <<HTML;
							<hr color='black' width='100%'>
						</td>
					</tr>
					<tr>
						<!-- TD for contact -->
						<td valign='top' align='center'>
							<b>$lang_contact</b>
							<br>
							<table border=0 cellspacing=7>
HTML
if ($enable_private_messages eq "on") {
	print <<HTML;
								<tr>
									<td valign='top' align='center' colspan=2><$smallfont><b><a href='$script_name?pmsg=1&sendto=$profile_id' target='_parent'>$lang_send_a_private_message_to $profile_name</a></b></td>
								</tr>
HTML
}
if ($profile_email and !$profile_hide_email) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'><$smallfont>$lang_email_address :</td>
									<td valign='top' align='left'><$smallfont><b><a href='mailto:$profile_email'>$profile_email</a></b></td>
								</tr>
HTML
}
if ($profile_icq) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'><$smallfont>$lang_icq_number :</td>
									<td valign='top' align='left'><$smallfont><b>
									<a href='http://wwp.icq.com/scripts/search.dll?to=$profile_icq' target='_blank'><img src='http://online.mirabilis.com/scripts/online.dll?icq=$profile_icq&img=5' height=15 width=15 border=0> $profile_icq</a></b></td>
								</tr>
HTML
}
if ($profile_aol) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'><$smallfont>$lang_aol_aim :</td>
									<td valign='top' align='left'><$smallfont><b><a href='aim:goim?screenname=$profile_aol&message=Hi.+Are+you+there?'>$profile_aol</b></td>
								</tr>
HTML
}
if ($profile_msn) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'><$smallfont>$lang_msn_messenger :</td>
									<td valign='top' align='left'><$smallfont><b>$profile_msn</b></td>
								</tr>
HTML
}
if ($profile_yahoo) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'><$smallfont>$lang_yahoo_messenger :</td>
									<td valign='top' align='left'><$smallfont><b>$profile_yahoo</b></td>
								</tr>
HTML
}
	print <<HTML;
							</table>
						</td>
					</tr>
				</table>
			</td>
			<!-- TD : ABOUT $profile_name -->
			<td valign='top' valign='top'>
				<table border=0 cellspacing=0 cellpadding=0>
					<tr>
						<td align='center'>
							<b>$lang_about $profile_name...</b><br>
							<table border=0 cellspacing=7>
								<tr>
									<td valign='top' align='right'>$lang_joined :</td>
									<td valign='top' align='left'><b>
HTML
									print date_time($profile_joindate);
print <<HTML;
									</b></td>
								</tr>
HTML
if ($profile_realname) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'>$lang_real_name :</td>
									<td valign='top' align='left'><b>$profile_realname</b></td>
								</tr>
HTML
}
if ($profile_location) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'>$lang_location :</td>
									<td valign='top' align='left'><b>$profile_location</b></td>
								</tr>
HTML
}
if ($profile_website) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'>$lang_website :</td>
									<td valign='top' align='left'><b><a href='$profile_website' target='_blank'>$profile_website</a></b></td>
								</tr>
HTML
}
if ($profile_occupation) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'>$lang_occupation :</td>
									<td valign='top' align='left'><b>$profile_occupation</b></td>
								</tr>
HTML
}
if ($profile_interests) {
	print <<HTML;
								<tr>
									<td valign='top' align='right'>$lang_interests :</td>
									<td valign='top' align='left'><b>$profile_interests</b></td>
								</tr>
HTML
}
	print <<HTML;
								</b></font>
							</td>
						</tr>
						<tr>
							<td valign='top' align='right'>$lang_forum_posts :</td>
							<td valign='top' align='left'><b>$profile_posts</b>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td><font class='tabletext'>
								$forumstats
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</td>
</tr>
</table>
<br>
- [ <a href='javascript:history.go(-1);'>$lang_back</a> ] -
<br>
HTML
&page_end;
}


sub post_form {

	# check guest access; if read-only the user is not allowed to post
	if ($user eq "guest" and $guest_access eq "read-only") {
		print "<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a> &raquo; <i>$lang_new_topic</i></b></font></div><br>";
		print "<div align='center'><table border='0' width='70%'><tr><td align='center'>
		<$smallfont><b><i>-- In order to post a message, please <a href='$script_name?login&ref=$qs_referer'>$lang_log_in</a> or <a href='$script_name?register'>$lang_register</a><b></u></i> --</font>
		</td></tr></table><br>
		</div>";
		&login;
		return undef;
	}

	# check the permissions for this forum
	open(FORUM_INFO, "< $simpleforum_dir/forum_$forum_id/forum.info") or dienice("Couldn't open forum.info for reading: $!");
	$forum_info_content = join '', <FORUM_INFO>;
	close FORUM_INFO;

	# if this is the post form below a preview of a post, $message and $subject need to be defined
	if (param('preview')) {
		$subject = param('subject');
		$textarea_content = param('message');
		$cookie_name = param('name'); # replace the cookie name by the new name
		$cookie_email = param('email'); # replace the cookie email by the new one
		if (param('subscribe')) { $subscribe_checked = "CHECKED"; }
		$attachment = param('attachment');
	}

	# check if this is a read-only forum and only give access to admins and moderators
	if ($forum_info_content =~ /<forum_perm>(.*?)<\/forum_perm>/s) {
		$forum_perm = $1;
		if ($forum_perm eq 'read-only' and !$admin_access and !$moderator_access) {
			print "<center>$lang_read_only_forum_not_authorized<br><br><a href='javascript:history.go(-1)'>$lang_back</a>";
			return undef;
		}
	}

	my($type) = @_;

	if ($original_topic_title) { $replyto_topic_title = "Re: ".$original_topic_title; }

	# print the form
	if ($type eq "post" and !param('preview')) {
		print "<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a> &raquo; <i>$lang_new_topic</i></b></font></div><br>";
	}
	if ($msg_id) { #reply to a specific post
		open(REPLY, "< $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic for reading: $!");
			$reply_content = join '', <REPLY>;
		close REPLY;

		# check if the user is subscribed to this topic
		if ($reply_content =~ /<subscribe>(.*?)<\/subscribe>\n/ and $logged_in) { $subscribe = $1; if ($subscribe =~ /^$user$/ or $subscribe =~ /^$user\|(.*)/ or $subscribe =~ /(.*)\|$user$/) { $user_subscribed = 1; } }

		if ($reply_content =~ /(.*)(<post>(.*?)<time>$msg_id<\/time>(.*?)<\/post>)(.*)/s) {
			$reply_content = $2;
			if ($reply_content =~ /<name>(.*?)<\/name>/s) { $reply_name = $1; }
			if ($reply_content =~ /<status>(.*?)<\/status>/s) { $reply_status = $1; }
			if ($reply_content =~ /<ip>(.*?)<\/ip>/s) { $reply_ip = $1; }
			if ($reply_content =~ /<email>(.*?)<\/email>/s) { $reply_email = $1; }
			if ($reply_content =~ /<message>(.*?)<\/message>/s) { $reply_message = $1; }
			if ($reply_content =~ /<subject>(.*?)<\/subject>/s) { $reply_subject = $1; }
		}
			date_time($msg_id);

		$reply_message =~ s/\n$//s;

		if ($reply_status eq "registered" and -e "$users_dir/$reply_name.prf") {
			# known user, get real name and email address
			open PRF, "$users_dir/$reply_name.prf";
				while (<PRF>) {
					if (/<user_name>(.*?)<\/user_name>/) { $reply_name = $1; }
					if (/<user_email>(.*?)<\/user_email>/) { $reply_email = $1; }
				}
			close PRF;
		}

		if ($reply_message =~ /(.*)\[quoted\]..(.*?)\[\/quoted\]/s) {
			$former_quote = $2;
			$former_quote =~ s/\n/\n> /sg;
			$former_quote =~ s/\n> $//sg;
			$reply_message =~ s/(.*)\[quoted\]..(.*?)\[\/quoted\]/$1> $former_quote/s;
		}
		$textarea_content = "\[quoted\]\nAt $hour:$min:$sec $ampm $short_date, $reply_name wrote:\n$reply_message\n\[\/quoted\]\n\n";
		$replyto_topic_title = $reply_subject;
		if ($mail eq "on" and $reply_email) {
			# Set the checkbox for email-reply
			$topic_url = $ENV{'HTTP_REFERER'};
			$emailreply = "<tr>
							<td>&nbsp;</td>
							<td><input type='checkbox' class='checkbox' name='send_mail' value='yes'><$smallfont> $lang_email_to $reply_name</font>
								<input type='hidden' name='send_mail_name' value='$reply_name'>
								<input type='hidden' name='send_mail_email' value='$reply_email'>
								<input type='hidden' name='send_mail_subject' value='$reply_subject'></td>
						</tr>";
		}
	}

	if ($mail eq "on" and $user_email) {
		# allow for registered users to subscribe to a topic, set the form in $subscribe
		if (!$user_subscribed) { # the user is not subscribed to this topic
			$subscribe = "<tr>
						<td>&nbsp;</td>
						<td><input type='checkbox' class='checkbox' name='subscribe' value='yes' $subscribe_checked><$smallfont> $lang_subscribe_to_this_topic</font></td>
					</tr>";
		} else { # the user is subscribed to this topic, allow him to unsubscribe
			$subscribe = "<tr><td>&nbsp;</td><td><$smallfont><a href='$script_name?fid=$forum_id&topic_id=$topic_id&action=unsubscribe'>$lang_unsubscribe</a></font></td></tr>";
		}
	} else {
		$subscribe = "";
	}

	#if ($admin_access and $type eq "post") {
	#	# Admins can make this post a sticky post, which means it will stick at the top of the topic list
	#	$make_sticky = "<tr>
	#						<td>&nbsp;</td>
	#						<td><input type='checkbox' class='checkbox' name='make_sticky' value='yes'><$smallfont> Make this post a <i>Sticky Post</i></font></td>
	#					</tr>";
	#}

	if ($attachments_uploadmax >= 1024000) {
		$max_attachment_size = ($attachments_uploadmax/1024000)."Mb";
	} else {
		$max_attachment_size = ($attachments_uploadmax/1024)."kb";
	}
	if (!$topic_url) { $topic_url = url(-path_info=>1,-query=>1); }
	# # # # HTML # # # #
	print <<HTML;
	<center>
	<form enctype="multipart/form-data" method='post' name='post_form' action='$script_name?fid=$forum_id&$type'>
	<input type='hidden' name='posted' value='yes'>
	<input type='hidden' name='topic_url' value='$topic_url'>
	<input type='hidden' name="topic_title" value="$topic_title">
	<input type='hidden' name='type' value='$type'>
HTML
	if ($logged_in) { print "<input type='hidden' name='logged_in' value='yes'>"; }
	print <<HTML;
	<center>
	<table border="1" cellspacing="0" cellpadding="30" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
	<tr><td>
	<table border=0>
HTML
		if ($logged_in) {
			print "<input type='hidden' name='name' value='$user'>\n";
		} else {
			print <<HTML;
	<tr>
		<th align='left'>$lang_name: </th>
		<td><input type='text' name='name' value='$cookie_name' style='width:200;'></td>
	</tr>
	<tr>
		<th align='left'>$lang_email: </th>
		<td><input type='text' name='email' value='$cookie_email' style='width:200;'></td>
	</tr>
HTML
		}
	print <<HTML;

	<tr>
		<th align='left'>$lang_subject: </th>
		<td><input type='text' name='subject' value='$replyto_topic_title$subject' style='width:450;'></td>
	</tr>
	<tr>
		<td align='left' valign='top'><b>$lang_message:</b><br>
HTML
	if ($allow_attachments eq "yes") {
		print <<HTML;
			<div id='add_attachment'><$smallfont><a href="javascript:divHide('attachment_form','show');divHide('add_attachment','hide');">[$lang_attachment]</a></div>
HTML
	}
	&print_emoticon_table;
	print <<HTML;
	</td>
		<td valign='top'><textarea wrap='soft' name='message' rows=10 style='width:450;'>$textarea_content</textarea></td>
	</tr>
	<tr>
		<th></th>
		<td><div class='hidden' id='attachment_form'><input type='file' name='attachment' style='width:450;'><br><$smallfont><i>$lang_maximum_attachment_size_allowed: $max_attachment_size</i></div></td>
	</tr>

	$make_sticky
	$emailreply
	$subscribe

	<tr>
		<td colspan=2 align='center'><input type='submit' value='$lang_send' style='width:100;'>
HTML
	if (!$msg_id) { # if this is not a specific reply to a post in a topic, allow a user to preview his post
		print "<input type='submit' value='Preview' name='preview' style='width:100;'>";
	}
	print <<HTML;
	</td>
	</tr>
	</table>
	</td></tr>
	</table>
	</center>
HTML
	# # # END HTML # # #
}

sub post_preview {
	# prints the preview page without the edit preview form, this form can be found in sub post_form
	$post_message = add_html(param('message'));
	$post_subject = add_html(param('subject'));
	$topic_title = param('topic_title');
	if ($topic_title) { $menu_topic_title = " &raquo; <a href='$script_name?fid=$forum_id&topic_id=$topic_id'>$lang_topic: $topic_title</a>"; }
	date_time(time); # set time
	if (&random_signature) {
		$print_signature = &add_html(&random_signature."\n");
		$print_signature = "<br><br>_________________<br>$print_signature";
	}

	if (!$logged_in) { $user_name = param('name'); $user_title = "Guest"; }
	print <<HTML;
	<center>
	<table border='0' width='$tablewidth' cellspacing=0 cellpadding=0>
			<tr><td align='left' valign='top'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a>$menu_topic_title &raquo; <i>Post Preview</i></b></font>
			<td align='right' valign='top'>
HTML
			print &select_a_forum;
			print <<HTML;
			<$smallfont><br>
			</tr>

		</table>
HTML
	print <<HTML;
	<br>
	<table width='$tablewidth' border='0' cellspacing='0' cellpadding='0'><tr><td><div align='right'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div></td></tr></table>
	<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor" $borderstyle>
	<tr>
		<td align='left' width='150' valign='top'>
			<$bigfont><b>$user_name</b></font>
HTML
	# if there's a user title and user titles are turned on print it
	if ($user_title and $enable_user_titles eq "on") { print "<br><$smallfont>$user_title</font>"; }
	if ($user_posts) { print "<br><$smallfont>$lang_posts: $user_posts</font>"; }
	print <<HTML;
			<br>
			<$smallfont><br>$reply_to_this_post $edit_this_post $quickdel_link $move_topic
			</font>
HTML
	if ($user_avatar) { print "<br><br><img src='$user_avatar' height='70' width='70'>"; }
	print <<HTML;
		</td>
		<td valign='top'>
			<$bigfont><b>$post_subject</b>
			<hr>
			$post_message
			$print_signature
		</tr>
	</tr>
	</table>

<br><b><center>Edit Preview</center></b><br>

HTML
}


sub verify_content {
	# check the user input

	# check the name field
	$name = param('name');
	if (!param('name')) {
		$error .= "<li>You forgot to enter your name</li>\n";
	}
	# check the email field on syntax
	if (param('email')) {
		$mailcheck = param('email');
		if ($mailcheck !~ /[\w\-]+\@[\w\-]+\.[\w\-]+/g) {
			$error .= "<li>\"$mailcheck\" is not a valid email address</li>\n";
		}
	}
	# check the subject field
	if (!param('subject')) {
		$error = $error."<li>You forgot to enter a subject</li>\n";
	}
	# check the message field, message is not required if there's an attachment
	if (!param('message') and !param('attachment')) {
		$error = $error."<li>You forgot to enter a message</li>\n";
	}
	# check if a guest's name isn't already used by a registered user
	if (!param('logged_in')) {
	 	open_dir($users_dir);
	 	foreach (@files) {
	 		if (/$name\.prf/i) {
				$error = $error."<li>The name you specified is already in use by a registered user, please choose a different name</li>\n";
			}
		}
	}
	# you can't have an attachment in previews, give an error if this is the case
	if (param('attachment') and param('preview')) {
		$error .= "<li>You cannot preview attachments, please preview your post without attachments and add it at the end before sending</li>\n";
	}
	# if any of the above checks results in an error, print the error and abort
	if ($error) {
		&page_start;
		print "<center><b>Your message has <u>not</u> been posted</b><br><br>\n<table border='0' width='60%'><tr><td>\n<ul>".$error."</ul></td></tr></table><a href='javascript:history.go(-1)'>$lang_back</a></center>";
		&page_end;
		exit;
	}

	# all fields are ok, store them in vars
	#[$name = param('name');] this is done above
	$subject = param('subject');
	$message = param('message');
	$email = param('email');

	# The part that takes care of the attachment
	$file = param("attachment");
	if ($file and $allow_attachments eq "yes") {
		if ($file =~ /(.*)\/(.*?)$/s) { #unix filesystem
			$filename = $2;
		} elsif ($file =~ /(.*)\\(.*?)$/s) { #windows filesystem
			$filename = $2;
		} else {
			$filename = $file;
		}
		#check if the file doesn't already exist
		if (-e "$attachments_dir/$filename") {
			dienice("$lang_upload_file_exists");
		}
		if ($ENV{'CONTENT_LENGTH'} > $attachments_uploadmax) {
			#file too large
			$attachments_uploadmax_kb = $attachments_uploadmax/1024;
			dienice("$lang_file_too_large $attachments_uploadmax_kb kb.");
		}
		$file_size = $ENV{'CONTENT_LENGTH'};
		if ($file_size >= 1024000) {
			$file_size_kbmb = sprintf("%.1f",($file_size/1024000))."Mb";
		} else {
			$file_size_kbmb = sprintf("%.2f",($file_size/1024))."kb";
		}
		# So far so good, now the only thing we need to do is upload the file
		#UPLOAD THE FILE
		if (!-e "$attachments_dir") {
			# attachments dir doesn't exist, so we need to creat this dir first
			mkdir("$attachments_dir",0777) or dienice("$!<br><br>If the above error sais \"Permission Denied\" this means that the attachments directory does not exist or that the script has not got the sufficient previleges to write the attachment to the attachments directory. Please create this directory and set its permissions (hint: chmod 777)");
		}
   		open(OUT,">$attachments_dir/$filename") or dienice("Couldn't write the attachment ($attachments_dir/$filename): $!");
			binmode OUT;
			flock OUT, 2;
			$flen = 0;
			while (read($file,$i,1024)) {
				print OUT $i;
				$flen = $flen + 1024;
				if ($flen > $attachments_uploadmax) {
					close(OUT);
				}
    		}
    	close(OUT);

		if ($message) { $message .= "\n\n"; }

		$ctype = uploadInfo($file)->{'Content-Type'};
		if ($ctype eq "image/gif" or $ctype eq "image/jpeg" or $ctype eq "image/pjpeg" or $ctype eq "image/png") {
			$attachments_url =~ s/^http:(\/\/(.*?))$/$1/s;
			$message .= "\[img:$attachments_url/$filename]";
		} else {
			$message .= "\[$lang_attachment: \[url=$attachments_url/$filename\]$filename\[/url\] ($file_size_kbmb)\]";
		}
	}
}


sub quick_delete {
	if ($dele_id == '1') {
		# delete entire topic
		unlink "$simpleforum_dir/forum_$forum_id/$topic_id.topic";
		&edit_statistics_file("tpc_amount--");
		print redirect("$script_name?fid=$forum_id");
		exit;
	}
	if (!$admin_access and !$moderator_access) { print "$lang_not_authorized<br>\n"; }
	if (!param('posted')) {
		&page_start;
		open (DELE, "< $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic for deletion.<br>Refresh the forum and try again.");
			$dele_content = join '', <DELE>;
		close DELE;
		if ($dele_content =~ /(.*)(<post>(.*?)<time>$dele_id<\/time>(.*?)<\/post>)(.*)/s) {
			$dele_content = $2;
			if ($dele_content =~ /<name>(.*?)<\/name>/s) { $dele_name = $1; }
			if ($dele_content =~ /<ip>(.*?)<\/ip>/s) { $dele_ip = $1; }
			if ($dele_content =~ /<email>(.*?)<\/email>/s) { $dele_email = $1; }
			if ($dele_content =~ /<message>(.*?)<\/message>/s) { $dele_message = $1; }
			if ($dele_content =~ /<subject>(.*?)<\/subject>/s) { $dele_subject = $1; }
		}
		&date_time($dele_id);
		# # # # HTML # # # #
		print <<HTML;
		<center>
		<form method='post' action='$script_name?fid=$forum_id&topic_id=$topic_id&quickdel=$dele_id'>
		<input type='hidden' name='posted' value='yes'>
		<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor1">
		<caption align='top'><div align='right'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div></caption>
HTML
		# # # END HTML # # #
		$dele_subject = add_html($dele_subject);
		$dele_message = add_html($dele_message);

		# # # # HTML # # # #
		print <<HTML;
		<tr>
			<th align='left' width='100'>$lang_author: </th>
			<td width='500'>$dele_name</td>
		</tr>
		<tr>
			<th align='left'>$lang_subject: </th>
			<td>$dele_subject</td>
		</tr>
		<tr>
			<th align='left' valign='top'>$lang_message: </th>
			<td>$dele_message</td>
		</tr>
		</table>
		<br>
		<input type='submit' value='$lang_delete'><input type='button' value='$lang_back' onClick='javascript:history.go(-1)'>
		<br><br><a href='javascript:history.go(-1)'>$lang_back</a>
		</form>
		</center>
HTML
		# # # END HTML # # #
		&page_end;
	} else {
		#delete message

		open(DELE, "+>> $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic for writing: $!");
			flock DELE, 2;
			seek DELE, 0, 0;
			$dele_content = join '', <DELE>;
			$dele_content =~ s/(.*)(<post>(.*?)<time>$dele_id<\/time>(.*?)<\/post>)(.*)/$1$5/s;
			seek DELE, 0, 0;
			truncate DELE, 0;
			print DELE $dele_content;
		close DELE;
		&edit_statistics_file("msg_amount--");
		if ($dele_content !~ /<post>/s) {
			#the topic is empty, delete the topic file!
			unlink "$simpleforum_dir/forum_$forum_id/$topic_id.topic";
			&edit_statistics_file("tpc_amount--");
		}
		print redirect("$script_name?fid=$forum_id");
	}
}

sub move_topic {
	# move topics from one subforum to another
	if (!$admin_access and !$moderator_access) { dienice("$lang_not_authorized"); } # double admin-only protection
	rename("$simpleforum_dir/forum_$move_topic_from/$topic_id.topic","$simpleforum_dir/forum_$move_topic_to/$topic_id.topic");
	# after moving, go back to the forum you were visiting
	print redirect("$script_name?fid=$move_topic_from");
}


sub edit {
	if (!param('posted')) {
		&page_start;
		open (EDIT, "< $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic for editing.<br>Refresh the forum and try again.");
			$edit_content = join '', <EDIT>;
		close EDIT;
		if ($edit_content =~ /(.*)(<post>(.*?)<time>$edit_id<\/time>(.*?)<\/post>)(.*)/s) {
			$edit_content = $2;
			if ($edit_content =~ /<name>(.*?)<\/name>/s) { $edit_name = $1; $edit_user = $1; }
			if ($edit_content =~ /<ip>(.*?)<\/ip>/s) { $edit_ip = $1; }
			if ($edit_content =~ /<email>(.*?)<\/email>/s) { $edit_email = $1; }
			if ($edit_content =~ /<message>(.*?)<\/message>/s) { $edit_message = $1; }
			if ($edit_content =~ /<subject>(.*?)<\/subject>/s) { $edit_subject = $1; }

			if ($edit_name eq $user) { # user editing his own post
				$edit_name = $user_name;
				$edit_posts = $user_posts;
				$edit_title = $user_title;
				$edit_avatar = $user_avatar;
			} else { # administrator/moderator editing someone else's post
				if (-e "$users_dir/$edit_name.prf") { # if it's a registered user, get his info
					open (PRF, "< $users_dir/$edit_name.prf") or dienice("Couldn't open the user's profile: $!");
					flock PRF, 2;
					while(<PRF>) {
						if (/<user_name>(.*?)<\/user_name>\n/s) { $edit_name = $1; }
						if (/<user_posts>(.*?)<\/user_posts>\n/s) { $edit_posts = $1; }
						if (/<user_avatar>(.*?)<\/user_avatar>\n/s) { $edit_avatar = $1; }
						if (/<user_title>(.*?)<\/user_title>/s) { $edit_title = $1; }
					}
					close PRF;
				} else { # if it's a guest, just set the title to "Guest"
					$edit_title = "Guest";
				}
			}
			if (!$edit_title) { # set the automatic title if no special title is set for this user
				if ($edit_posts < $title_lvl2_posts) { $edit_title = $title_lvl1; }
				elsif ($edit_posts < $title_lvl3_posts) { $edit_title = $title_lvl2; }
				elsif ($edit_posts < $title_lvl4_posts) { $edit_title = $title_lvl3; }
				elsif ($edit_posts < $title_lvl5_posts) { $edit_title = $title_lvl4; }
				elsif ($edit_posts < $title_lvl6_posts) { $edit_title = $title_lvl5; }
				elsif ($edit_posts) { $edit_title = $title_lvl6; }
			}
		}
		&date_time($edit_id);
		# # # # HTML # # # #
		print "<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a> &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a> &raquo; <a href='$script_name?fid=$forum_id&topic_id=$topic_id'>$lang_topic: $edit_subject</a> &raquo; <i>$lang_edit</i></b></font></div><br>";
		print <<HTML;
		<b><center>$lang_edit</center></b>
		<center>
		<form method='post' action='$script_name?fid=$forum_id&topic_id=$topic_id&edit=$edit_id'>
		<input type='hidden' name='posted' value='yes'>
		<table width='$tablewidth' border='0' cellspacing='0' cellpadding='0'><tr><td><div align='right'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div></td></tr></table>
		<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor" $borderstyle>
		<tr>
			<td align='left' width='150' valign='top'>
				<$bigfont><b>$edit_name</b></font>
HTML
		if ($edit_title and $enable_user_titles eq "on") { print "<br><$smallfont>$edit_title</font>"; }
		if ($edit_posts) { print "<br><$smallfont>$lang_posts: $edit_posts</font>"; }

	if ($edit_avatar) { print "<br><br><img src='$edit_avatar' height='70' width='70'>"; }
	print <<HTML;
		</td>
		<td valign='top'>
			<$bigfont><input type='text' name='subject' value='$edit_subject' style='width:470;'><br>
			<textarea wrap='soft' name='message' style='width:470; height:150;'>$edit_message</textarea>
		</tr>
	</tr>
	</table>

		<br>
		<input type='hidden' name='edit_user' value='$edit_user'>
		<input type='submit' value='$lang_edit'><input type='reset' value='$lang_revert'>
		<br><br><a href='javascript:history.go(-1)'>$lang_back</a>
		</form>
		</center>
HTML
		# # # END HTML # # #
		&page_end;
	} elsif ($admin_access or ($user eq param('edit_user') and $author_edit eq "on")) {
		#User authorized, edit topic
		$message = param('message');
		$subject = param('subject');
		if (!$message or !$subject) {
			&page_start;
			print "<center>";
			if (!$subject) { print "You have not entered a subject<br>\n"; }
			if (!$message) { print "You have not entered a message<br>\n"; }
			print "<br><a href='javascript:history.go(-1)'>$lang_back</a><br><br>";
			&page_end;
			exit;
		}

		open(EDIT, "+>> $simpleforum_dir/forum_$forum_id/$topic_id.topic") or dienice("Couldn't open topic for writing: $!");
			flock EDIT, 2;
			seek EDIT, 0, 0;
			$edit_content = join '', <EDIT>;
			if ($edit_content =~ /(.*)(<post>(.*?)<time>$edit_id<\/time>(.*?)<\/post>)(.*)/s) {
				$edit_post = $2;
				$edit_post =~ s/<subject>(.*?)<\/subject>/<subject>$subject<\/subject>/s;
				$edit_post =~ s/<message>(.*?)<\/message>/<message>$message\n<\/message>/s;
			}
			$edit_content =~ s/(.*)(<post>(.*?)<time>$edit_id<\/time>(.*?)<\/post>)(.*)/$1$edit_post$5/s;
			seek EDIT, 0, 0;
			truncate EDIT, 0;
			print EDIT $edit_content;
		close EDIT;
		print redirect("$script_name?fid=$forum_id");
	} else {
		&page_start; print "<center>$lang_not_authorized<br>"; &page_end;
	}
}


sub admin {

# 	I.		Forum Config
# 				1.	General
# 				2.	Look & Feel
# 				3.	Attachments
# 				4.	Mail Settings
# 				5.	Change Admin Password
# 				6.	Reset Forum Config
#
# 	II.		Forum Administration
# 				1.	Add/Edit/Delete Forums
# 				2.	Delete Topics
# 				3.	Manage Attachments
#
# 	III.	User Administration
# 				1.	User Permissions
#				2.	User Titles
#				3.	Delete Users
#				4.	Ban Users

	if ($admin_access) {
		if (param('admin_action') =~ /^1_(\d*)$/) {
			# Forum Configuration
			$admin_sub_action = $1;
			&forum_configuration;
		} elsif (param('admin_action') =~ /^2_(\d*)$/) {
			# Forum Administration menu
			$admin_sub_action = $1;
			&forum_administration;
		} elsif (param('admin_action') =~ /^3_(\d*)$/) {
			# User Administration menu
			$admin_sub_action = $1;
			&user_administration;
		} elsif (param('blockip')) {
			&add_ipblock;
		} else {
			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br>
			<a href='http://simpleforum.go.dyndns.org' target='_blank'><img border=0 src='http://www.holypaladins.com/~kadjiis/simpleforum/versioncheck.cgi?pro$version'></a>
			<br>
			<table border=0 width='50%'>
				<tr>
					<td>
						<ul>
							<li><b>Forum Configuration</b></p>
								<ul>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=1_1'>General</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=1_2'>Look & Feel</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=1_3'>Attachments</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=1_4'>Mail Settings</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=1_6'>Reset Forum Settings</a></li>
								</ul>
							</li>
							<br>
							<li><b>Forum Administration</b></p>
								<ul>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=2_1'>Add/Edit/Delete Forums</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=2_2'>Delete Topics and Messages</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=2_3'>Manage Attachments</a></li>
									<!-- <li><a href='$script_name?fid=$forum_id&admin=1&admin_action=2_4'>Censorship</a></li> -->

								</ul>
							</li>
							<br>
							<li><b>User Administration</b></p>
								<ul>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=3_1'>User Permissions</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=3_2'>User Titles</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=3_5'>Register Users</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=3_4'>Ban Users</a></li>
									<li><a href='$script_name?fid=$forum_id&admin=1&admin_action=3_3'>Delete Users</a></li>
							</li>
						</ul>
					</td>
				</tr>
			</table>
			</center>
HTML
		}
	} else {
		&page_start;
		print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br><br>
			You are not authorized!
			</center>
HTML
	}
}


sub forum_configuration {

	# This sub takes care of all the actions in the Forum Configuration menu in the Administrator Area
	# Depending on the value of $admin_sub_action we know what exactly the user wants to do.
	# Possible values for $admin_sub_action
	# 1 = General
	# 2 = Look & Feel
	# 3 = Attachments
	# 4 = Mail Settings
	# 5 = (none)
	# 6 = Reset Forum Settings

	if ($admin_sub_action == 1 and !param('posted')) {
		# General
			if ($html_protection eq "on") { $htmlon = " SELECTED"; } else { $htmloff = " SELECTED"; }
			if ($show_email_addresses eq "on") { $showmailon = " SELECTED"; } else { $showmailoff = " SELECTED"; }
			if ($bbcode eq "on") { $bbcodeon = " SELECTED"; } else { $bbcodeoff = " SELECTED"; }
			if ($smileys eq "on") { $smileyson = " SELECTED"; } else { $smileysoff = " SELECTED"; }
			if ($hoursystem == 12) { $twelveon = " SELECTED"; } else { $twentyfouron = " SELECTED"; }
			if ($date_notation eq "mmddyy") { $mmddyyon = " SELECTED"; } elsif ($date_notation eq "ddmmyy") { $ddmmyyon = " SELECTED"; } elsif ($date_notation eq "yymmdd") { $yymmddon = " SELECTED"; }
			if ($author_edit eq "on") { $authediton = " SELECTED"; } else { $autheditoff = " SELECTED"; }

			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br>
			<center>
			<$smallfont>Forum Configuration</font><br><br>
			<form method='post' action='$script_name?fid=$forum_id&admin=1'>
			<input type='hidden' name='posted' value='yes'>
			<input type='hidden' name='password' value='$password'>
			<input type='hidden' name='admin_action' value='1_1'>
			<center>
			<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
			<table border=0 width='100%'>
			<tr>
				<td>
					<div align='center'><b>GENERAL SETTINGS</b></div>
					<br>
					<b>Forum Title</b>
					<$smallfont><br><i>Choose a Title for your forum. It will appear on top of every page.</i><br>
					<input type='text' name='title' value="$title" style='width:300;'>
					<br><br>
					<b>Forum Subtitle</b>
					<$smallfont><br><i>Subtitle that will appear below the Forum Title on the Forum Index.</i><br>
					<input type='text' name='subtitle' value="$subtitle" style='width:300;'>
					<br><br>
					<b>Home</b>
					<$smallfont><br><i>This is the name for the link (URL) back to your main page.</i><br>
					<input type='text' name='home_name' value="$home_name" style='width:300;'>
					<br><br>
					<b>Home URL</b>
					<$smallfont><br><i>This is the URL for the link back to your main page.</i><br>
					<input type='text' name='home_url' value="$home_url" style='width:300;'>
					<br><br>
					<b>Images Directory</b>
					<$smallfont><br><i>Directory where all the images of SimpleForum can be found. If the images are showing up on your forum there's no need to change this.
					<br>Example: http://www.mydomain.com/images/</i><br>
					<input type='text' name='images_dir' value="$images_dir" style='width:300;'>
					<br><br>
					<b>Language</b>
					<$smallfont><br><i>Choose a language for your forum.</i><br>
					<select name='language'>
HTML

			open_dir("$simpleforum_dir/languages");
			foreach $language_file(@files) {
				if ($language_file =~ /^(.*?)\.pm$/) {
					if ($language eq $1) { $langselected = "SELECTED"; } else { $langselected = ""; }
					print "<option value='$1' $langselected>$1</option>";
				}
			}

		print <<HTML;
				</select>
				<br><br>
				<b>Hour Difference</b>
				<$smallfont><br><i>If the server time is different from your local time you can adjust the Forum Time here. Can be a negative number as well. Expressed in hours.
				<br>Example: 1, this will set the hour difference to +1 HOUR</i>
				<br><input type='text' name='hour_difference' value='$hour_difference' style='width:30;'>
				<br><br>
				<b>Date notation</b>
				<$smallfont><br><i>Short date notation on the forum</i><br>
				<select name='date_notation'>
					<option value='ddmmyy' $ddmmyyon>DD/MM/YY</option>
					<option value='mmddyy' $mmddyyon>MM/DD/YY</option>
					<option value='yymmdd' $yymmddon>YY/MM/DD</option>
				</select>
				<br><br>
				<b>Hour notation</b>
				<$smallfont><br><i>12h or 24h (12h will add AM and PM behind the hour notation)</i><br>
				<select name='hoursystem'>
					<option value='12' $twelveon>12h</option>
					<option value='24' $twentyfouron>24h</option>
				</select>
				<br><br>
				<b>HTML Protection</b>
				<$smallfont><br><i>Disable HTML in posts</i><br>
				<select name='html_protection'>
					<option value='on' $htmlon>On</option>
					<option value='off' $htmloff>Off</option>
				</select>
				<br><br>
				<b>BBCode</b>
				<$smallfont><br><i>Turn BBCode in messages [on/off]. To learn more about BBCode click "Help" in the top menu.</i><br>
				<select name='bbcode'>
					<option value='on' $bbcodeon>On</option>
					<option value='off' $bbcodeoff>Off</option>
				</select>
				<br><br>
				<b>Smileys</b>
				<$smallfont><br><i>Add smileys to messages</i><br>
				<select name='smileys'>
					<option value='on' $smileyson>On</option>
					<option value='off' $smileysoff>Off</option>
				</select>
				<br><br>
				<b>Author Edit</b>
				<$smallfont><br><i>Allow the Author to edit his message after he/she has posted it.</i><br>
				<select name='author_edit'>
					<option value='on' $authediton>Allow</option>
					<option value='off' $autheditoff>Don't allow</option>
				</select>
				<br><br>
				<b>Topics per Page</b>
				<$smallfont><br><i>The amount of topics shown on one page in the topic index</i><br>
				<input type='text' name='topics_per_page' value='$topics_per_page' style='width:30;'>
				<br><br>
				<b>Messages per Page</b>
				<$smallfont><br><i>The amount of messages shown on one page inside a topic</i><br>
				<input type='text' name='posts_per_page' value='$posts_per_page' style='width:30;'>
				<br><br>
				<b>Popular</b>
				<$smallfont><br><i>The amount of replies required to make the topic "Popular"</i><br>
				<input type='text' name='popularnumb' value='$popularnumb' style='width:30;'>
				<br><br>
				<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
				</td>
			</tr>
		</table>
	</table>
HTML

	} elsif ($admin_sub_action == 2 and !param('posted')) {
		# Look & Feel
			if ($menu_display eq "set1") { $set1_on = "SELECTED"; } elsif ($menu_display eq "set2") { $set2_on = "SELECTED"; } else { $menu_display_text_on = "SELECTED"; }
			if ($topic_index_statistics eq "yes") { $topic_index_statistics_on = "SELECTED"; } else { $topic_index_statistics_off = "SELECTED"; }
			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br>
			<center>
			<$smallfont>Forum Configuration</font><br><br>
			<form method='post' action='$script_name?fid=$forum_id&admin=1'>
			<input type='hidden' name='posted' value='yes'>
			<input type='hidden' name='password' value='$password'>
			<input type='hidden' name='admin_action' value='1_2'>
			<center>
			<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
			<table border=0 width='100%'>
			<div align='center'><b>LOOK & FEEL</b></div>
			<br><$standardfont><b>Background Color</b> <font face='verdana' size='2' color='$backgroundcolor'> &diams;</font>
			<$smallfont><br><i>The background color for your Forum and some other objects such as textareas (if supported by the browser).<br>
			Example: black or #FF00EE</i><br></font>
			<input type='text' name='backgroundcolor' value='$backgroundcolor' style='width:70;'>
			<br><br>
			<b>Background Image</b>
			<$smallfont><br><i>If you want an image for background, specify the URL to the image<br>
			Example: http://www.domain.com/path/to/image.jpg</i><br>
			<input type='text' name='backgroundimage' value='$backgroundimage' style='width:400;'>
			<br><br>
			<b>Menu Display</b>
			<$smallfont><br><i>Have your menu displayed as text or images.</i><br>
			<select name='menu_display'><option value='text' $menu_display_text_on>Text</option><option value='set1' $set1_on>Images - Set 1</option><option value='set2' $set2_on>Images - Set 2</option></select>
			<br><br>
			<b>Topic Index Statistics</b>
			<$smallfont><br><i>Print the Forum Statistics also below topic indexes.</i><br>
			<select name='topic_index_statistics'><option value='yes' $topic_index_statistics_on>Yes</option><option value='no' $topic_index_statistics_off>No</option></select>
			<br><br>
			<b>Table Color 1</b> <font face='verdana' size='2' color='$tablecolor1'>&diams;</font>
			<$smallfont><br><i>Table backgroundcolor 1. Empty field = Transparent background.</i><br>
			<input type='text' name='tablecolor1' value='$tablecolor1' style='width:70;'>
			<br><br>
			<b>Table Color 2</b> <font face='verdana' size='2' color='$tablecolor2'>&diams;</font>
			<$smallfont><br><i>Table backgroundcolor 2. Empty field = Transparent background.</i><br>
			<input type='text' name='tablecolor2' value='$tablecolor2' style='width:70;'>
			<br><br>
			<b>Table Color 3</b> <font face='verdana' size='2' color='$tablecolor3'>&diams;</font>
			<$smallfont><br><i>Table backgroundcolor 3. Empty field = Transparent background.</i><br>
			<input type='text' name='tablecolor3' value='$tablecolor3' style='width:70;'>
			<br><br>
			<b>Table border color</b> <font face='verdana' size='2' color='$tablebordercolor'>&diams;</font>
			<$smallfont><br><i>Self explanatory.</i><br>
			<input type='text' name='tablebordercolor' value='$tablebordercolor' style='width:70;'>
			<br><br>
			<b>Postform Background</b> <font face='verdana' size='2' color='$postformbackground'>&diams;</font>
			<$smallfont><br><i>Table background color for the post and reply forms on your Forum.</i><br>
			<input type='text' name='postformbackground' value='$postformbackground' style='width:70;'>
			<br><br>
			<b>Table Width</b>
			<$smallfont><br><i>Table width for most tables on your forums.
			<br>Examples: 600 or 90%</i><br>
			<input type='text' name='tablewidth' value='$tablewidth' style='width:35;'>
			<br><br>
			<b>Font(s)</b>
			<$smallfont><br><i>The font you want to use for your forum, note that the visitor must have the font installed on his computer in order to see it. By adding a "," you can add a secondary font in case the visitor has not got the font installed (e.g. "arial, verdana"). Empty field will apply the browser's standard font.</i><br>
			<input type='text' name='fontface' value='$fontface' style='width:200;'>
			<br><br>
			<b>Font Size</b>
			<$smallfont><br><i>The size of the font in general, this does not count for headers and such<br>
			Example: 12, this will make the font size 12pt</i><br>
			<input type='text' name='fontsize' value='$fontsize' style='width:20;'>
			<br><br>
			<b>Small Font Size</b>
			<$smallfont><br><i>The font size of comments, less important text, ... </i><br>
			<input type='text' name='fontsizesmall' value='$fontsizesmall' style='width:20;'>
			<br><br>
			<b>Font Color</b> <font face='verdana' size='2' color='$fontcolor'>&diams;</font>
			<$smallfont><br><i>Will change the color for most text on your forum</i><br>
			<input type='text' name='fontcolor' value='$fontcolor' style='width:70;'>
			<br><br>
			<b>Link Color</b> <font face='verdana' size='2' color='$link_color'>&diams;</font>
			<$smallfont><br><i>Color of the links you haven't visited</i><br>
			<input type='text' name='link_color' value='$link_color' style='width:70;'>
			<br><br>
			<b>Visited Link Color</b> <font face='verdana' size='2' color='$visited_link_color'>&diams;</font>
			<$smallfont><br><i>Color of the links you have visited</i><br>
			<input type='text' name='visited_link_color' value='$visited_link_color' style='width:70;'>
			<br><br>
			<b>Link Hover Color</b> <font face='verdana' size='2' color='$link_hover_color'>&diams;</font>
			<$smallfont><br><i>Color of the link when holding your mouse over the text</i><br>
			<input type='text' name='link_hover_color' value='$link_hover_color' style='width:70;'>
			<br><br>
				<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
				</td>
			</tr>
		</table>
	</table>
HTML
	} elsif ($admin_sub_action == 3 and !param('posted')) {
		# Attachments
			$tmp_attachments_uploadmax = $attachments_uploadmax/1024000;
			if ($allow_attachments eq "yes") { $allow_attachments_on = " SELECTED"; } else { $allow_attachments_off = " SELECTED"; }
			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br>
			<center>
			<$smallfont>Forum Configuration</font><br><br>
			<form method='post' action='$script_name?fid=$forum_id&admin=1'>
			<input type='hidden' name='posted' value='yes'>
			<input type='hidden' name='password' value='$password'>
			<input type='hidden' name='admin_action' value='1_3'>
			<center>
			<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
			<table border=0 width='100%'>
			<div align='center'><b>ATTACHMENTS</b></div>
			<br><br>
			<b>Allow Attachments</b>
			<$smallfont><br><i>Enable/Disable all attachment functions used by the script</i><br>
			<select name='allow_attachments'><option value='yes' $allow_attachments_on>Yes</option><option value='no' $allow_attachments_off>No</option></select>
			<br><br>
			<b>Attachments Directory</b>
			<$smallfont><br><i>Where would you like the attachments to be stored? Leave blank for default
			Use absolute path to attachments directory (e.g. /path/to/attachments or ../attachments)</i><br>
			<input type='text' name='attachments_dir' value='$attachments_dir' style='width:300;'>
			<br><br>
			<b>Attachments URL</b>
			<$smallfont><br><i>This is the URL to the attachments directory. Change this only if the attachment links in posts are all broken links.
			<br>Example: http://www.mydomain.com/attachments/</i><br>
			<input type='text' name='attachments_url' value='$attachments_url' style='width:300;'>
			<br><br>
			<b>Maximum file size</b>
			<$smallfont><br><i>The maximum size a file can have to be uploaded.</i><br>
			<input type='text' name='attachments_uploadmax' value='$tmp_attachments_uploadmax' style='width:20;'><$smallfont> (Megabytes)</font>
			<br><br>
				<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
				</td>
			</tr>
		</table>
	</table>
HTML
	} elsif ($admin_sub_action == 4 and !param('posted')) {
		# Mail Settings
			if ($admin_email_notify eq "on") { $admin_email_notify_on = " SELECTED"; } else { $admin_email_notify_off = " SELECTED"; }
			if ($mail eq "on") { $mailon = " SELECTED"; } else { $mailoff = " SELECTED"; }
			if ($show_email_addresses eq "on") { $showmailon = " SELECTED"; } else { $showmailoff = " SELECTED"; }
			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b>
			<br>
			<center>
			<$smallfont>Forum Configuration</font><br><br>
			<form method='post' action='$script_name?fid=$forum_id&admin=1'>
			<input type='hidden' name='posted' value='1'>
			<input type='hidden' name='password' value='$password'>
			<input type='hidden' name='admin_action' value='1_4'>
			<center>
			<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
			<table border=0 width='100%'>
			<div align='center'><b>MAIL SETTINGS</b></div>
			<br><br>
			<b>Mail</b>
			<$smallfont><br><i>Enable/Disable all mail functions used by the script through sendmail</i><br>
			<select name='mail'><option value='on' $mailon>On</option><option value='off' $mailoff>Off</option></select>
			<br><br>
			<b>Mail program</b>
			<$smallfont><br><i>Location of the mail program</i><br>
			<input type='text' name='mailprog' value='$mailprog' style='width:300;'>
			<br><br>
			<b>Administrator Email</b>
			<$smallfont><br><i>Email address of the Forum Administrator</i><br>
			<input type='text' name='admin_email' value='$admin_email' style='width:300;'>
			<br><br>
			<b>Show/Hide Email Addresses</b>
			<$smallfont><br><i>Show/Hide user's email address on the Forum.</i><br>
			<select name='show_email_addresses'><option value='on' $showmailon>Show</option><option value='off' $showmailoff>Hide</option></select>
			<br><br>
			<b>Admin Notify</b>
			<$smallfont><br><i>Notify the administrator of any posts added on the forum (by email). Requires Administrator Email</i><br>
			<select name='admin_email_notify'><option value='on' $admin_email_notify_on>On</option><option value='off' $admin_email_notify_off>Off</option></select>
			<br><br>
				<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
				</td>
			</tr>
		</table>
	</table>
HTML

	} elsif ($admin_sub_action == 6) {
		# Reset Forum Settings
			&page_start;
			print "<div align='center'><b>$lang_administration_area</b><br>
			<$smallfont>Forum Configuration</font><br><br>\n";

			if (param('sent')) {
			#reset the settings by deleting the config file
				unlink "$simpleforum_dir/simpleforum.conf";
				print <<HTML;
				<center>
				<b>Reset Forum Settings</b><br><br>
				Forum Settings Reset!<br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='password' value='$password'>
				<input type='submit' value='Continue'>
				</form>
HTML
			} else {
				#doublecheck if this is what the user wants to do
				print "<center><b>Reset Forum Settings</b>
				<br><br>This will discard all your forum settings specified in \"Forum Configuration\" and reset them to their defaults.<br>Resetting the Forum will not delete topic data.
				<br><br>Are you sure you want to do this?
				<br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='1_6'>
				<input type='submit' name='sent' value='Yes'><input type='button' onClick='javascript:history.go(-1)' value='No'>
				</form></center>";
			}
	}


	if (param('posted')) {
		# Write the new configuration to the simpleforum.conf file (For ALL subcathegories of the "Forum Configuration Menu
		if ($admin_sub_action == 1) { @variables = ("images_dir","title","subtitle","home_name","home_url","hour_difference","hoursystem","date_notation","html_protection","bbcode","smileys","author_edit","topics_per_page","posts_per_page","popularnumb","language"); }
		elsif ($admin_sub_action == 2) { @variables = ("backgroundcolor","backgroundimage","menu_display","topic_index_statistics","tablecolor1","tablecolor2","tablecolor3","tablebordercolor","tablewidth","postformbackground","fontface","fontsize","fontsizesmall","fontcolor","link_color","visited_link_color","link_hover_color"); }
		elsif ($admin_sub_action == 3) { @variables = ("attachments_dir","attachments_url","allow_attachments","attachments_uploadmax"); }
		elsif ($admin_sub_action == 4) { @variables = ("mail","admin_email","mailprog","admin_email_notify","show_email_addresses"); }

		open(CONF, "+>> $simpleforum_dir/simpleforum.conf") or dienice("Couldn't open conf file");
			flock CONF, 2;
			seek CONF, 0, 0;
			$conf_content = join '', <CONF>;
			seek CONF, 0, 0;
			truncate CONF, 0;
			foreach $variable (@variables) {
				$variable_value = param($variable);
				if ($variable eq "attachments_uploadmax") { $variable_value = $variable_value * 1024000; }
				if ($conf_content =~ /$variable:(.*?)\n/s) {
					$conf_content =~ s/$variable:(.*?)\n/$variable:$variable_value\n/sg;
				} else {
					$conf_content .= "$variable:$variable_value\n";
				}
			}
			print CONF $conf_content;
		close CONF;
		print redirect("$script_name?fid=$forum_id&admin=1");
	}
}


sub forum_administration {
	if ($admin_sub_action == 1) {
		# Add/Edit/Delete Forums
			&page_start;
			print "<center><b>$lang_forum_administration</b><br>";
			if (param('posted')) {
				if (param('action') eq "addforum") {
				#add a forum
					$i = "01";
					while (!$directory_made) {
						if (!-e "$simpleforum_dir/forum_$i") {
							#create new directory for this forum
							$directory_made = $i;
						} else { $i++; }
					}
					$forum_name = param('forum_name');
					$forum_more = param('forum_more');
					$forum_perm = param('forum_perm');
					$forum_pass = param('forum_pass');
					$forum_mods = join "\|", param('forum_mods');
					if ($forum_pass) { $forum_pass = encrypt($forum_pass); }
					$new_topic_dir = "forum_$directory_made";
					mkdir("$simpleforum_dir/$new_topic_dir",0777) or dienice("<i>Could not create the topic directory: $!</i>\n<br><br>Set the permissions for the SimpleForum directory ($simpleforum_dir) to 777 (chmod 777 $simpleforum_dir). This means that user, group and everyone must have read/write/execute access for the simpleforum-directory<br><br>");
					open(INFO, "> $simpleforum_dir/$new_topic_dir/forum.info") or dienice("Couldn't create forum.info: $!");
					flock INFO, 2;
					print INFO <<INFO;
<forum_name>$forum_name</forum_name>
<forum_more>$forum_more</forum_more>
<forum_pass>$forum_pass</forum_pass>
<forum_perm>$forum_perm</forum_perm>
<forum_mods>$forum_mods</forum_mods>
INFO
					close INFO;
					print <<HTML;
					<center>
					<$smallfont>Add Forum</font><br><br>
					New Forum "$forum_name" Created!<br><br>
					<form method='post' action='$script_name?fid=$forum_id&admin=1'>
					<input type='hidden' name='password' value='$password'>
					<input type='hidden' name='admin_action' value='2_1'>
					<input type='submit' value='Back'>
					</form>
HTML

				} elsif (param('action') eq "editforum") {
					open_dir($simpleforum_dir);
					foreach $file(sort(@files)) {
						if ($file =~ /^(forum_(\d*))$/) {
							$fid = $2;
							$tdir = $1;
							if (param("forum_name_$tdir") and param("forum_more_$tdir")) {
								$forum_name = param("forum_name_$tdir");
								$forum_more = param("forum_more_$tdir");
								$forum_mods = join "\|", param("forum_mods_$tdir");
								if (param("forum_pass_$tdir") eq 'none') {
									$forum_pass = "";
								} elsif (param("forum_pass_$tdir") eq "") {
									$forum_pass = param("forum_pass_old_$tdir");
								} else {
									$forum_pass = encrypt(param("forum_pass_$tdir"));
								}
								$forum_perm = param("forum_perm_$tdir");

								open(INFO, "+>> $simpleforum_dir/forum_$fid/forum.info") or dienice("Couldn't open forum.info: $!");
									flock INFO, 2;
									seek INFO, 0, 0;
									$info_content = join '', <INFO>;
									seek INFO, 0, 0;
									truncate INFO, 0;
									print INFO <<CONTENT;
<forum_name>$forum_name<\/forum_name>
<forum_more>$forum_more<\/forum_more>
<forum_pass>$forum_pass<\/forum_pass>
<forum_perm>$forum_perm<\/forum_perm>
<forum_mods>$forum_mods<\/forum_mods>
CONTENT
								close INFO;
							}
						}
					}

					# Forum Order change
					foreach $file(sort(@files)) {
						if ($file =~ /^(forum_(\d*))$/) {
							$fid = $2;
							$tdir = $1;
							if (param("forum_order_$tdir") ne $fid) {
								# We need to be absolutely sure that forums don't get overwritten. Therefore we test the numbers.
									$chg_to = param("forum_order_$tdir");
									foreach $taken_number(@taken_numbers) {
										if ($taken_number eq $chg_to) {
											dienice("You have the same forum number twice! Please select unique forum numbers for each forum.<br><br><a href='javascript:history.go(-1);'>Back</a>");
										}
									}
									push @taken_numbers, $chg_to;
									if (param("forum_order_forum_$chg_to") eq $chg_to) {
										dienice("You have the same forum number twice! Please select unique forum numbers for each forum.<br><br><a href='javascript:history.go(-1);'>Back</a>");
									} else {
										$chg .= ";$fid->$chg_to;";
									}
							}
						}
					}
					# All systems GO for forum order change
					while ($chg =~ /;(\d*?)->(\d*?);/sg) {
						$chg_from = $1;
						$chg_to = $2;
						rename("$simpleforum_dir/forum_$chg_from","$simpleforum_dir/tmp_forum_$chg_to");
					}
					open_dir($simpleforum_dir);
					foreach $file(@files) {
						if ($file =~ /^tmp_forum_(\d*)$/) {
							$fid = $1;
							rename("$simpleforum_dir/$file","$simpleforum_dir/forum_$fid");
						}
					}

					print <<HTML;
					<center>
					<$smallfont>Edit Forums</font><br><br>
					Forum Info Updated!<br><br>
					<form method='post' action='$script_name?fid=$forum_id&admin=1'>
					<input type='hidden' name='password' value='$password'>
					<input type='hidden' name='admin_action' value='2_1'>
					<input type='submit' value='Back'>
					</form>
HTML
				} elsif (param('action') eq "deleteforum") {
					$forum_delete = param('deleteforum');
					if (param('confirmed') eq "yes") {
						opendir(DEL, "$simpleforum_dir/$forum_delete") or dienice("Couldn't open $forum_delete: $!");
							@delfiles = readdir DEL;
						closedir DEL;
						foreach $delfile(@delfiles) {
							if ($delfile ne '.' and $delfile ne '..') {
								unlink "$simpleforum_dir/$forum_delete/$delfile" or dienice("Couldn't delete $delfile: $!");
							}
						}
						rmdir "$simpleforum_dir/$forum_delete" or dienice("Couldn't delete $forum_delete: $!");
						&edit_statistics_file; #Reset the statistics
						print <<HTML;
						<center>
						<$smallfont>Delete Forum</font><br><br>
						Forum Deleted!<br><br>
						<form method='post' action='$script_name?admin=1'>
						<input type='hidden' name='password' value='$password'>
						<input type='hidden' name='admin_action' value='2_1'>
						<input type='submit' value='Back'>
						</form>
HTML
						exit;
					}
					if (!param('deleteforum')) { print "<br>You haven't selected a Forum to delete<br><br><a href='javascript:history.go(-1)'>Back</a></html>"; exit; }
					($tdir,$forum_name) = split(/\|/,$forum_delete);
					print <<HTML;
					<$smallfont>Delete Forum</font>
					<br><br>
					<form method='post'>
					Are you sure you want to delete \"$forum_name\"?<br>
					This action cannot be undone!
					<br><br>
					Click \"Delete\" if you want to delete $forum_name<br>
					<input type='hidden' name='confirmed' value='yes'>
					<input type='hidden' name='password' value='$password'>
					<input type='hidden' name='admin_action' value='2_1'>
					<input type='hidden' name='action' value='deleteforum'>
					<input type='hidden' name='posted' value='yes'>
					<input type='hidden' name='deleteforum' value='$tdir'>
					<br>
					<input type='submit' value='Delete'>
					</form>
					<br><br>
HTML
				}
			} else {
				open_dir($simpleforum_dir);
				foreach $file(sort(@files)) {
					if ($file =~ /^(forum_(\d*))$/) {
						$amount_of_forums++; #count the forums for later (forum order form)
						push @forum_dirs, $file;
					}
				}
				print <<HTML;
				<$smallfont>Add/Edit/Delete Forums</font><br>
				<form method='post'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_1'>
				<input type='hidden' name='action' value='addforum'>
				<input type='hidden' name='posted' value='yes'>
				<table border=0 cellspacing=3 width='$tablewidth'>
					<tr>
						<td colspan='2'><b>ADD FORUM</b></td>
					</tr>
					<tr>
						<td width='150'><b>Forum Title: </b></td>
						<td><input type='text' name='forum_name' style='width:150;'></td>
					</tr>
					<tr>
						<td><b>Password: </b><$smallfont><br><i>Optional </i></td>
						<td><input type='text' name='forum_pass' style='width:150;'></td>
					</tr>
					<tr>
						<td><b>More Info: </b></td>
						<td><input type='text' name='forum_more' style='width:400;'></td>
					</tr>
					<tr>
						<td><b>Forum Permissions: </b></td>
						<td><select name='forum_perm' style='width:150;'><option value='normal'>Normal</option><option value='read-only'>Read Only</option></select></td>
					</tr>
					<tr>
						<td valign='top'><b>Forum Moderator(s): </b></td>
						<td><select name='forum_mods' style='width:150;' size='4' MULTIPLE>
HTML
				open_dir($users_dir);
				foreach (@files) {
					if (/^(.*?)\.prf$/) {
						$potential_moderator_user = $1;
						open(PRF, "< $users_dir/$_") or dienice("Couldn't open a profile: $_<br>Error code: $!");
						flock PRF, 2;
						while (<PRF>) {
							if (/<user_name>(.*?)<\/user_name>\n/) {
								$potential_moderator_name = $1;
								print "<option value='$potential_moderator_user'>$potential_moderator_name</option>\n";
							}
						}
						close PRF;
					}
				}
				print <<HTML;
						</select></td>
					</tr>
					<tr>
						<td colspan='2' align='center'><input type='submit' value='Create Forum' style='color:green;'></td>
					</tr>
				</table>
				</form>


				<form method='post'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_1'>
				<input type='hidden' name='action' value='deleteforum'>
				<input type='hidden' name='posted' value='yes'>
				<table border=0 cellspacing=3 width='$tablewidth'>
					<tr>
						<td colspan='2'><b>DELETE FORUM</b></td>
					</tr>
					<tr>
						<td width='150'><b>Select Forum: </b></td>
						<td><select name='deleteforum'>
						<option value=''>&laquo; Select &raquo;</option>
HTML
				foreach $forum_dir(sort(@forum_dirs)) {
					if ($forum_dir =~ /^(forum_(\d*))$/) {
						$fid = $2;
						$tdir = $1;
						open(INFO, "< $simpleforum_dir/forum_$fid/forum.info") or dienice("Couldn't open forum.info: $!");
							$info_content = join '', <INFO>;
						close INFO;
						if ($info_content =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = $1; }
						print <<HTML;
						<option value='$tdir|$forum_name'>$forum_name</option>
HTML
					}
				}

						print <<HTML;
						</select></td>
					</tr>
					<tr>
						<td colspan='2' align='center'><input type='submit' value='Delete Forum' style='color:red;'></td>
					</tr>
				</table>
				</form>


				<form method='post'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_1'>
				<input type='hidden' name='action' value='editforum'>
				<input type='hidden' name='posted' value='yes'>
				<table border=0 cellspacing=3 width='$tablewidth'>
					<tr>
						<td colspan='2'><b>EDIT FORUMS</b></td>
					</tr>
HTML

				foreach $forum_dir(sort(@forum_dirs)) {
					if ($forum_dir =~ /^(forum_(\d*))$/) {
						$fid = $2;
						$tdir = $1;
						open(INFO, "< $simpleforum_dir/forum_$fid/forum.info") or dienice("Couldn't open forum.info: $!");
							$info_content = join '', <INFO>;
						close INFO;
						if ($info_content =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = $1; }
						if ($info_content =~ /<forum_more>(.*?)<\/forum_more>/s) { $forum_more = $1; }
						if ($info_content =~ /<forum_pass>(.*?)<\/forum_pass>/s) { $forum_pass = $1; }
						if ($info_content =~ /<forum_perm>(.*?)<\/forum_perm>/s) { $forum_perm = $1; }
						if ($info_content =~ /<forum_mods>(.*?)<\/forum_mods>/s) { $forum_mods = $1; }
						if ($forum_perm eq "normal") { $perm_normal = "SELECTED"; $perm_readonly = ""; } elsif ($forum_perm eq "read-only") { $perm_normal = ""; $perm_readonly = "SELECTED"; }
						if ($forum_pass) { $newpass = "New "; $enter_none_for = "<$smallfont><br><i>Enter \"none\" to disable the current password</i>"; } else { $newpass = ""; $enter_none_for = ""; }
						print <<HTML;
						<tr>
							<td><b>Forum No.: </b></td>
							<td><select name='forum_order_$tdir'>
HTML
							$k = 0;
							for (1..$amount_of_forums) {
								$k++;
								if ($k < 10) { $k_value = "0$k"; } else { $k_value = $k; }
								if ($k_value == $fid) { $k_selected = "SELECTED"; } else { $k_selected = ""; }
								print "<option value='$k_value' $k_selected>$k</option>\n";
							}
							print <<HTML;
							</select></td>
						</tr>
						<tr>
							<td width='150'><b>Forum Title: </b></td>
							<td><input type='text' name='forum_name_$tdir' value="$forum_name" style='width:150;'></td>
						</tr>
						<tr>
							<td width='150'><b>$newpass\Password: </b><br><i><$smallfont>Optional</i> </td>
							<td><input type='text' name='forum_pass_$tdir' value="" style='width:150;'>$enter_none_for</td>
							<input type='hidden' name='forum_pass_old_$tdir' value='$forum_pass'>
						</tr>
						<tr>
							<td><b>More Info: </b></td>
							<td><input type='text' name='forum_more_$tdir' value="$forum_more" style='width:400;'></td>
						</tr>
						<tr>
							<td><b>Forum Permissions: </b></td>
							<td><select name='forum_perm_$tdir' style='width:150;'><option value='normal' $perm_normal>Normal</option><option value='read-only' $perm_readonly>Read Only</option></select></td>
						</tr>
						<tr>
							<td valign='top'><b>Forum Moderator(s): </b></td>
							<td><select name='forum_mods_$tdir' style='width:150;' size='4' MULTIPLE>
								<option value=''>&laquo; No Moderators &raquo;</option>
HTML
							open_dir($users_dir);
							foreach (@files) {
								if (/^(.*?)\.prf$/) {
									$potential_moderator_user = $1;
									open(PRF, "< $users_dir/$_") or dienice("Couldn't open a profile: $_<br>Error code: $!");
									flock PRF, 2;
									while (<PRF>) {
										if (/<user_name>(.*?)<\/user_name>\n/) {
											$potential_moderator_name = $1;
											$selected = "";
											@forum_mods = split(/\|/,$forum_mods);
											foreach $forum_mod(@forum_mods) { if ($forum_mod eq $potential_moderator_user) { $selected = "SELECTED"; } }
											print "<option value='$potential_moderator_user' $selected>$potential_moderator_name</option>\n";
										}
									}
									close PRF;
								}
							}
							print <<HTML;
							</select></td>
						</tr>

						<tr><td colspan=2><$smallfont>&nbsp;</td></tr>
HTML
					}
				}
				print <<HTML;
					<tr>
						<td colspan='2' align='center'><input type='submit' value='Edit Forums' style='color:orange;'></td>
					</tr>
				</table>
				</form>
HTML
			}
	} elsif ($admin_sub_action == 2) {
		# Delete Topics and Messages
			&page_start;
			print "<center><b>$lang_administration_area</b><br>";
			#get all the topic files
			open_dir($topic_dir);

			@topics = @files;

			#filter the topic files from the files in topic_dir
			foreach $tpc(@topics) {
				if ($tpc =~ /(.*?).topic$/s) {
					($mtime) = (stat("$topic_dir/$tpc")) [9];
					push @lastmodifiedtopics, "$mtime\|$tpc";
				}
			}

			@topics = ();
			foreach $lastmodifiedtopic(reverse(sort(@lastmodifiedtopics))) {
				$lastmodifiedtopic =~ s/(.*?)\|(.*?).topic/$2.topic/s;
				push @topics, $lastmodifiedtopic;
			}

			if (param('posted')) {
				#Delete the selected topics
				foreach $topic(@topics) {
					if ($topic =~ /(.*?).topic$/sg) {
						if (param($1)) {
							unlink "$topic_dir/$1.topic";
							$reset_stats = 1;
						}
					}
				}

				if ($reset_stats) { &edit_statistics_file; } #reset the stats file

				#Delete replies in topics
				#"refresh" @topics
				opendir(TOPICS, $topic_dir) or dienice("Couldn't open $topic_dir: $!");
				@topics = readdir TOPICS;
				closedir TOPICS;

				foreach $topic(reverse(sort(@topics))) {
					if ($topic =~ /(.*?).topic$/sg) {
						$param = "delreplies$1";
						if (param($param)) {
							#The user wants to delete replies in this topic
							$topic_id = $1;
							if (!$open_form) {
								print "<center><$smallfont>Edit & Delete Replies // Block IP's<\/font><\/p>
								<FORM method='post' action='$script_name?fid=$forum_id&admin=1'>
								<input type='hidden' name='delrepliesposted' value='yes'>
								<input type='hidden' name='password' value='$password'>
								<input type='hidden' name='admin_action' value='2_2'>";
								$open_form = 1;
							}
							&delete_replies_form;
						}
					}
				}
				if ($open_form) {
					print "<input type='submit' value='Delete Selected Replies'><br><br><\/FORM>\n";
				} else {
					print "<center>
					<$smallfont>Delete Topics</font><br><br>
					Selected Topics Deleted!<br><br>
					<form method='post' action='$script_name?fid=$forum_id&admin=1'>
					<input type='hidden' name='password' value='$password'>
					<input type='submit' value='Back'>
					</form>";
				}
			} elsif (param('delrepliesposted')) {
				#delete the selected REPLIES
				foreach $topic(@topics) {
					if ($topic =~ /(.*?).topic$/sg) {
						$topic_id = $1;
						if (param($topic_id)) {
							@time = param($topic_id);
							foreach $time(@time) {
								open(TOPIC,"+>> $topic_dir/$topic_id.topic") or dienice("Couldn't open $topic_id.topic: $!");
								flock TOPIC,2;
								seek TOPIC, 0, 0;
								$topic_text = join '', <TOPIC>;
								seek TOPIC, 0, 0;
								truncate TOPIC, 0;
								$topic_text =~ s/^(.*)<post>(.*?)<time>$time<\/time>(.*?)<\/post>(.*)$/$1$4/s;
								print TOPIC $topic_text;
								close TOPIC;
								&edit_statistics_file("msg_amount--");
								#if the user deleted the only post left in a topic, delete the topic
								if ($topic_text !~ /<post>/s) { unlink "$topic_dir/$topic_id.topic"; &edit_statistics_file("tpc_amount--"); }
							}
						}
					}
				}
				print "<center>
					<$smallfont>Delete Topics and Replies</font><br><br>
					Selected Topics and Replies Deleted!<br><br>
					<form method='post' action='$script_name?fid=$forum_id&admin=1'>
					<input type='hidden' name='password' value='$password'>
					<input type='submit' value='Back'>
					</form>";
			} else {
				print <<HTML;
				<center><$smallfont>Delete Topics & Replies</font><br><br>
				<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor='$tablecolor3'>
  			  	<caption><div align='right'><$smallfont>Tick the topics you want to delete in the <font color='#BA777A'>RED</font> column<br>
  			  	Tick the topics in which you want to delete replies in the <font color='#EDD563'>ORANGE</font> column<br>
  			  	If you want to block an IP from someone who posted in a specific topic, also tick the <font color='#EDD563'>ORANGE</font> column<br><br></caption>
				<form method='post'>
				<input type='hidden' name='posted' value='yes'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_2'>
				<tr>
					<th bgcolor="$tablecolor1" width='20'>&nbsp;</th>
					<th bgcolor="$tablecolor1" width='20'>&nbsp;</th>
					<th bgcolor="$tablecolor1" align='left'>$lang_subject</th>
   			 	<th bgcolor="$tablecolor2" align='left' width='110'>$lang_author</th>
   			 	<th bgcolor="$tablecolor2" align='right' width='90'>$lang_last_post</th>
				</tr>
HTML

				#open, read and print topic content
				foreach $topic(@topics) {
					if ($topic =~ /(.*?).topic$/sg) {
						$topic_id = $1;
						#open the topic
						open(TOPIC,"< $topic_dir/$topic") or dienice("Couldn't open $topic_dir/$topic : $!");
						$topic_content = join '', <TOPIC>;
						close TOPIC;

						#get necessary content
						if ($topic_content =~ /<name>(.*?)<\/name>/s) {
							$topic_name = $1;
						}
						if ($topic_content =~ /<subject>(.*?)<\/subject>/s) {
							$topic_subject = $1;
						}
						if ($topic_content =~ /(.*)<time>(.*?)<\/time>(.*?)$/s) {
							$topic_time = $2;
						}
						#find out how many replies on the topic
						while ($topic_content =~ /<post>/sg) {
							$topic_replies++;
						}
						$topic_replies--;
						if (!$topic_replies) {
							$topic_replies = undef;
						} elsif ($topic_replies == 1) {
							$topic_replies = "- $topic_replies $lang_reply";
						} else {
							$topic_replies = "- $topic_replies $lang_replies";
						}

						#print the shiz :)
						date_time($topic_time);

						$topic_subject = add_html($topic_subject);
						# # # # HTML # # # #
						print <<HTML;
						<tr>
							<td bgcolor='#BA777A' align='center'><input type='checkbox' class='checkbox' name='$topic_id' value='$topic_id'></td>
							<td bgcolor="#EDD563" align='center'><input type='checkbox' class='checkbox' name='delreplies$topic_id' value='$topic_id'></td>
							<td>$topic_subject $topic_replies</td>
							<td>$topic_name</td>
							<td align='right'><$smallfont>$short_date $hour:$min:$sec $ampm</td>
						</tr>

HTML
						# # # END HTML # # #
					}
				}
				# # # # HTML # # # #
				print <<HTML;
				</table>
				<br>
				<input type='submit' value='&nbsp;&nbsp;Proceed&nbsp;&nbsp;'>
				</form>

HTML
				# # # END HTML # # #
			}
	} elsif ($admin_sub_action == 3) {
		# Manage Attachments
			if (!param('posted')) {
				&page_start;
				print <<HTML;
				<center><b>$lang_administration_area</b><br>
				<$smallfont>Attachments</font>
				<br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_3'>
				<input type='hidden' name='posted' value='yes'>
				<table width="600" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor1">
					<tr bgcolor='$tablecolor2'>
						<th width='30'>&nbsp;</th>
						<th>Attachment</th>
						<th width='80'>Size</th>
					</tr>
HTML


				opendir(DIR, $attachments_dir);
					@files = readdir DIR;
				closedir (DIR);
				foreach $attachment(@files) {
					if ($attachment ne ".." and $attachment ne ".") {
						($attachment_size) = (stat("$attachments_dir/$attachment")) [7];
						$attachment_size_total += $attachment_size;
						if ($attachment_size >= 1024000) {
							$attachment_size = sprintf("%.2f",($attachment_size/1024000))."Mb";
						} else {
							$attachment_size = sprintf("%.2f",($attachment_size/1024))."kb";
						}
						$attachment_printed = 1;
						print <<HTML;
							<tr>
								<td align='center'><input type='checkbox' class='checkbox' name='del_attachments' value='$attachment'></td>
								<td><a href='$attachments_dir/$attachment'>$attachment</a></td>
								<td>$attachment_size</td>
							</tr>
HTML
					}
				}
				if (!$attachment_printed) {
					#no attachment was printed
					print <<HTML;
					<tr>
						<td colspan='3'><i>There are currently no attachments</i></td>
					</tr>
HTML
				}
				if ($attachment_size_total >= 1024000) {
					$attachment_size_total = sprintf("%.2f",($attachment_size_total/1024000))."Mb";
				} else {
					$attachment_size_total = sprintf("%.2f",($attachment_size_total/1024))."kb";
				}
				print <<HTML;
				</table>
				<table width='600' border='0' cellspacing='0' cellpadding='0'><tr><td align='right'><$smallfont>Total Attachment Size: $attachment_size_total</font></td></tr></table>
				<input type='submit' value='&nbsp; Delete Selected Attachments &nbsp;'>
				</form>
HTML
			} else {
					@del_attachments = param('del_attachments');
				foreach $del_attachment(@del_attachments) {
					unlink "$attachments_dir/$del_attachment" or dienice("Couldn't delete $del_attachment!");
				}
				&page_start;
				print <<HTML;
				<center><b>$lang_administration_area</b><br>
				<$smallfont>Attachments</font><br><br>
				The selected attachments have been deleted!<br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='password' value='$password'>
				<input type='submit' value='Back'>
				</form>
HTML
			}
	} elsif ($admin_sub_action = 4) {
		#censorships
			if (!param('posted')) {
				&page_start;
				print <<HTML;
				<center>
				<b>$lang_administration_area</b>
				<br>
				<center>
				<$smallfont>Forum Administration</font><br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='posted' value='yes'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='2_4'>
				<center>
				<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
				<tr><td>
				<table border=0 width='100%'>
				<div align='center'><b>CENSORSHIP</b></div>
				<br><br>
				<b>Censored words</b>
				<$smallfont><br><i>Words entered here will be automatically censored by the forum. Use a comma (,) between each new word.<br>
				Example: word1, word2, word3</i><br>
				<textarea name='censored_words'>$censored_words</textarea>
				<br><br>
				<div align='center'><input type='submit' value='$lang_save_changes' style='width:150;'><input type='reset' value='$lang_revert' style='width:150;'></div>
				</td>
				</tr>
				</table>
				</table>
HTML
			} else {
				# Write the new configuration to the simpleforum.conf file (For ALL subcathegories of the "Forum Configuration Menu
				@variables = ("censored_words");
				open(CONF, "+>> $simpleforum_dir/simpleforum.conf") or dienice("Couldn't open conf file");
					flock CONF, 2;
					seek CONF, 0, 0;
					$conf_content = join '', <CONF>;
					seek CONF, 0, 0;
					truncate CONF, 0;
					foreach $variable (@variables) {
						$variable_value = param($variable);
						if ($conf_content =~ /$variable:(.*?)\n/s) {
							$conf_content =~ s/$variable:(.*?)\n/$variable:$variable_value\n/sg;
						} else {
							$conf_content .= "$variable:$variable_value\n";
						}
					}
					print CONF $conf_content;
				close CONF;
				print redirect("$script_name?fid=$forum_id&admin=1");
			}
	}
}


sub user_administration {

	# This sub takes care of all the actions in the User Administration menu in the Administrator Area
	# Depending on the value of $admin_sub_action we know what exactly the user wants to do.
	# Possible values for $admin_sub_action
	# 1 = User Permissions
	# 2 = User Titles
	# 3 = Delete Users
	# 4 = Ban Users
	# 5 = Register Users

	if ($admin_sub_action == 1) {
		if (!param('posted')) {
			# User Permissions Form
			if ($guest_access eq "on") { $guest_access_on = "SELECTED"; } elsif ($guest_access eq "off") { $guest_access_off = "SELECTED"; } elsif ($guest_access eq "read-only") { $guest_access_read_only = "SELECTED"; }
			if ($enable_private_messages eq "on") { $enable_private_messages_on = "SELECTED"; } else { $enable_private_messages_off = "SELECTED"; }
			if ($enable_guest_registration eq "on") { $enable_guest_registration_on = "SELECTED"; } else { $enable_guest_registration_off = "SELECTED"; }
			&page_start;
			print <<HTML;
				<center>
				<b>$lang_administration_area</b>
				<br>
				<center>
				<$smallfont>User Permissions</font><br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='posted' value='yes'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='3_1'>
				<center>
				<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
				<tr><td>
				<table border=0 width='100%'>
				<div align='center'><b>USER PERMISSIONS</b></div>
				<br><br>
				<b>Administrator Access</b>
				<$smallfont><br><i>Selected user(s) will have administrator access on your forum.</font></i><br>
				<select name='administrator_access' style='width:150;' size='5' MULTIPLE>
HTML
				open_dir($users_dir);
				foreach (@files) {
					if (/^(.*?)\.prf$/) {
						$potential_admin_user = $1;
						open(PRF, "< $users_dir/$_") or dienice("Couldn't open a profile: $_<br>Error code: $!");
						flock PRF, 2;
						while (<PRF>) {
							if (/<user_name>(.*?)<\/user_name>\n/) {
								$potential_admin_name = $1;
								$selected = "";
								foreach $admin_account(@admin_accounts) { if ($admin_account eq $potential_admin_user) { $selected = "SELECTED"; } }
								print "<option value='$potential_admin_user' $selected>$potential_admin_name</option>\n";
							}
						}
						close PRF;
					}
				}
				print <<HTML;
				</select>
				<br><br>
				<b>Guest Access</b>
				<$smallfont><br><i>Allow guests to view your forum</i><br></font>
				<select name='guest_access'><option value='on' $guest_access_on>On</option><option value='read-only' $guest_access_read_only>Read Only</option><option value='off' $guest_access_off>Off</option></select>
				<br><br>
				<b>Registrations</b>
				<$smallfont><br><i>Allow guests to register to your forum</i><br></font>
				<select name='enable_guest_registration'><option value='on' $enable_guest_registration_on>On</option><option value='off' $enable_guest_registration_off>Off</option></select>
				<br><br>
				<b>Private Messaging</b>
				<$smallfont><br><i>Allow users to send private messages</i><br></font>
				<select name='enable_private_messages'><option value='on' value='on' $enable_private_messages_on>On</option><option value='off' $enable_private_messages_off>Off</option></select>
				<br><br>
				<$smallfont><i>In future releases this is the place where you can allow or disallow users to for example set their own prefered language, date notation preferences, topics per page, etc etc...</font>
				<br><br>
					<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
					</td>
				</tr>
			</table>
		</table>
HTML
		} else {
			@new_administrators = param('administrator_access');
			open(CONF, "+>> $simpleforum_dir/simpleforum.conf") or dienice("Couldn't open simpleforum.conf: $!");
			flock CONF, 2;
			seek CONF, 0, 0;
			$conf_content = join '', <CONF>;
			seek CONF, 0, 0;
			truncate CONF, 0;
			$new_administrators = join "\|", @new_administrators;
			if ($new_administrators) { $conf_content =~ s/admin_account:(.*?)\n/admin_account:$new_administrators\n/s; }
			print CONF $conf_content;
			close CONF;
			# part of the writing to the configuration files is also done below
		}
	} elsif ($admin_sub_action == 2 and !param('posted')) {

			# User Titles Form
			&page_start;
			if ($enable_user_titles eq "on") { $enable_user_titles_on = "SELECTED"; } else { $enable_user_titles_off = "SELECTED"; }
			print <<HTML;
				<center>
				<b>$lang_administration_area</b>
				<br>
				<center>
				<$smallfont>User Titles</font><br><br>
				<form method='post' action='$script_name?fid=$forum_id&admin=1'>
				<input type='hidden' name='posted' value='yes'>
				<input type='hidden' name='password' value='$password'>
				<input type='hidden' name='admin_action' value='3_2'>
				<input type='hidden' name='change_manual_titles' value='1'>
				<center>
				<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
				<tr><td>
				<table border=0 width='100%'>
				<div align='center'><b>USER TITLES</b></div>
				<br><br>
				<b>User Titles</b>
				<$smallfont><br><i>Turn user titles on or off</i>
				<br><select name='enable_user_titles'><option value='on' $enable_user_titles_on>On</option><option value='off' $enable_user_titles_off>Off</option></select>
				<br><br>
				<b>Automatic User Titles</b>
				<$smallfont><br><i>Depending on how many posts a user has made on your forum, his "title" will change. You can set the user titles and the amount of posts required to obtain a certain title here.</i><br>
				<br><div align='center'>
				<table border=0>
				<tr>
					<td>Level 1</td>
					<td><center>0</center></td>
					<td><input type="text" name="title_lvl1" value="$title_lvl1" style="width:150;"></td>
				</tr>
				<tr>
					<td>Level 2</td>
					<td><input type="text" name="title_lvl2_posts" value="$title_lvl2_posts" style="width:40;"></td>
					<td><input type="text" name="title_lvl2" value="$title_lvl2" style="width:150;"></td>
				</tr>
				<tr>
					<td>Level 3</td>
					<td><input type="text" name="title_lvl3_posts" value="$title_lvl3_posts" style="width:40;"></td>
					<td><input type="text" name="title_lvl3" value="$title_lvl3" style="width:150;"></td>
				</tr>
				<tr>
					<td>Level 4</td>
					<td><input type="text" name="title_lvl4_posts" value="$title_lvl4_posts" style="width:40;"></td>
					<td><input type="text" name="title_lvl4" value="$title_lvl4" style="width:150;"></td>
				</tr>
				<tr>
					<td>Level 5</td>
					<td><input type="text" name="title_lvl5_posts" value="$title_lvl5_posts" style="width:40;"></td>
					<td><input type="text" name="title_lvl5" value="$title_lvl5" style="width:150;"></td>
				</tr>
				<tr>
					<td>Level 6</td>
					<td><input type="text" name="title_lvl6_posts" value="$title_lvl6_posts" style="width:40;"></td>
					<td><input type="text" name="title_lvl6" value="$title_lvl6" style="width:150;"></td>
				</tr>
				</table>
				</div>
									</td>
				</tr>
			</table>
			<br>
			<b>Manual User Titles</b>
			<$smallfont><br><i>If a user requires a custom title (e.g. "Administrator", "Member", ...) you can set this here. Users without a custom title will receive the automatic title (see above).
			<br><br>
			<div align='center'>
			<table border='0'>
			<tr><td valign='top'>
				<table border='0'>
HTML
			open_dir($users_dir);
			foreach (@files) { if (/^.*?\.prf$/) { push @user_profiles, $_; } }
			$profile_amount = $#user_profiles;

			foreach (sort @user_profiles) {
				if (/^(.*?)\.prf$/) {
					# This is a user profile
						$profile_user = $1;
						open(PRF, "$users_dir/$profile_user\.prf") or dienice("Couldn't open $profile_user\.prf: $!");
						flock PRF, 2;
						while (<PRF>) {
							if (/<user_name>(.*?)<\/user_name>/s) { $profile_name = $1; }
							if (/<user_title>(.*?)<\/user_title>/s) { $profile_title = $1; }
						}
						close PRF;
						print "<tr><td width='100' align='right'>$profile_name</td><td width='200'><input type='text' name='$profile_user' value='$profile_title' style='width:150;'></td></tr>\n";
						if ($print_id == int($profile_amount/2)) { print "</table>\n</td><td valign='top'><table border='0'>"; }
						$print_id++;
				}
			}
			print <<HTML;
				</table>
				</td></tr>
			</table>
			<br>
			<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
			</form>
			</div>
			</td></tr>
		</table>
HTML

	} elsif ($admin_sub_action == 3) {
		# Delete Users
		if (!param('confirm_delete')) {
			# Print the delete users form
			&page_start;
			print <<HTML;
			<center>
			<b>$lang_administration_area</b><br>
			<$smallfont>Delete Users</font>
			<br><br>
			Check the box next to the user(s) you want to delete and press "Delete Selected Users".<br><br>
			<form method='post' action="$script_name?fid=$forum_id&admin=1&admin_action=3_3">
				<input type='hidden' name='admin_action' value='3_3'>
				<input type='hidden' name='confirm_delete' value='1'>
				<input type='hidden' name='password' value='$password'>
HTML
			open_dir($users_dir);

			#filter out the profiles and store them in @user_profiles
			foreach (@files) {
				if (/^.*?\.prf$/) {
					push @user_profiles, $_;
				}
			}
			# $delete_amount contains the number of files in $users_dir
			$delete_amount = $#user_profiles + 1;
			print "<input type='hidden' name='delete_amount' value='$delete_amount'>\n";

			# according to $delete_amount we can calculate the dimensions of the table which contains the users
			$table_cols = 4; 								# colums
			$table_rows = int($delete_amount/$table_cols);	# rows
			if ($table_rows != ($delete_amount/$table_cols)) { $table_rows++; } # (example: 4.3333 must be rounded to 5 instead of 4)
			$table_cell_width = int(600/$table_cols);		# width of a cell

			# print the table containing the user list
			print "<table border='0'>\n<tr><td valign='top' width='$table_cell_width'>";
			foreach $user_profile(sort @user_profiles) {
				# $delete_id is required for easily finding which users are selected
				# each checkbox in the form has name="$delete_id" and value="$user_profile"
				# this way we can scan the id's and if their value is positive (selected)
				# we delete the file which has that value ($delete_name.prf)
				# The amount of delete id's is more or less the amount of variables in @user_profiles
				# we store this in $delete_amount (see above)
				$delete_id++;
				if ($user_profile =~ /^(.*?)\.prf$/) {
					$delete_user = $1;
					open PRF, "$users_dir/$user_profile" or dienice("Couldn't open $user_profile");
						flock PRF, 2;
						while (<PRF>) {
							if (/<user_name>(.*?)<\/user_name>\n/) {
								$delete_name = $1;
								print "<input type='checkbox' name='$delete_id' value='$delete_user'> $delete_name</br>\n";
								for ($i = 1; $i < $table_cols; $i++) {
									if ($delete_id == $table_rows * $i and $delete_id ne $delete_amount) {
										print "</td><td valign='top' width='$table_cell_width'>\n";
									}
								}
							}
						}
					close PRF;
				}
			}
			print <<HTML;
					</td></tr></table><br>
				<input type='submit' value='Delete Selected Users'>
			</form>
			</center>
HTML
		} else {
			# Delete the selected users
			# $delete_amount is the amount of param's to check (see expl. above)
			$delete_amount = param('delete_amount');
			for ($i = 1; $i <= $delete_amount; $i++) {
				if (param($i)) {
					$delete_user = param($i);
					if (-e "$users_dir/$delete_user.prf") { unlink "$users_dir/$delete_user.prf"; }
					if (-e "$users_dir/private_messages/$delete_user\_in.pmsg") { unlink "$users_dir/private_messages/$delete_user\_in.pmsg"; }
					if (-e "$users_dir/private_messages/$delete_user\_out.pmsg") { unlink "$users_dir/private_messages/$delete_user\_out.pmsg"; }
				}
			}
			# redirect back to admin area
			print redirect("$script_name?fid=$forum_id&admin=1");
			exit;
		}
	} elsif ($admin_sub_action == 4) {
		# Ban Users
		if (!param('posted')) {
			# Ban Users Form
			&page_start;
			print <<HTML;
			<div align='center'>
			<b>$lang_administration_area</b>
			<br><$smallfont>Ban Users</font>
			<br><br>
				<table width="600" border="1" cellspacing="0" cellpadding="20" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor">
				<tr><td>
					<table border='0' width='600'>
						<tr><td>
							<center><b>BAN USERS</b></center>
							<br>
							<b>Set New Ban</b>
							<br>
							<$smallfont>Select a user to ban and enter the duration of the ban.</font>
							<br>
							<form method='post'>
							<input type='hidden' name='posted' value='1'>
							<input type='hidden' name='password' value='$password'>
							<input type='hidden' name='admin_action' value='3_4'>
							<select name='ban_user'>
							<option value=''>&laquo; Select User &raquo;</option>
							<option value=''>&nbsp;</option>
HTML
			open_dir($users_dir);
			foreach (sort @files) {
				if (/^(.*?)\.prf$/) {
					$profile_user = $1;
					open PRF, "$users_dir/$profile_user\.prf" or dienice("Couldn't open $profile_user.prf : $!");
					flock PRF, 2;
					while (<PRF>) {
						if (/<user_name>(.*?)<\/user_name>\n/) {
							$profile_name = $1;
							print "<option value='$profile_user'>$profile_name</option>\n";
						}
					}
					close PRF;
				}
			}
			print <<HTML;
							</select>
							<input type='text' name='ban_duration_1' size='3'>
							<select name='ban_duration_2'>
								<option value='60'>Minutes</option>
								<option value='3600'>Hours</option>
								<option value='86400'>Days</option>
								<option value='2592000'>Months</option>
							</select>
							<input type='submit' value=' Place Ban '>
							</form>
							<br>
							<b>Unban User</b><br>
							<$smallfont>Remove a previously placed ban.
							<br><i>Under Construction...</i></font>
						</td></tr>
					</table>
				</td></tr>
			</table>
		</div>
HTML
		} else {
			# The user that will be banned
			$ban_user = param('ban_user');
			# The time the ban expires
			$ban_expires = time + (param('ban_duration_1') * param('ban_duration_2'));

			# Open target's profile and set <user_ban> and get <user_ip>
			open(PRF, "+>> $users_dir/$ban_user\.prf") or dienice("Couldn't open profile: $!");
			flock PRF, 2;
			seek PRF, 0, 0;
			$prf_content = join '', <PRF>;
			seek PRF, 0, 0;
			truncate PRF, 0;
			if ($prf_content =~ /<user_ban>(.*?)<\/user_ban>\n/s) {
				$prf_content =~ s/<user_ban>(.*?)<\/user_ban>\n/<user_ban>$ban_expires<\/user_ban>\n/s;
			} else {
				$prf_content .= "<user_ban>$ban_expires<\/user_ban>\n";
			}
			if ($prf_content =~ /<user_ip>(.*?)<\/user_ip>/) { $ban_ip = $1; }
			print PRF $prf_content;
			close PRF;

			# Open the ipban file and set the banned IP's to prevent this user from accessing the forum using another account
			open (IPBAN, ">> $simpleforum_dir/blocked_ips.conf") or dienice("Couldn't open ipban file: $!");
			flock IPBAN, 2;
			print IPBAN <<BAN;
<ip>$ban_ip</ip><expires>$ban_expires</expires>
BAN
			close IPBAN;

			# Redirect back to admin area
			print redirect("$script_name?fid=$forum_id&admin=1");
			exit;
		}
	} elsif ($admin_sub_action == 5) {
		# register users
		&register;
	}

	if (param('posted')) {
		# Write the new configuration to the simpleforum.conf file (For ALL subcathegories of the "Forum Configuration Menu
		if ($admin_sub_action == 1) { @variables = ("guest_access","enable_private_messages","enable_guest_registration"); }
		elsif ($admin_sub_action == 2) { @variables = ("enable_user_titles","title_lvl1","title_lvl2","title_lvl3","title_lvl4","title_lvl5","title_lvl6","title_lvl2_posts","title_lvl3_posts","title_lvl4_posts","title_lvl5_posts","title_lvl6_posts"); }

		open(CONF, "+>> $simpleforum_dir/simpleforum.conf") or dienice("Couldn't open conf file");
			flock CONF, 2;
			seek CONF, 0, 0;
			$conf_content = join '', <CONF>;
			seek CONF, 0, 0;
			truncate CONF, 0;
			foreach $variable (@variables) {
				$variable_value = param($variable);
				if ($variable eq "attachments_uploadmax") { $variable_value = $variable_value * 1024000; }
				if ($conf_content =~ /$variable:(.*?)\n/s) {
					$conf_content =~ s/$variable:(.*?)\n/$variable:$variable_value\n/sg;
				} else {
					$conf_content .= "$variable:$variable_value\n";
				}
			}
			print CONF $conf_content;
		close CONF;
		print redirect("$script_name?fid=$forum_id&admin=1");

		# Change the manual user titles in the profiles
		if (param('change_manual_titles')) {
			# Set the new user titles in the profiles
			open_dir($users_dir);
			foreach (@files) {
				if (/^(.*?)\.prf$/) {
					$profile_title = param($1);
					open PRF, "+>> $users_dir/$_" or dienice("Couldn't open $_: $!");
					flock PRF, 2;
					seek PRF, 0, 0;
					$profile_text = join '', <PRF>;
					seek PRF, 0, 0;
					truncate PRF, 0;
					$profile_text =~ s/<user_title>(.*?)<\/user_title>\n/<user_title>$profile_title<\/user_title>\n/sg;
					print PRF $profile_text;
					close PRF;
				}
			}
		}
	}
}


sub delete_replies_form {
	#first we open the specific topic
	open(TOPIC,"< $topic_dir/$topic_id.topic") or dienice("Couldn't open $topic_dir/$topic_id.topic");
	$topic_content = join '', <TOPIC>;
	close TOPIC;
	if ($topic_content =~ /<subject>(.*?)<\/subject>/s) { $topic_title = $1; }

	# # # # HTML # # # #
	print <<HTML;
	<center>
	<b>TOPIC: $topic_title</b>
HTML
	# # # END HTML # # #

	#get necessary content and print it
	while ($topic_content =~ /<post>(.*?)<\/post>/sg) {
		$post_content = $1;
		if ($post_content =~ /<name>(.*?)<\/name>/sg) {
			$post_name = $1;
		}
		if ($post_content =~ /<ip>(.*?)<\/ip>/sg) {
			$post_ip = $1;
		}
		if ($post_content =~ /<email>(.*?)<\/email>/sg) {
			$post_email = $1;
		}
		if ($post_content =~ /<subject>(.*?)<\/subject>/sg) {
			$post_subject = $1;
		}
		if ($post_content =~ /<time>(.*?)<\/time>/sg) {
			$post_time = $1;
		}
		if ($post_content =~ /<message>(.*?)<\/message>/sg) {
			$post_message = $1;
		}

		$post_subject = add_html($post_subject); #add smileys, images, url's, ...
		$post_message = add_html($post_message); #add smileys, images, url's, ...

		#This line takes care of the color switching
		if ($tablecolor eq $tablecolor1) { $tablecolor = $tablecolor2; } else { $tablecolor = $tablecolor1; }
		#This line adds the link to the email address to the Author's name
		if ($post_email) {
			if ($post_email =~ /\@/s) { $post_email = "mailto:$post_email"; } else { $blanktarget = "target='_blank'"; }
			$post_name = "<a href='$post_email' $blanktarget>$post_name</a>";
		}
		#Make $post_time "readable" ;)
		date_time($post_time);

		#Here we print ONE post from the entire topic, in a loop (while)
		# # # # HTML # # # #
		print <<HTML;
		<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor">
		<caption align='top'><div align='right'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div></caption>
		<tr>
			<td rowspan='4' bgcolor='#BA777A' width='20' align='center' valign='middle'><input type='checkbox' class='checkbox' name='$topic_id' value='$post_time'></td>
			<th align='left' width='100'>$lang_author: </th>
			<td>$post_name</td>
		</tr>
		<tr>
			<th align='left'>IP: </th>
			<td>$post_ip <a href='$script_name?fid=$forum_id&admin=1&blockip=$post_ip'>Block this IP</a></td>
		</tr>
		<tr>
			<th align='left'>Subject: </th>
			<td>$post_subject</td>
		</tr>
		<tr>
			<th align='left' valign='top'>$lang_message: </th>
			<td>$post_message</td>
		</tr>
		</table><br>
HTML
		# # # END HTML # # #
	}
}


sub add_ipblock {
	$blockip = param('blockip');
	open (IPBAN, "+>> $simpleforum_dir/blocked_ips.conf") or dienice("$!<br>Make sure that the dir $simpleforum_dir has its permissions set to 777");
	flock IPBAN, 2;
	print IPBAN "$blockip\n";
	close IPBAN;
	print "<br>$blockip has been blocked";
}


sub search {
	if (param('posted')) {
		$searchkey = param('searchkey');
		$searchfor = param('searchfor');
		$searchforums = param('searchforums');
		$searchcase = param('searchcase');
		$searchtimespan = param('searchtimespan');

		if (!$searchkey) { print "<center>$lang_you_must_enter_a_search_key"; return; }
		if (length($searchkey) < 3) { print "<center>Search key must contain at least 3 characters</center>"; return; }
		@searchchars = split(//,$searchkey);
		foreach $char(@searchchars) {
			if ($char =~ /\W/) { if ($char ne "\ ") { $bad_chars = 1; } }
		}
		if ($bad_chars) { print "<center>Bad search phrase `$searchkey'. Please do not use commas or non-alphanumeric characters.</center>"; return; }

		if ($searchforums eq 'all') {
			open_dir($simpleforum_dir);
			foreach $file(@files) {
				if ($file =~ /^(forum_\d*)$/) { push @searchforums, $1; }

			}
		} else {
			push @searchforums, $searchforums;
		}

		#search only in files greater than the current time minus one day/week/...
		if ($searchtimespan eq "all") { $searchtimespan = time; }
		$searchtimespan = time - $searchtimespan;

		foreach $forum_dir(@searchforums) {
			open_dir("$simpleforum_dir/$forum_dir");
			foreach $topic(@files) {
				if ($topic =~ /^(\d*?).topic$/) {
					$topic_time = $1;
					if ($topic_time ge $searchtimespan) {
						open(TPC, "< $simpleforum_dir/$forum_dir/$topic_time.topic") or dienice("couldn't open a topic: $!");
							$tpc_content = join '', <TPC>;
						close TPC;
						if ($searchcase eq "insensitive") {
							$tpc_content =~ tr/[A-Z]/[a-z]/;
							$searchkey =~ tr/[A-Z]/[a-z]/;
						}
						while ($tpc_content =~ /<post>(.*?)<\/post>/sg and !$found) {
							$tpc_post_content = $1;
							if ($searchfor eq "post") {
								if ($tpc_post_content =~ /<subject>(.*?)$searchkey(.*?)<\/subject>/s) {
									#match subject
									push @results, "$forum_dir/$topic";
									$found = 1;
								} elsif ($tpc_post_content =~ /<message>(.*?)$searchkey(.*?)<\/message>/s) {
									#match message body
									push @results, "$forum_dir/$topic";
									$found = 1;
								}
							} elsif ($searchfor eq "author") {
								if ($tpc_post_content =~ /<name>(.*?)$searchkey(.*?)<\/name>/s) {
									#match author
									push @results, "$forum_dir/$topic";
									$found = 1;
								}
							}
						}
						$found = "";
					}
				}
			}
		}
		if (@results) {
			@topics = @results;
			&print_topic_list;
		} else {
			print "<center><i>$lang_no_matches</i><br><br><a href='javascript:history.go(-1)'>$lang_back</a><br>";
		}
	} else {
	# Print the search form
	# # # # HTML # # # #
	print <<HTML;
	<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <i>$lang_search</i></b></font></div>
	<br><center>
	<form method='post'>
	<table width="600" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor='$tablecolor3'>
		<tr>
			<th colspan=2 bgcolor='$tablecolor1'>$lang_search</font></th>
		</tr>
		<tr>
			<td valign='top' width='120'>$lang_search_key</td>
			<td align='center'><input type='text' name='searchkey' style='width:450;'></td>
		</tr>
		<tr>
			<td>$lang_search_for</td>
			<td><input type='radio' class='radio' name='searchfor' value='post' CHECKED> $lang_subjects / $lang_messages<br>
				<input type='radio' class='radio' name='searchfor' value='author'> $lang_author</td>
		</tr>
		<tr>
			<th colspan=2 bgcolor='$tablecolor1'>$lang_options</th>
		</tr>
		<tr>
			<td>$lang_forum</td>
			<td><select name='searchforums'>
				<option value='all'>$lang_all_forums</option>
HTML
	# # # END HTML # # #
		open_dir($simpleforum_dir);
		foreach $file(sort(@files)) {
			if ($file =~ /^(forum_(\d*))$/) {
				$fid = $2;
				$tdir = $1;
				open(INFO, "< $simpleforum_dir/forum_$fid/forum.info") or dienice("Couldn't open forum.info: $!");
					$info_content = join '', <INFO>;
				close INFO;
				if ($info_content =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = add_html($1); }
				print <<HTML;
				<option value='$tdir'>$forum_name</option>
HTML
			}
		}
	# # # # HTML # # # #
	print <<HTML;
				</select></td>
		</tr>
		<tr>
			<td valign='top'>$lang_case</td>
			<td><input type='radio' class='radio' name='searchcase' value='insensitive' CHECKED> $lang_insensitive<br>
				<input type='radio' class='radio' name='searchcase' value='sensitive'> $lang_sensitive</td>
		</tr>
		<tr>
			<td>$lang_time_span</td>
			<td><select name='searchtimespan'>
				<option value='all'>$lang_all_posts</option>
				<option value='86400'>1 $lang_day</option>
				<option value='604800'>1 $lang_week</option>
				<option value='1209600'>2 $lang_weeks</option>
				<option value='2419200'>1 $lang_month</option>
				<option value='7257600'>3 $lang_months</option>
				<option value='14515200'>6 $lang_months</option>
				<option value='29030400'>1 $lang_year</option>
				</select>
	</table>
	<input type='hidden' name='posted' value='yes'>
	<$smallfont>$lang_searching_will_take_a_while</font><br><br>
	<input type='submit' value='$lang_search!'>
	</form>
	</center>
HTML
	# # # END HTML # # #
	}
}


sub help {
	#The Help section
	# # # # HTML # # # #
	print <<HTML;
	<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <i>$lang_help</i></b></font></div>
	<br>
	<center>
	<table border=0 width=600 bgcolor='$tablecolor3'>
	<tr>
		<th colspan=2 bgcolor='$tablecolor2'>$lang_help</th>
	</tr>
	<tr>
		<td bgcolor='$tablecolor1' width='300' align='center'>$lang_smileys</td>
		<td bgcolor='$tablecolor1' width='300' align='center'>BBCode</td>
	</tr>
	<tr>
		<td valign='top'><table border=0>
				<tr>
					<td colspan=2><$smallfont><div align='justify'><i>$lang_smileys_expl</i></div></td>
				</tr>
				<tr><td><table border=0 width='140'><tr><td>
				<tr>
					<td width='30'><img src='$smileys_dir/smile.gif'></td>
					<td><$smallfont>:)</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/wink.gif'></td>
					<td><$smallfont>;)</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/sad.gif'></td>
					<td><$smallfont>:(</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/crying.gif'></td>
					<td><$smallfont>:'(</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/tongue.gif'></td>
					<td><$smallfont>:P or :p</td>
				</tr>

				<tr>
					<td width='30'><img src='$smileys_dir/grin.gif'></td>
					<td><$smallfont>:D</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/noexpression.gif'></td>
					<td><$smallfont>:|</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/angry.gif'></td>
					<td><$smallfont>>:(</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/devil.gif'></td>
					<td><$smallfont>>:)</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/shocked.gif'></td>
					<td><$smallfont>:O or :o</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/unsure.gif'></td>
					<td><$smallfont>:S or :s</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/sick.gif'></td>
					<td><$smallfont>:X or :x</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/wassat.gif'></td>
					<td><$smallfont>:?</td>
				</tr>
				</table></td>
				<td><table border=0 width='140'>
				<tr>
					<td width='30'><img src='$smileys_dir/cool.gif'></td>
					<td><$smallfont>8)</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/blink.gif'></td>
					<td><$smallfont>o.O or 8|</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/happy.gif'></td>
					<td><$smallfont>^.^</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/pinch.gif'></td>
					<td><$smallfont>>.<</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/getlost.gif'></td>
					<td><$smallfont>L.L or l.l</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/blushing.gif'></td>
					<td><$smallfont>:blush:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/dizzy.gif'></td>
					<td><$smallfont>:dizzy:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/ermm.gif'></td>
					<td><$smallfont>:erm:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/laughing.gif'></td>
					<td><$smallfont>:laugh:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/online2long.gif'></td>
					<td><$smallfont>:geek:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/sleeping.gif'></td>
					<td><$smallfont>:zzz:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/w00t.gif'></td>
					<td><$smallfont>:w00t:</td>
				</tr>
				<tr>
					<td width='30'><img src='$smileys_dir/whistling.gif'></td>
					<td><$smallfont>:whistle:</td>
				</tr>
				</td></tr></table>
		</table></td>
		<td valign='top'><table border=0>
				<tr>
					<td colspan=2><$smallfont><div align='justify'><i>$lang_bbcode_expl</i></div></td>
				<tr>
					<td><$smallfont>[b]bold[/b]</td>
					<td width='120'><$smallfont><b>bold</b></td>
				</tr>
				<tr>
					<td><$smallfont>[u]underline[/u]</td>
					<td><$smallfont><u>underline</u></td>
				</tr>
				<tr>
					<td><$smallfont>[i]italic[/i]</td>
					<td><$smallfont><i>italic</i></td>
				</tr>
				<tr>
					<td><$smallfont>[center]center[/center]</td>
					<td><$smallfont><div align='center'>center</div></td>
				</tr>
				<tr>
					<td><$smallfont>[justify]justify[/justify]</td>
					<td><$smallfont><div align='justify'>justify</div></td>
				</tr>
				<tr>
					<td><$smallfont>[right]right[/right]</td>
					<td><$smallfont><div align='right'>right</div></td>
				</tr>
				<tr>
					<td><$smallfont>[color:red]red text[/color]</td>
					<td><$smallfont><font color="red">red text</font></td>
				</tr>
				<tr>
					<td valign='top'><$smallfont>[h6]h6 header[/h6]</td>
					<td valign='top'><$smallfont><h6>h6 header</h6></td>
				</tr>
				<tr>
					<td valign='top'><$smallfont>[pre]text[/pre]</td>
					<td valign='top'><$smallfont><pre>text</pre></td>
				</tr>
				<tr>
					<td><$smallfont>[img://www.domain.com/w00t.gif]</td>
					<td><$smallfont><img src='$smileys_dir/w00t.gif'></p></td>
				</tr>
				<tr>
					<td valign='top'><$smallfont>[quote]Text[/quote]</td>
					<td><$smallfont><i>Quote:\n<br>\&laquo; Text \&raquo;</i></td>
				</tr>
				<tr>
					<td valign='top'><$smallfont>[url=http://www.domain.com]<br>My Site[/url]</td>
					<td><$smallfont><a href='http://simpleforum.go.dyndns.org' target='_blank'>My Site</a></td>
				</tr>
		</table></td>
	</tr>
	<tr>
		<td align='center' colspan=2 bgcolor='$tablecolor1'>$lang_post_icons</td>
	</tr>
	<tr>
		<td colspan=2><$smallfont>
			<img src='$images_dir/post_icons/post_small.gif'> - $lang_help_regular_topic<br>
			<img src='$images_dir/post_icons/newpost_small.gif'> - $lang_help_newregular_topic<br>
			<img src='$images_dir/post_icons/popular_small.gif'> - $lang_help_popular_topic<br>
			<img src='$images_dir/post_icons/newpopular_small.gif'> - $lang_help_newpopular_topic<br>
		</td>
	</tr>
	</table>
	</center>
HTML
	# # # END HTML # # #
}

sub print_emoticon_table {
if ($smileys eq "on") {
print <<HTML;
<script language="JavaScript" type="text/javascript">
<!--
function emoticon(text) {
	text = ' ' + text + ' ';
	document.post_form.message.value  += text;
	document.post_form.message.focus();
}
//-->
</script>
<!-- Show/Hide smileys -->
<!-- <div id='emoticon_text'><$smallfont><a href="javascript:divHide('emoticon_table','show');divHide('emoticon_text','hide');">[$lang_smileys]</a></div>
<div class='hidden' id='emoticon_table'> -->
<table width="100" border="0" cellspacing="0" cellpadding="2">
				<tr align="center" valign="middle">
				  <td><a href="javascript:emoticon(':)')"><img src="$smileys_dir/smile.gif" border="0" alt="Smile" title="Smile" /></a></td>
				  <td><a href="javascript:emoticon(';)')"><img src="$smileys_dir/wink.gif" border="0" alt="Wink" title="Wink" /></a></td>
				  <td><a href="javascript:emoticon(':P')"><img src="$smileys_dir/tongue.gif" border="0" alt="Tongue" title="Tongue" /></a></td>
				  <td><a href="javascript:emoticon(':w00t:')"><img src="$smileys_dir/w00t.gif" border="0" alt="Very Happy" title="Very Happy" /></a></td>
				</tr>
				<tr align="center" valign="middle">
				  <td><a href="javascript:emoticon(':(')"><img src="$smileys_dir/sad.gif" border="0" alt="Sad" title="Sad" /></a></td>
				  <td><a href="javascript:emoticon(':cry:')"><img src="$smileys_dir/crying.gif" border="0" alt="Crying" title="Crying" /></a></td>
				  <td><a href="javascript:emoticon('>:(')"><img src="$smileys_dir/angry.gif" border="0" alt="Angry" title="Angry" /></a></td>
				  <td><a href="javascript:emoticon(':o')"><img src="$smileys_dir/shocked.gif" border="0" alt="Shocked" title="Shocked" /></a></td>
				</tr>
				<tr align="center" valign="middle">
				  <td><a href="javascript:emoticon(':laugh:')"><img src="$smileys_dir/laughing.gif" border="0" alt="Laugh" title="Laugh" /></a></td>
				  <td><a href="javascript:emoticon(':whistle:')"><img src="$smileys_dir/whistling.gif" border="0" alt="Whistle" title="Whistle" /></a></td>
				  <td><a href="javascript:emoticon(':?')"><img src="$smileys_dir/wassat.gif" border="0" alt="Wassat?" title="Wassat?" /></a></td>
				  <td><a href="javascript:emoticon(':x')"><img src="$smileys_dir/sick.gif" border="0" alt="Yuck!" title="Yuck!" /></a></td>
				</tr>
				<tr align="center" valign="middle">
				  <td><a href="javascript:emoticon('8)')"><img src="$smileys_dir/cool.gif" border="0" alt="Cool" title="Cool" /></a></td>
				  <td><a href="javascript:emoticon('8|')"><img src="$smileys_dir/blink.gif" border="0" alt="Blink" title="Blink" /></a></td>
				  <td><a href="javascript:emoticon('>:)')"><img src="$smileys_dir/devil.gif" border="0" alt="Twisted Evil" title="Twisted Evil" /></a></td>
				  <td><a href="javascript:emoticon(':blush:')"><img src="$smileys_dir/blushing.gif" border="0" alt="Blushing" title="Blushing" /></a></td>
				</tr>
				<tr align="center" valign="middle">
				  <td><a href="javascript:emoticon(':erm:')"><img src="$smileys_dir/ermm.gif" border="0" alt="Erm..." title="Erm..." /></a></td>
				  <td><a href="javascript:emoticon(':S')"><img src="$smileys_dir/unsure.gif" border="0" alt="Unsure" title="Unsure" /></a></td>
				  <td><a href="javascript:emoticon('>.<')"><img src="$smileys_dir/pinch.gif" border="0" alt="Pinch" title="Pinch" /></a></td>
				  <td><a href="javascript:emoticon('l.l')"><img src="$smileys_dir/getlost.gif" border="0" alt="Get Lost" title="Get Lost" /></a></td>
				</tr>
</table>
<!-- <center><$smallfont><a href="javascript:divHide('emoticon_table','hide');divHide('emoticon_text','show');">[$lang_hide]</a></font>
</div> -->
HTML
}
}

sub select_a_forum {
	if (!$select_a_forum) {
	open_dir($simpleforum_dir);

	$select_a_forum = <<HTML;
	<select name="fid" onChange="location.href=this.options[this.selectedIndex].value" size="1" style='font-family:$fontface; font-size:$fontsizesmall\pt; background-color:$backgroundcolor; color:$fontcolor;'>
	<option value="$script_name?fid=$forum_id" selected>&laquo; $lang_select_forum &raquo;</option>
	<option value="$script_name?fid=$forum_id">&nbsp;<\/option>
	<option value="$script_name">$lang_forum_index</option>
HTML

	foreach $file(sort(@files)) {
		if ($file =~ /^(forum_(\d*))$/) {
			$forum_dir = $1;
			$fid = $2;
			open(INFO, "< $simpleforum_dir/$forum_dir/forum.info") or dienice("Couldn't open $simpleforum_dir/$forum_dir/forum.info: $!");
			$forum_info = join '', <INFO>;
			close INFO;
			if ($forum_info =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = add_html($1); }
			if ($forum_info =~ /<forum_more>(.*?)<\/forum_more>/s) { $forum_more = add_html($1); }
			$select_a_forum .= <<HTML;
			<option value="$script_name?fid=$fid">&raquo; $forum_name</option>
HTML
		}
	}
	$select_a_forum .= <<HTML;
	</select>
HTML
	}
	return $select_a_forum;
}


sub currently_online {
	if ($user eq "guest") { $guest_ip = $ENV{'REMOTE_ADDR'}; }
	open (FC, "+>> $simpleforum_dir/stats.sf") or dienice("couldn't open stats file: $!");
	flock FC, 2;
	seek FC, 0, 0;
	$fc_text = join '',<FC>;
	seek FC, 0, 0;
	truncate FC, 0;
		#write to stats file
		if ($fc_text =~ /<recentusers>(.*?)<\/recentusers>/s) {$recent_users = $1;} else {$fc_text .= "<recentusers><\/recentusers>\n";}
		@recent_users = split('\\|',$recent_users);
		foreach $ruser(@recent_users) {
			chomp $ruser;
			if ($ruser =~ /^(.*):(.*?)$/) {
				if (($1 ne $user and $1 ne "guest($guest_ip)") and (time-$2) < 360) {
					$newrecent_users = "$ruser|$newrecent_users";
				}
			}
		}
		if ($user ne "guest") {
			$newrecent_users = "$user:".time."|$newrecent_users";
		} else {
			$newrecent_users = "$user($guest_ip):".time."|$newrecent_users";
		}
		$fc_text =~ s/<recentusers>(.*?)<\/recentusers>/<recentusers>$newrecent_users<\/recentusers>/sg;
		#print to forum
		@newrecent_users = split('\\|',$newrecent_users);
		foreach $ruser(@newrecent_users) {
			if ($ruser =~ /^(.*?):(\d*?)$/ and $1 and $1 !~ "guest\((.*?)\)") {
				open(PROFILE, "< $users_dir/$1\.prf");
				$profile_text = join '', <PROFILE>;
				close PROFILE;
				$seenuser = $1;
				$seentime = $2;
				if ($profile_text =~ /<user_name>(.*?)<\/user_name>/) { $online_name = $1; }
				if ((time - $seentime) > 240) { $ocolor = "#DF0000"; }
				elsif ((time - $seentime) > 120) { $ocolor = "#E77E52"; }
				else { $ocolor = "#5F8563"; }
				if ($comma) { $currently_online .= ", ";}
				$currently_online .= "<b><a href='$script_name?pid=$seenuser'><font color='$ocolor'>$online_name</font></b></a>";
				$comma = 1;
			} elsif ($ruser =~ /^guest\((.*?)\):(.*?)$/) {
				$guestcount++;
			}
		}
		if ($guestcount) {
			if ($comma) { $currently_online .= ", "; } if ($guestcount > 1) {$guest_s = $lang_guests; } else { $guest_s = $lang_guest; }
			$currently_online .= "<b>$guestcount $guest_s</b>\n\n";
		}
	print FC $fc_text;
	close FC;
}


sub statistics {
if ($topic_index_statistics eq "yes") {
	open(STATS, "< $simpleforum_dir/stats.sf") or &edit_statistics_file;
		$stats_content = join '', <STATS>;
		if ($stats_content =~ /<tpc_amount>(\d*)<\/tpc_amount>/s) { $tpc_amount = $1; } else { $reset_stats = 1; }
		if ($stats_content =~ /<msg_amount>(\d*)<\/msg_amount>/s) { $msg_amount = $1; } else { $reset_stats = 1; }
		if ($stats_content =~ /<usr_amount>(\d*)<\/usr_amount>/s) { $usr_amount = $1; } else { $reset_stats = 1; }
	close STATS;

	if ($reset_stats) { &edit_statistics_file; }

	date_time(time);
	print <<HTML;
	<table bgcolor='$tablecolor1' border='1' width="$tablewidth" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor">
	<tr>
		<td bgcolor='$tablecolor2'><$smallfont><b>$title - $lang_forum_statistics</b></font></td>
	</tr>
	<tr>
		<td><$smallfont>- $lang_current_forum_date_and_time: <b>$full_date $ampm</b>
			<br>- $lang_stats1 <b>$tpc_amount</b> $lang_stats2 <b>$msg_amount</b> $lang_stats3
			<br>- $lang_stats4 <b>$usr_amount</b> $lang_stats5
			<br>- $lang_currently_online: $currently_online
		</td>
	</tr>
	</table>
HTML
}
}

sub edit_statistics_file {
	$action = join '', @_;

	if ($action =~ /^(.*?)(..)$/ and -e "$simpleforum_dir/stats.sf") {
		$action = $1;
		$increase_or_decrease = $2;
			open(STATS, "+>> $simpleforum_dir/stats.sf");
				flock STATS, 2;
				seek STATS, 0, 0;
				$stats_content = join '',<STATS>;
				if ($stats_content =~ /<$action>(\d*)<\/$action>/s) {
					if ($increase_or_decrease eq "++") {
						$amount = $1 + 1;
					} elsif ($increase_or_decrease eq "--") {
						$amount = $1 - 1;
					}
					$stats_content =~ s/<$action>(\d*)<\/$action>/<$action>$amount<\/$action>/s;
				}
				seek STATS, 0, 0;
				truncate STATS, 0;
				print STATS $stats_content;
			close STATS;
			return;
	}

	# RESET the stats file (-> check msg_amount and tpc_amount) if no action is given

	if (-e "$simpleforum_dir/stats.sf") {
			open(STATS, "< $simpleforum_dir/stats.sf");
				$stats_content = join '',<STATS>;
			close STATS;
			if ($stats_content =~ /<usr_amount>(\d*)<\/usr_amount>/s) {
				$usr_amount = $1;
			}
	}

	open_dir($simpleforum_dir);
	@sffiles = @files;
	foreach $sffile(@sffiles) {
		if ($sffile =~ /forum_(\d*)/s) {
			open_dir("$simpleforum_dir/$sffile");
			@topics = @files;
			foreach $topic(@topics) {
				if ($topic =~ /(\d*).topic/s) {
					$tpc_amount++;
					open(TPC, "< $simpleforum_dir/$sffile/$topic") or dienice("Couldn't open topic: $!");
					$tpc_content = join '', <TPC>;
					while ($tpc_content =~ /<post>(.*?)<\/post>/sg) {
						$msg_amount++;
					}
					close TPC;
				}
			}
		}
	}
	if (!$usr_amount) { $usr_amount = 1; }
	if (!$tpc_amount) { $tpc_amount = 0; }
	if (!$msg_amount) { $msg_amount = 0; }
	open(STATS, "> $simpleforum_dir/stats.sf") or dienice("Couldn't create statistics file: $!");
	flock STATS, 2;
	print STATS <<STATS_CONTENT;
<tpc_amount>$tpc_amount</tpc_amount>
<msg_amount>$msg_amount</msg_amount>
<usr_amount>$usr_amount<\/usr_amount>
STATS_CONTENT
	close STATS;
}

sub register {
	# Register new users
	if ($enable_guest_registration eq "off" and !$admin_access) { &page_start; print "<center>Registrations have been turned off by the forum administrator<br><br><a href='javascript:history.go(-1);'>$lang_back</a><br>"; &page_end; exit; }

	if (param('confirmed')) {
		# User registered, print confirm message
		&page_start;
		print <<HTML;
		<div align='center'><b>$lang_register</b>
		<br><br>
		<i>Your account has been created!</i>
		<br><br>Please write your password down somewhere safe. Lost passwords cannot be retrieved.<br>Click \"$lang_personal\" in the top menu to configure the forum to your liking.
		<br><br><a href='$script_name'>$lang_forum_index</a>
		<br><br>
HTML
		&page_end;
	} elsif (!param('posted')) {
		# Print the register form
		&page_start;
		print <<HTML;
		<div align='center'><b>$lang_register</b>
		<br><br>
		<div align='justify' style='width:400;'><$smallfont>$lang_register_expl</div>
		<br><form method='post' action='$script_name?register'>
		<input type='hidden' name='posted' value='1'>
		<table border="0" cellspacing="0" cellpadding="3" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor">
			<tr>
				<td>$lang_name </td>
				<td><input type='text' name='register_user'></td>
			</tr>
			<tr>
				<td>$lang_password </td>
				<td><input type='password' name='register_password'></td>
			</tr>
			<tr>
				<td>$lang_confirm </td>
				<td><input type='password' name='register_password_confirm'></td>
			</tr>
			<tr>
				<td colspan='2' align='center'><input type='submit' value='$lang_register' style='width:80px'></td>
			</tr>
		</table>
		</form>
HTML
		&page_end;
	} else {
		# Verify the input and write the new user profile + Login (set sfusr cookie)
		$register_user = param('register_user');
		$register_password = param('register_password');
		$register_password_confirm = param('register_password_confirm');
		$profile_file = $register_user;
		$profile_file =~ tr/[A-Z]/[a-z]/;

			if ($register_password eq $register_password_confirm) {
				if (length($register_password) > 3) {
					#check passw value for incorrect characters
					if ($register_password =~ /\W/) {
						#illegal character found
						dienice("Illegal character for your password, please use alphanumeric characters only!<br><br><a href='javascript:history.go(-1)'>Back</a>");
					}
				} else {
					#empty password or less than 4 chars
					dienice("The password must contain at least 4 characters<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>");
				}
			} else {
				#passw don't match
				dienice("The 2 given passwords don't match, please enter your password twice the same<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>");
			}

		if (!$register_user or !$register_password) { dienice("You forgot to enter a user name or a password<br><br><a href='javascript:history.go(-1);'>$lang_back</a>"); }
		$register_password = encrypt($register_password);

		if (-e "$users_dir/$profile_file.prf") { dienice("This user already exists! Please choose a different name.<br><br><a href='javascript:go(-1);'>$lang_back</a>"); }
		open(PROFILE, "> $users_dir/$profile_file.prf") or dienice("Couldn't create profile: $!");
		flock PROFILE, 2;
		$register_time = time;
		$register_ip = $ENV{'REMOTE_ADDR'};
		print PROFILE <<PRF_CONTENT;
<user_name>$register_user</user_name>
<user_ip>|$register_ip|</user_ip>
<user_password>$register_password</user_password>
<user_joindate>$register_time</user_joindate>
<user_rank>1</user_rank>
<user_title></user_title>
<user_posts>0</user_posts>
PRF_CONTENT
		close PROFILE;

		# log in after registration, except when this user was created by the administrator
		if (!$admin_access) {
			$cookie = cookie(-name => 'sfusr',
						 -value => "$profile_file\|$register_password");
			print "Set-Cookie: $cookie\n";
		}

		# remove the user from the Currently Online in stats
		open (STATS, "+>> $simpleforum_dir/stats.sf") or dienice("Couldn't open stats file: $!");
		flock STATS, 2;
		seek STATS, 0, 0;
		$stats_content = join '', <STATS>;
		seek STATS, 0, 0;
		truncate STATS, 0;
		$stats_content =~ s/<recentusers>(.*?)$user\:\d*?\|(.*?)<\/recentusers>/<recentusers>$1$2<\/recentusers>/sg;
		print STATS $stats_content;
		close STATS;

		# redirect admins to admin area and users to their profile
		if ($admin_access) {
			print redirect("$script_name?&fid=$forum_id&admin=1");
		} else {
			print redirect("$script_name?user_settings=1");
		}
	}
}

sub login {
	$login_referer = param('ref');
	if (!param('posted')) {
		# print the login form
		if (!$header_printed) { &page_start; }
		print <<HTML;
		<div align='center'>
		<b>$lang_log_in</b><br><br>
		$lang_login_expl
			<br><br>
		<form method='post' action='$script_name?login'>
		<input type='hidden' name='posted' value='1'>
		<input type='hidden' name='login_referer' value='$login_referer'>
		<table border='0' style='border: 1px solid;background:$postformbackground;' cellpadding='10'>
			<tr><td>
				<table border='0'>
				<tr>
					<td align='right'><b>$lang_name : </b></td>
					<td><input type='text' name='user' style='width:170;'></td>
				</tr>
				<tr>
					<td align='right'><b>$lang_password : </b></td>
					<td><input type='password' name='user_password' style='width:170;'></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><input type='checkbox' class='checkbox' name='remember_login' value='+356d'> $lang_remember_login</td>
				</tr>
				<tr>
					<td colspan='2' align='center'><br><input type='submit' value='$lang_log_in' style='width:80;'></td>
				</tr>
				</table>
			</td></tr>
		</table>
		</form>
		</div>
HTML
		if (!$header_printed) { &page_end; }
	} else {
		# verify user login input and login => set sfusr cookie
		$user = param('user');
		$user_password_input = param('user_password');
		$login_referer = param('login_referer');
		if (!$user or !$user_password_input) {
			dienice("You forgot to enter your name or password<br><br><a href='javascript:history.go(-1);'>$lang_back</a>");
		}
		$user =~ tr/[A-Z]/[a-z]/;
		$user_password_input = encrypt($user_password_input);
		open(USER_PROFILE, "< $users_dir/$user\.prf") or $error = 1;
			flock USER_PROFILE, 2;
			@user_profile_content = <USER_PROFILE>;
		close USER_PROFILE;
		foreach $line (@user_profile_content) {
			chomp $line;
			if ($line =~ /^<(.*?)>(.*?)<\/(.*?)>$/) {
				$$1 = $2;
			}
		}
		if ($user_password_input ne $user_password) { $error = 1; }
		if ($error) { dienice("You specified an invalid user name or password<br><br><a href='javascript:history.go(-1);'>$lang_back</a>"); }
		if (param('remember_login')) {
			$login_time = param('remember_login');
			$cookie = cookie(-name => 'sfusr',
					 -value => "$user\|$user_password",
					 -expires => $login_time);
		} else {
			$cookie = cookie(-name => 'sfusr',
					 -value => "$user\|$user_password");
		}
		print "Set-Cookie: $cookie\n";
		$login_referer =~ s/\$/\&/sg;

		# remove the "guest" from the Currently Online visit
		open (STATS, "+>> $simpleforum_dir/stats.sf") or dienice("Couldn't open stats file: $!");
		flock STATS, 2;
		seek STATS, 0, 0;
		$stats_content = join '', <STATS>;
		seek STATS, 0, 0;
		truncate STATS, 0;
		$stats_content =~ s/<recentusers>(.*?)guest\($ENV{'REMOTE_ADDR'}\)\:\d*?\|(.*?)<\/recentusers>/<recentusers>$1$2<\/recentusers>/sg;
		print STATS $stats_content;
		close STATS;

		print redirect("$login_referer");
	}
}


sub logout {
	# Log out => empty the sfusr cookie
	$cookie = cookie(-name => 'sfusr',
					 -value => "");
	print "Set-Cookie: $cookie\n";

	# remove the user from the Currently Online in stats
	open (STATS, "+>> $simpleforum_dir/stats.sf") or dienice("Couldn't open stats file: $!");
	flock STATS, 2;
	seek STATS, 0, 0;
	$stats_content = join '', <STATS>;
	seek STATS, 0, 0;
	truncate STATS, 0;
	$stats_content =~ s/<recentusers>(.*?)$user\:\d*?\|(.*?)<\/recentusers>/<recentusers>$1$2<\/recentusers>/sg;
	print STATS $stats_content;
	close STATS;

	print redirect("$script_name");
}


sub user_settings {
	# user settings
	if (!$logged_in) { dienice("You're not logged in"); }
	if (param('user_profile')) {
		if (!param('posted')) {
			#print the edit profile form
			&page_start;
			open(FC, "< $simpleforum_dir/stats.sf") or die "Could not open stats: $!";
			$fc_text = join '', <FC>;
			close FC;
			if ($fc_text =~ /<msg_amount>(.*?)<\/msg_amount>/ and $1) {
				$forum_totalposts = $1;
				$percent_of_total = sprintf("%.2f",($user_posts/$forum_totalposts)*100);
				$posts_per_day = sprintf("%.2f",($user_posts/((time - $user_joindate)/86400)));
				$forumstats = "<$smallfont>[$percent_of_total% $lang_of_total / $posts_per_day $lang_posts_per_day]";
			}
			if ($user_hide_email eq "yes") { $user_hide_email_on = "CHECKED"; }
			print <<HTML;
			<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <a href='$script_name?user_settings=1'>$lang_personal</a> &raquo; <i>$lang_my_profile</i></b></font></div>
			<div align='center'>
			<br>
			<$bigfont><b>$lang_profile ~ $user_name</b></font><br><br>
			<form action='$script_name?user_settings=1' method='post'>
			<input type='hidden' name='posted' value='1'>
			<input type='hidden' name='user_profile' value='1'>
			<input type='hidden' name='user_settings' value='1'>
			<table border='1' cellspacing=0 cellpadding='10' bordercolorlight='gray' bordercolordark='#000000'>
				<tr>
					<!-- TD FOR AVATAR AND CONTACT -->
					<td valign='top'>
						<table border=0 cellspacing=0 cellpadding=0>
							<tr>
								<!-- TD for avatar -->
								<td align='center' valign='top'></font>
									<font class='tablefield'><b>$lang_avatar</b></font>
									<font class='forumlink'><br><br></font>
HTML
if ($user_avatar) { print "<img src='$user_avatar' width=100 height=100>"; } else { print "<table border=1><tr><td height=100 width=100 valign='middle' align='center'>$lang_none</td></tr></table>"; }
print <<HTML;
									<br>URL : <input type='text' name='user_avatar' value='$user_avatar' style='width:70%'>
									<hr color='black' width='100%'>
								</td>
							</tr>
							<tr>
								<!-- TD for contact -->
								<td valign='top' align='center'>
									<b>$lang_contact</b>
									<br>
									<table border=0 cellspacing=7>
										<tr>
											<td valign='top' align='right'><$smallfont>$lang_email_address :</font></td>
											<td valign='top' align='left'><input type='text' name='user_email' value='$user_email'>
											<br><input type='checkbox' name='user_hide_email' value='yes' $user_hide_email_on> <$smallfont>$lang_hide <a href="javascript:divHide('hide_email_expl','show');">($lang_more)</a>
											<div id='hide_email_expl' style='width:170' align='justify' class='hidden'>$lang_hide_expl</div></$smallfont></td>
										</tr>
										<tr>
											<td valign='top' align='right'><$smallfont>$lang_icq_number :</font></td>
											<td valign='top' align='left'><input type='text' name='user_icq' value='$user_icq'></b></td>
										</tr>
										<tr>
											<td valign='top' align='right'><$smallfont>$lang_aol_aim :</font></td>
											<td valign='top' align='left'><input type='text' name='user_aol' value='$user_aol'></td>
										</tr>
										<tr>
											<td valign='top' align='right'><$smallfont>$lang_msn_messenger :</font></td>
											<td valign='top' align='left'><input type='text' name='user_msn' value='$user_msn'></td>
										</tr>
										<tr>
											<td valign='top' align='right'><$smallfont>$lang_yahoo_messenger :</font></td>
											<td valign='top' align='left'><input type='text' name='user_yahoo' value='$user_yahoo'></td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
					<!-- TD : ABOUT $user_name -->
					<td valign='top' valign='top'>
						<table border=0 cellspacing=0 cellpadding=0>
							<tr>
								<td align='center'>
									<b>$lang_about $user_name...</b><br>
									<table border=0 cellspacing=7>
										<tr>
											<td valign='top' align='right'>$lang_joined :</td>
											<td valign='top' align='left'><b>
HTML
print &date_time($user_joindate).<<HTML;
												</b>
											</td>
										</tr>
										<tr>
											<td valign='top' align='right'>$lang_real_name :</td>
											<td valign='top' align='left'><input type='text' name='user_realname' value='$user_realname'></td>
										</tr>
										<tr>
											<td valign='top' align='right'>$lang_location :</td>
											<td valign='top' align='left'><input type='text' name='user_location' value='$user_location'></td>
										</tr>
										<tr>
											<td valign='top' align='right'>$lang_website :</td>
											<td valign='top' align='left'><input type='text' name='user_website' value='$user_website'></td>
										</tr>
										<tr>
											<td valign='top' align='right'>$lang_occupation :</td>
											<td valign='top' align='left'><input type='text' name='user_occupation' value='$user_occupation'></td>
										</tr>
										<tr>
											<td valign='top' align='right'>$lang_interests :</td>
											<td valign='top' align='left'><textarea style='width:200;height:60;' name='user_interests'>$user_interests</textarea></td>
										</tr>
									</b></font>
								</td>
							</tr>
							<tr>
								<td valign='top' align='right'>$lang_forum_posts :</td>
								<td valign='top' align='left'><b>$user_posts</b>
							</tr>
							<tr>
								<td>&nbsp;</td>
								<td><$smallfont>
								$forumstats
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>
<BR>
<input type='submit' value='$lang_save_changes'>
<input type='reset' value='$lang_revert'>
</form>
</div>
HTML
			&page_end;
		} else {
			# edit the user's profile file
			open(USER_PROFILE, "+>> $users_dir/$user\.prf") or dienice("Couldn't open your profile for writing!");
				flock USER_PROFILE, 2;
				seek USER_PROFILE, 0, 0;
				$user_profile_content = join '', <USER_PROFILE>;

				# get and change the values for the user variables
				@user_profile_vars = ("user_email","user_hide_email","user_icq","user_aol","user_msn","user_yahoo","user_avatar","user_realname","user_location","user_website","user_occupation","user_interests");
				foreach $user_profile_var(@user_profile_vars) {
					$user_profile_var_value = param($user_profile_var);
					if ($user_profile_content =~ /<$user_profile_var>(.*?)<\/$user_profile_var>\n/s) {
						$user_profile_content =~ s/<$user_profile_var>(.*?)<\/$user_profile_var>\n/<$user_profile_var>$user_profile_var_value<\/$user_profile_var>\n/sg;
					} else {
						$user_profile_content .= "<$user_profile_var>$user_profile_var_value<\/$user_profile_var>\n";
					}
				}
				seek USER_PROFILE, 0, 0;
				truncate USER_PROFILE, 0;
				# set http:// before the user_website if necessary:
				if ($user_profile_content =~ /<user_website>(.*?)<\/user_website>\n/ and $1 and $1 !~ /^http:\/\//sg) { $user_profile_content =~ s/<user_website>(.*?)<\/user_website>\n/<user_website>http:\/\/$1<\/user_website>\n/sg; }
				print USER_PROFILE $user_profile_content;
			close USER_PROFILE;
			print redirect("$script_name?user_settings=1");
			exit;
		}
	} elsif (param('user_prefs')) {
		# user preferences
		if (!param('posted')) {
			# print user preferences form
			&page_start;
			print <<HTML;
				<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <a href='$script_name?user_settings=1'>$lang_personal</a> &raquo; <i>My Settings</i></b></font></div>
				<div align='center'>
				<br>
				<$bigfont><b>My Settings</b></font><br><br>
				<form method='post' action='$script_name?fid=$forum_id&user_settings=1'>
				<input type='hidden' name='posted' value='1'>
				<input type='hidden' name='user_prefs' value='1'>
				<input type='hidden' name='user_settings' value='1'>
				<center>
				<table border="1" width='600' cellspacing="0" cellpadding="15" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
				<tr><td>
				<table border=0 width='100%'>
				<b>Signatures</b>
				<$smallfont><br><i>These are small messages that will be added at the bottom of your message. If you choose to have more than one signature, the forum will choose one for you randomly.</i>
				<table border='0'>
					<tr>
						<td><$smallfont>Signature 1:</font><br>
							<TEXTAREA ROWS=5 NAME='user_sign1' WRAP='virtual' style='width:250px;'>$user_sign1</TEXTAREA></td>
						<td><$smallfont>Signature 2:</font><br>
							<TEXTAREA ROWS=5 NAME='user_sign2' WRAP='virtual' style='width:250px;'>$user_sign2</TEXTAREA></td>
					</tr>
					<tr>
						<td align='left'><$smallfont>Signature 3:</font><br>
							<TEXTAREA ROWS=5 NAME='user_sign3' WRAP='virtual' style='width:250px;'>$user_sign3</TEXTAREA></td>
						<td align='left'><$smallfont>Signature 4:</font><br>
							<TEXTAREA ROWS=5 NAME='user_sign4' WRAP='virtual' style='width:250px;'>$user_sign4</TEXTAREA></td>
					</tr>
				</table>
				<br>
					<div align='center'><input type='submit' value='Submit Changes' style='width:150;'><input type='reset' value='Revert' style='width:150;'></div>
					</td>
				</tr>
			</table>
		</table>
HTML
			&page_end;
		} else {
			# user preferences form submitted
			@variables = ("user_sign1","user_sign2","user_sign3","user_sign4");
			open(PRF, "< $users_dir/$user.prf") or dienice("Couldn't open users profile");
				flock PRF, 2;
				$profile_text = join '', <PRF>;
				foreach $variable(@variables) {
						$variable_value = param($variable);
						if ($profile_text =~ /<$variable>(.*?)<\/$variable>\n/s) {
							$profile_text =~ s/<$variable>(.*?)<\/$variable>\n/<$variable>$variable_value<\/$variable>\n/sg;
						} else { # add the variable
							$profile_text .= "<$variable>$variable_value<\/$variable>\n";
						}
				}
			close PRF;
			open (PRF, "> $users_dir/$user.prf") or dienice("Couldn't open profile for writing: $!");
			flock PRF, 2;
			print PRF $profile_text; # comes from sub start at the beginning of the script
			close PRF;
			print redirect("$script_name?user_settings=1");
			exit;
		}
	} else {
		# print user settings main
		&page_start;
		print <<HTML;
		<div align='center'>
		<div align='center'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk &raquo; <i>$lang_personal</i></b></font></div>
		<br>
		<form method='post' action='$script_name?fid=$forum_id&user_settings=1'>
			<input type='submit' value='$lang_my_profile' style='width:150'>
			<input type='hidden' name='user_settings' value='1'>
			<input type='hidden' name='user_profile' value='1'>
		</form>
HTML
		if ($enable_private_messages eq "on") {
		print <<HTML;
		<form method='post' action='$script_name?fid=$forum_id&user_settings=1&pmsg=1'>
			<input type='submit' value='$lang_private_messages' style='width:150'>
			<input type='hidden' name='user_settings' value='1'>
			<input type='hidden' name='pmsg' value='1'>
		</form>
HTML
		}
		print <<HTML;
		<form method='post' action='$script_name?fid=$forum_id&user_settings=1'>
			<input type='submit' value='My Settings' style='width:150'>
			<input type='hidden' name='user_settings' value='1'>
			<input type='hidden' name='user_prefs' value='1'>
		</form>
		</div>
HTML
		&page_end;
	}
}


sub private_messages {
	# This sub handles everything that has to do with private messaging

	if ($enable_private_messages eq "off") { &page_start; print "<center>The Private Messaging feature has been disabled by the administrator<br><br><a href='javascript:history.go(-1);'>$lang_back</a><br>"; &page_end; exit; }

	$pmsg_dir = "$users_dir/private_messages"; # This is the directory where the date files are stored

	# $box (as defined in the line below) is the "place" where you are inside the private messaging system. It can be either the Inbox or the Outbox or Send Message ("box")
	if (param('outbox')) { $box = $lang_outbox; } elsif (param('send_pmsg') or param('sendto')) { $box = $lang_send_message } else { $box = $lang_inbox }

	if (!param('del')) {
		# print the header for all private messages pages (except when deleting, because the delete part uses a redirect)
		# This is the "header" for all the private messages pages
		&page_start;
		if (param('user_settings')) { $user_settings = param('user_settings'); $user_settings_lnk = " &raquo; <a href='$script_name?fid=$forum_id&user_settings=$user_settings'>$lang_personal</a>"; }

		#print private messages menu
		print "<center><b>$lang_private_messages</b><br><$smallfont><a href='$script_name?fid=$forum_id&pmsg=1&user_settings=$user_settings'>$lang_inbox</a> - <a href='$script_name?fid=$forum_id&pmsg=1&user_settings=$user_settings&outbox=1'>$lang_outbox</a> - <a href='$script_name?fid=$forum_id&pmsg=1&user_settings=$user_settings&send_pmsg=1'>$lang_send_message</a><br><br></font>";

		print "<div align='left' style='width:$tablewidth;'><$smallfont><b>&raquo; <a href='$script_name'>$lang_forum_index</a>$frm_lnk $user_settings_lnk &raquo; <i>$lang_private_messages </i>&raquo;<i> $box</i></b></font></div>";
	}

	if (param('send_pmsg') or param('sendto')) {
		# For sending new private messages
		if (!param('posted')) {
			# print the send private message form

			# param sendto (if it exists) contains the recipient
			if (param('sendto')) { $pmsg_recipient = param('sendto'); }

			print <<HTML;
			<br>
			<table border="1" cellspacing="0" cellpadding="10" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
			<form name='post_form' method='post' action='$script_name?fid=$forum_id&pmsg=1&user_settings=$user_settings'>
			<input type='hidden' name='posted' value='1'>
			<input type='hidden' name='pmsg' value='1'>
			<input type='hidden' name='user_settings' value='$user_settings'>
			<input type='hidden' name='send_pmsg' value='1'>
			<table border=0 cellspacing=7 width='600'>
				<tr>
				<td><font class='tablefield'><b>$lang_recipient</b></font></td>
				<td><font class='tabletext'>
HTML
			if ($pmsg_recipient) {
				# if the recipient is predefined, just open his profile and get his name
				open(STPRF,"< $users_dir/$pmsg_recipient.prf") or dienice("Unknown user!\n");
				flock STPRF, 2;
				$stprf_text = join '', <STPRF>;
				close STPRF;
				if ($stprf_text =~ /<user_name>(.*?)<\/user_name>/) {
					print "<input type='hidden' name='pmsg_recipient' value='$pmsg_recipient'>\n$1";
				} else { dienice("Couldn't find name! Recipient unknown or corrupted profile."); exit; }
			} else {
				# if the recipient is *not* predifined, get a list of all known users and let the sender select a recipient
				# get the name for every possible recipient
				open_dir($users_dir);
				print "<select name='pmsg_recipient' style='width:200;'>\n<option value=''>&laquo; $lang_select &raquo;</option>\n";

				foreach $file(sort(@files)) {
					if ($file =~ /^(.*?).prf$/ and $1 ne "guest") {
						$stuser = $1;
						open(STPRF,"< $users_dir/$file") or die "Couldn't find $file: $!\n";
						flock STPRF, 2;
						$stprf_text = join '', <STPRF>;
						close STPRF;
						if ($stprf_text =~ /<user_name>(.*?)<\/user_name>/) {
							print "<option value='$stuser'>$1</option>\n";
						}
					}
				}
			}
			print "</select>\n";

			# Print the rest of the form : Title and Message
			print <<HTML;
			</td>
			</tr>
			<tr>
			<td><b>$lang_subject</b></td>
			<td><input type='text' name='pmsg_subject' style='width:480;'></td>
			</tr>
			<tr>
			<td valign='top'><b>$lang_message</b><br>
HTML
			&print_emoticon_table;
			print <<HTML;
			</td><td><textarea name='message' style='width:480; height:200;'></textarea></td>
			</tr>
			<tr>
			<td colspan=2 align='center'><input type='submit' value='$lang_send' style='width:100;'></td>
			</tr>
			</table>
			</form>
			</td></tr>
			</table>
HTML
		} else {
			# form is submitted; send the message
			# check input
			$pmsg_recipient = param('pmsg_recipient');
			$pmsg_subject = param('pmsg_subject');
			$pmsg_message = param('message');
			if (!$pmsg_recipient) { $err .= "- select a recipient<br>\n"; }
			if (!$pmsg_subject) { $err .= "- enter a subject<br>\n"; }
			if (!$pmsg_message) { $err .= "- enter a message<br>\n"; }
			if ($err) { print "<br><center><b>Message could not be sent. You forgot to</b><br>\n<table border=0><tr><td>$err</td></tr></table><br>\n<a href='javascript:history.go(-1)'>$lang_back</a></center>"; exit;}

			# create pmsg dir if it doesn't already exist
			if (!-e $pmsg_dir) { mkdir($pmsg_dir, 0777); }

			#open recipient's private messages file and write the new private message (1), dito for outbox of the sender (2)
			$pmsg_message .= "\n";

			# 1 - Write to recipient's inbox file
			open(PMSG,"+>> $pmsg_dir/$pmsg_recipient\_in.pmsg") or die "Couldn't open $pmsg_recipient_in.pmsg";
			flock PMSG, 2;
			seek PMSG, 0, 0;
			$pmsg_text = join '', <PMSG>;
			seek PMSG, 0, 0;
			truncate PMSG, 0;
			$pmsg_time = time;
			print PMSG <<PMSG;
<pmsg>
<pmsg_read>no</pmsg_read>
<pmsg_sender>$user</pmsg_sender>
<pmsg_time>$pmsg_time</pmsg_time>
<pmsg_subject>$pmsg_subject</pmsg_subject>
<pmsg_message>$pmsg_message</pmsg_message>
</pmsg>

PMSG
			print PMSG $pmsg_text;
			close PMSG;

			# 2 - Write to the sender's outbox file
			open(PMSG_OUTBOX,"+>> $pmsg_dir/$user\_out.pmsg") or die "Couldn't open $user_out.pmsg";
			flock PMSG_OUTBOX, 2;
			seek PMSG_OUTBOX, 0, 0;
			$pmsg_outbox_text = join '', <PMSG_OUTBOX>;
			seek PMSG_OUTBOX, 0, 0;
			truncate PMSG_OUTBOX, 0;
			print PMSG_OUTBOX <<PMSG;
<pmsg>
<pmsg_sender>$pmsg_recipient</pmsg_sender>
<pmsg_time>$pmsg_time</pmsg_time>
<pmsg_subject>$pmsg_subject</pmsg_subject>
<pmsg_message>$pmsg_message</pmsg_message>
</pmsg>

PMSG
			print PMSG_OUTBOX $pmsg_outbox_text;
			close PMSG_OUTBOX;

			# open the recipient's profile and reset the private messages popup
			open (PRFP, "+>> $users_dir/$pmsg_recipient.prf") or dienice("Couldn't open $pmsg_recipient.prf:$!");
			flock PRFP,2;
			seek PRFP, 0, 0;
			$prfp_text = join '', <PRFP>;
			seek PRFP, 0, 0;
			truncate PRFP, 0;
			if ($prfp_text =~ /<user_pmsg_popped>(.*?)<\/user_pmsg_popped>\n/s) {
				$prfp_text =~ s/<user_pmsg_popped>(.*?)<\/user_pmsg_popped>\n/<user_pmsg_popped>no<\/user_pmsg_popped>\n/s;
			} else {
				$prfp_text .= "<user_pmsg_popped>no<\/user_pmsg_popped>\n";
			}
			print PRFP $prfp_text;
			close PRFP;

			# print a message to ensure the sender that the private message has been sent (and nothing went wrong)
			$pmsg_subject = add_html($pmsg_subject); # add html, smileys, bbcode, ...
			$pmsg_message = add_html($pmsg_message);
			print <<HTML;
			<br>
			<center><font class='newsheader'><b>$lang_message_sent_to $pmsg_recipient!</b></font></p>
			<table border="1" width='600' cellspacing="0" cellpadding="20" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$postformbackground">
			<tr><td>
				<table cellspacing=7 border=0>
				<tr>
				<td><b>$lang_subject</b></td>
				<td>$pmsg_subject</td>
				</tr>
				<tr>
				<td valign='top'><b>$lang_message</b></td>
				<td>$pmsg_message</td>
				</tr>
				</table>
			</td></tr>
			</table>
HTML
		}
	} elsif (param('del')) {
		# Delete a private message from inbox or outbox

		# set the file in which the message should be deleted, either the inbox file, else the outbox file
		if (param('outbox')) { $pmsg_file = "$user\_out.pmsg"; $outbox = param('outbox'); }	# outbox file
		else { $pmsg_file = "$user\_in.pmsg"; }												# inbox file

		# The $del_id variable is based on the time when the to-be-deleted-private-message
		# was sent. We scan the content of the pmsg and remove the pmsg matching the del_id.
		$del_id = param('del');
		open(PMSG, "+>> $pmsg_dir/$pmsg_file") or dienice("$pmsg_file: $1");
			flock PMSG, 2;
			seek PMSG, 0,0;
			$pmsg_text = join '', <PMSG>;
			seek PMSG, 0,0;
			truncate PMSG, 0;
			$pmsg_text =~ s/^(.*)<pmsg>\n.*?\n<pmsg_time>$del_id<\/pmsg_time>\n.*?<\/pmsg>\n(.*)$/$1$2/sg;
			print PMSG $pmsg_text;
		close PMSG;
		$user_settings = param('user_settings');

		# redirecting the user to the inbox or outbox depending on where he came from
		print redirect("$script_name?fid=$forum_id&pmsg=1&user_settings=$user_settings&outbox=$outbox");
		exit;
	} else {
		# INBOX & OUTBOX - This will print out all Private Messages in the inbox OR in the outbox
		# open private messages file for this user

		# Set the file from which to read the messages; either inbox or outbox
		if (param('outbox')) { $pmsg_file = "$user\_out.pmsg"; $outbox = param('outbox'); }	# outbox file
		else { $pmsg_file = "$user\_in.pmsg"; } 											# inbox file

		# open and get the contents from the private messages file
		open(PMSG, "+>> $pmsg_dir/$pmsg_file");
		flock PMSG, 2;
		seek PMSG, 0, 0;
		$pmsg_text = join '', <PMSG>;
		$new_pmsg_text = $pmsg_text;
		# mark every unread message as read
		$new_pmsg_text =~ s/<pmsg_read>no<\/pmsg_read>\n/<pmsg_read>yes<\/pmsg_read>\n/sg;
		seek PMSG, 0, 0;
		truncate PMSG, 0;
		print PMSG $new_pmsg_text;
		close PMSG;

		# The while loop below goes through every private message one by one, parsing and printing the data
		while ($pmsg_text =~ /<pmsg>\n(.*?)<\/pmsg>\n/sg) {
			$pmsg_printed = 1; # if the private messages file contains one message (and thus prints one message), we disable the "No messages" note.
			$pmsg = $1;

			# parse the private message (in the loop)
			if ($pmsg =~ /<pmsg_sender>(.*?)<\/pmsg_sender>\n/s) { $pmsg_sender = $1; }
			if ($pmsg =~ /<pmsg_read>(.*?)<\/pmsg_read>\n/s) { $pmsg_read = $1; }
			if ($pmsg =~ /<pmsg_time>(.*?)<\/pmsg_time>\n/s) { $pmsg_time = $1; }
			if ($pmsg =~ /<pmsg_subject>(.*?)<\/pmsg_subject>\n/s) { $pmsg_subject = $1; }
			if ($pmsg =~ /<pmsg_message>(.*?)<\/pmsg_message>\n/s) { $pmsg_message = $1; }

			# reset vars
			$pmsg_user = ""; $pmsg_avatar = ""; $pmsg_title = ""; $pmsg_posts = ""; $pmsg_status = "";

			# check whether the sender of the message is a registered user
			if (-e "$users_dir/$pmsg_sender\.prf") {
				$pmsg_sender;
				# This is a registered user! Get his avatar, name, post-amount, ...
				open(PMSG_PROFILE, "< $users_dir/$pmsg_sender\.prf");
					flock PMSG_PROFILE, 2;
					$pmsg_profile = join '', <PMSG_PROFILE>;
				close PMSG_PROFILE;
				if ($pmsg_profile =~ /<user_name>(.*?)<\/user_name>\n/s) {
					$pmsg_name = "<a href=\"$script_name?pid=$pmsg_user\">$1</a>";
				}
				if ($pmsg_profile =~ /<user_avatar>(.*?)<\/user_avatar>\n/s) {
					$pmsg_avatar = $1;
				}
				if ($pmsg_profile =~ /<user_posts>(.*?)<\/user_posts>\n/s) {
					$pmsg_posts = $1;
				}
				if ($pmsg_profile =~ /<user_title>(.*?)<\/user_title>\n/s) {
					$pmsg_title = $1;
				}
			} else {
				$pmsg_title = $lang_guest;
			}

			$pmsg_subject = add_html($pmsg_subject); #add smileys, images, url's, ...
			$pmsg_message = add_html($pmsg_message);

			#This line takes care of the color switching
			if ($tablecolor eq $tablecolor1) { $tablecolor = $tablecolor2; } else { $tablecolor = $tablecolor1; }

			#Make $pmsg_time "readable" ;)
			date_time($pmsg_time);

			# determine the user's title
			if (!$post_title and $enable_user_titles eq "on") {
				if ($post_posts < $title_lvl2_posts) { $post_title = $title_lvl1; }
				elsif ($post_posts < $title_lvl3_posts) { $post_title = $title_lvl2; }
				elsif ($post_posts < $title_lvl4_posts) { $post_title = $title_lvl3; }
				elsif ($post_posts < $title_lvl5_posts) { $post_title = $title_lvl4; }
				elsif ($post_posts < $title_lvl6_posts) { $post_title = $title_lvl5; }
				elsif ($post_posts) { $post_title = $title_lvl6; }
			}

			# set the border color for new messages
			if ($pmsg_read eq "no") { $borderstyle = "style='border-color:#FF0000;'"; } else { $borderstyle = ""; }

			# print the shiz (one message in a loop)
			print <<HTML;
			<div align='right' style='width:$tablewidth;'><$smallfont>$lang_posted_on $short_date $hour:$min:$sec$ampm</div>
			<table width="$tablewidth" border="1" cellspacing="0" cellpadding="4" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor" $borderstyle>
			<tr>
				<td align='left' width='150' valign='top'>
					<$bigfont><b>$pmsg_name</b></font>
HTML
			if ($pmsg_title and $enable_user_titles eq "on") { print "<br><$smallfont>$pmsg_title</font>"; }
			if ($pmsg_posts) { print "<br><$smallfont>$lang_posts: $pmsg_posts</font>"; }
			print <<HTML;
					<br>
					<$smallfont><br><a href='$script_name?fid=$forum_id&user_settings=$user_settings&pmsg=1&sendto=$pmsg_sender'>$lang_reply</a> | <a href='$script_name?fid=$forum_id&user_settings=$user_settings&pmsg=1&del=$pmsg_time&outbox=$outbox'>Delete</a>
					</font>
HTML
			if ($pmsg_avatar) { print "<br><br><img src='$pmsg_avatar' height='70' width='70'>"; }
			print <<HTML;
				</td>
				<td valign='top'>
					<$bigfont><b>$pmsg_subject</b>
					<hr>
					$pmsg_message
				</tr>
			</tr>
			</table>
			<br>
HTML
		}
		if (!$pmsg_printed) {
			# no messages in Inbox
			print <<HTML;
			<br><table width="$tablewidth" border="1" cellspacing="0" cellpadding="10" bordercolordark="$tablebordercolor" bordercolorlight="$tablebordercolor" bgcolor="$tablecolor" $borderstyle>
				<tr><td bgcolor='$tablecolor1' align='center'><i>$lang_there_are_currently_no_messages_in_your $box.</i></td></tr>
			</table>\n
HTML
		}
	}
	# print the page footer for every private messages page
	&page_end;
}


# # # # DO NOT EDIT ANYTHING BELOW # # # # # # # # # # # # # # # # # #

sub installation {
	if ($admin_account) { return undef; } #already installed
	$admin_account = param('admin_account');
	$admin_password = param('admin_password');
	$admin_password1 = param('admin_password1');
	$admin_password2 = param('admin_password2');
	$images_dir = param('images_dir');

	if (!param('step3b')) { # admin log in on installation complete, so don't print the normal headers!
		print header . <<HTML;
		<HTML>
		<head><title>Simpleforum $version - Installation</title></head>

		<style type='text/css'>
		<!--
		.hidden { display: none; }
		-->
		</style>

		<script language="JavaScript" type="text/javascript">
		<!--
		function divHide(id,mode)
		{
			if (document.getElementById)
			{
				if(mode == 'show')
				{
				  document.getElementById(id).style.display = 'block';
				}
				else
				{
				  document.getElementById(id).style.display = 'none';
				}
			}
			else if(document.all)
			{
				if(mode == 'show')
				{
				  document.all[id].style.display = '';
				}
				else
				{
				  document.all[id].style.display = 'none';
				}
			}
		}
		-->
		</script>

		<body>
		<center>
		<div align='justify'><font face='verdana' size='2'><font size='4'><b>Welcome to Simpleforum Pro $version!</b></font>
		<hr>
		In order to make this script work on your server there are a few steps you need to follow. Please read the instructions carefully!
		<br><br>
HTML
	}

	if (param('step1')) {
		if (param('step2')) {
			if (param('step3a')) {
				if (param('step3b')) {
					#installation complete

					# assign users directory location and create it if necessary
					$users_dir = "$simpleforum_dir/users";
					if (!-e $users_dir) {mkdir($users_dir,0777) or dienice("Couldn't create the users directory: $!");}

					# write the administrator's profile
					$profile_file = $admin_account;
					$profile_file =~ tr/[A-Z]/[a-z]/;
					if (-e "$users_dir/$profile_file.prf") { print "This user already exists! Please choose a different name.<br><br><a href='javascript:go(-1);'>Back</a>"; exit; }
					open(PROFILE, "> $users_dir/$profile_file.prf") or dienice("Couldn't create profile: $!");
					flock PROFILE, 2;
					$register_time = time;
					$register_ip = $ENV{'REMOTE_ADDR'};
					$admin_password = encrypt($admin_password);
					print PROFILE <<PRF_CONTENT;
<user_name>$admin_account</user_name>
<user_ip>|$register_ip|</user_ip>
<user_password>$admin_password</user_password>
<user_joindate>$register_time</user_joindate>
<user_rank>1</user_rank>
<user_title>Administrator</user_title>
<user_posts>0</user_posts>
PRF_CONTENT
					close PROFILE;

					# write the simpleforum.conf file
					open(CONF, "> $simpleforum_dir/simpleforum.conf") or $die = 1;
					if ($die) { print "Couldn't write the configuration to the $simpleforum_dir directory! ($!) Please make sure that you've set the permissions of this directory to 777 (or whatever fits for your webserver's configuration</body></html>"; exit; }
					flock CONF, 2;
					print CONF <<CONFCONTENT;
admin_account:$profile_file
images_dir:$images_dir
CONFCONTENT
					close CONF;
					$cookie = cookie(-name => 'sfusr',
									 -value => "$profile_file\|$admin_password");
					print "Set-Cookie: $cookie\n";
					print header."<HTML>
					<head><title>Simpleforum $version - Installation</title></head>
					<body>
					<center>
					<div align='justify'><font face='verdana' size='2'><font size='4'><b>Welcome to Simpleforum Pro $version!</b></font>
						<hr>
					<b>Installation complete!</b>
					<br><br>To configure your forum any further, go to the Admin area on your forum by clicking \"Admin\" in the top menu. Enjoy!<br><br><a href='$script_name'>Click here to enter your forum</a><br></body></html>";
					exit;
				} else { # step 3b
					# add a slash (/) if necessary
					if ($images_dir and $images_dir !~ /^(.*?)\/$/) { $images_dir .= "/"; } elsif (!$images_dir) { $images_dir = "$simpleforum_dir/images/"; }
					print <<HTML;
					<b>Step 3 - Images!</b>
							<br><i>If you can see the following image, click "Finish!", else click "Continue".
							<br>Image: <img src='$images_dir\smileys/w00t.gif'>
							<br><br>
							<form method='post' action='$script_name?installation'>
								<input type='hidden' name='simpleforum_dir' value='$simpleforum_dir'>
								<input type='hidden' name='admin_account' value='$admin_account'>
								<input type='hidden' name='admin_password' value='$admin_password'>
								<input type='hidden' name='images_dir' value='$images_dir'>
								<input type='hidden' name='step1' value='1'>
								<input type='hidden' name='step2' value='1'>
								<input type='hidden' name='step3a' value='1'>
								<input type='hidden' name='step3b' value='1'>
								<input type='submit' value='Finish!'><input type='button' onClick="javascript:divHide('images_form','show');" value="Continue">
							</form>
							<div id='images_form' class='hidden'>
							<br>If the image above doesn't show, it means that the images directory which is located in $simpleforum_dir cannot be reached from the browser.
							<br>
							<br>To fix this issue, read the following instructions carefully.
							<ul>
								<li>Go to your simpleforum directory ($simpleforum_dir)</li>
								<li>Move the "images" directory, located in $simpleforum_dir to somewhere outside the cgi-bin (or outside the directory configured to execute cgi scripts)</li>
								<li>If you don't get the previous step, just move the images directory to the http root level of your server (the directory where you place your html files).</li>
								<li>Try accessing the images directory through your browser by going to the new location of the images directory. (Open a new window)
								<ul><li>Example: http://www.mydomain.com/path/to/images/</li></ul></li>
								<li>If you can see the images, enter the location in the text-field below; else keep moving the images directory around on your server until you find a suitable location for it.</li>
							</ul>
							<br><b><font size=1>Enter URL to images directory here:</font></b>
							<br>
							<form method='post' action='$script_name?installation'>
								<input type='hidden' name='simpleforum_dir' value='$simpleforum_dir'>
								<input type='hidden' name='admin_account' value='$admin_account'>
								<input type='hidden' name='admin_password' value='$admin_password'>
								<input type='hidden' name='step1' value='1'>
								<input type='hidden' name='step2' value='1'>
								<input type='hidden' name='step3a' value='1'>
								<input type='text' name='images_dir' value='$images_dir' size='60'>
								<input type='submit' value='Continue'>
								<br><font size='1'>Example: http://www.mydomain.com/path/to/images/</font>
							</form>
							</div>
HTML
				}
			} else { # step 3a
				if ($admin_account) {
					while ($admin_account =~ /(\W)/sg) {
						if ($1 ne ' ') {
							print "<b>Whoops!</b><br><br>Illegal character(s) found in your user name, please use alphanumeric characters only<br><br><a href='javascript:history.go(-1);'>Back</a>"; exit;
						}
					}
					$profile_file = $admin_account;
					$profile_file =~ tr/[A-Z]/[a-z]/;
					if (-e "$simpleforum_dir/users/$profile_file.prf") {
						print "<b>Whoops!</b><br><br>This account already exists<br><br><a href='javascript:history.go(-1);'>Back</a>"; exit;
					}
				} else {
					print "<b>Whoops!</b><br><br>You forgot to enter an account name!<br><br><a href='javascript:history.go(-1);'>Back</a>"; exit;

				}
				if ($admin_password1 eq $admin_password2) {
					$admin_password = $admin_password1;
					if (length($admin_password) > 3) {
						#check passw value for incorrect characters
						if ($admin_password !~ /\W/) {
							print <<HTML;
							<b>Step 3 - Images!</b>
							<br><i>If you can see the following image, click "Finish!", else click "Continue".
							<br>Image: <img src='$simpleforum_dir/images/smileys/w00t.gif'>
							<br><br>
							<form method='post' action='$script_name?installation'>
								<input type='hidden' name='simpleforum_dir' value='$simpleforum_dir'>
								<input type='hidden' name='admin_account' value='$admin_account'>
								<input type='hidden' name='admin_password' value='$admin_password'>
								<input type='hidden' name='step1' value='1'>
								<input type='hidden' name='step2' value='1'>
								<input type='hidden' name='step3a' value='1'>
								<input type='hidden' name='step3b' value='1'>
								<input type='submit' value='Finish!'><input type='button' onClick="javascript:divHide('images_form','show');" value="Continue">
							</form>
							<div id='images_form' class='hidden'>
							<br>If the image above doesn't show, it means that the images directory which is located in $simpleforum_dir cannot be reached from the browser.
							<br>
							<br>To fix this issue, read the following instructions carefully.
							<ul>
								<li>Go to your simpleforum directory ($simpleforum_dir)</li>
								<li>Move the "images" directory, located in $simpleforum_dir to somewhere outside the cgi-bin (or outside the directory configured to execute cgi scripts)</li>
								<li>If you don't get the previous step, just move the images directory to the http root level of your server (the directory where you place your html files).</li>
								<li>Try accessing the images directory through your browser by going to the new location of the images directory. (Open a new window)
								<ul><li>Example: http://www.mydomain.com/path/to/images/</li></ul></li>
								<li>If you can see the images, enter the location in the text-field below; else keep moving the images directory around on your server until you find a suitable location for it.</li>
							</ul>
							<br><b><font size=1>Enter URL to images directory here:</font></b>
							<br>
							<form method='post' action='$script_name?installation'>
								<input type='hidden' name='admin_account' value='$admin_account'>
								<input type='hidden' name='simpleforum_dir' value='$simpleforum_dir'>
								<input type='hidden' name='admin_password' value='$admin_password'>
								<input type='hidden' name='step1' value='1'>
								<input type='hidden' name='step2' value='1'>
								<input type='hidden' name='step3a' value='1'>
								<input type='text' name='images_dir' value='http://www.mydomain.com/path/to/images/' size='60'>
								<input type='submit' value='Continue'>
								<br><font size='1'>Example: http://www.mydomain.com/path/to/images/</font>
							</form>
							</div>
HTML
						} else {
							#illegal character found
							print "<b>Whoops!</b><br><br>Incorrect value for the Administrator Password, please use alphanumeric characters only!<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit;
						}
					} else {
						#empty password or less than 4 chars
						print "<b>Whoops!</b><br><br>The password must contain at least 4 characters<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit;
					}
				} else {
					#passw don't match
					print "<b>Whoops!</b><br><br>The 2 given passwords don't match, please enter the admin password twice the same<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit;
				}
			}
		} else { # step 2
			if (!$simpleforum_dir) { print "<b>Whoops!</b><br><br>No value given for the simpleforum files directory<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit; }
			if (!-e $simpleforum_dir) { print "<b>Whoops!</b><br><br>Looks like the directory ($simpleforum_dir) could not be located!<br>Please set the simpleforum_files directory in the right place, next to $script_name.<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit; }
			open(FILE, "> $simpleforum_dir/permissionscheck.txt") or $permissions_error = 1;
			print FILE "Test";
			close FILE;
			if ($permissions_error) { print "<b>Whoops!</b><br><br>Could not write to the directory '$simpleforum_dir'. Please set the permissions for this directory to 777 (or whatever fits for your webserver's configuration).<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit; }
			open(FILE, "< $simpleforum_dir/permissionscheck.txt") or $permissions_error = 1;
			close FILE;
			if ($permissions_error) { print "<b>Whoops!</b><br><br>Could not read from the directory '$simpleforum_dir'. Please set the permissions for this directory to 777 (or whatever fits for your webserver's configuration).<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit; }
			unlink "$simpleforum_dir/permissionscheck.txt";
			if (-e "$simpleforum_dir/simpleforum.conf") {
				open(FILE, "+>> $simpleforum_dir/simpleforum.conf") or $permissions_error = 1;
				close FILE;
				if ($permissions_error) { print "<b>Whoops!</b><br><br>Your simpleforum.conf file is not readable by the script. This means you have somehow changed its owner/permissions. Please chmod the simpleforum.conf file (located in simpleforum_files) to 777 or whatever fits for your webserver's configuration. If this error keeps appearing, delete the simpleforum.conf file. Note that this will delete your former simpleforum settings. You can keep a copy of the simpleforum.conf file and open it with a texteditor to see the old values of your configuration.<br><br><a href='javascript:history.go(-1)'>Back</a></body></html>"; exit; }
			}
			print <<HTML;
			<b>Step 2 - The Administrator Account</b>
			<br><i>This account will have the ability to configure and manage everything that is going on on your forum. You can assign multiple administrators later in the forum configuration, only one is required now.

			The password must be at least 4 characters long and may contain only alphanumeric characters! Write your password down somewhere safe because it <b>cannot</b> be recovered when lost!

			<br><br>Password examples:	<ul><li>abc123</li>
								<li>mypassword</li>
							</ul></i>

			<form method='post' action='$script_name?installation'>
			<table border='0'>
				<tr><td><font face='verdana' size='2'>Account Name:</font></td><td><input type='text' name='admin_account'></td></tr>
				<tr><td><font face='verdana' size='2'>Password:</font></td><td><input type='password' name='admin_password1'></td></tr>
				<tr><td><font face='verdana' size='2'>Confirm:</font></td><td><input type='password' name='admin_password2'></td></tr>
				<tr><td colspan='2'><br><input type='submit' value='Continue'></td></tr>
			</table>
			<input type='hidden' name='simpleforum_dir' value='$simpleforum_dir'>
			<input type='hidden' name='step1' value='1'>
			<input type='hidden' name='step2' value='1'>
			</form>
HTML
		}
	} else { # step 1
		print <<HTML;
		<b>Step 1 - The SimpleForum Files directory</b>
		<br><i>This directory, called "simpleforum_files", is the directory where SimpleForum will save all its data in.
		The simpleforum_files directory came with the download and should be placed in the same directory you put $script_name and the permissions for this directory should be set to 777 (or whatever fits for your webserver's configuration).
		<br><br>If you have done this, click "Continue" and the script will test if the location is correct and if the permissions for this directory are set correctly.</i>
		<form method='post' action='$script_name?installation'>
		<input type='hidden' name='step1' value='1'>
		<br><input type='submit' value='Continue'></form>
HTML
	}
	print <<HTML;
	</div>
	</body>
	</HTML>
HTML
exit;
}


sub start {
	#Don't edit anything here!
	#standard operations

$qs = $ENV{'QUERY_STRING'};
$password = encrypt(param('password'));
$version = "4.0";
$script_name = $ENV{'SCRIPT_FILENAME'};
$script_name =~ s/^(.*)\/(.*?)$/$2/s;

if (-e "$simpleforum_dir/simpleforum.conf") {
	open CONF, "$simpleforum_dir/simpleforum.conf" or dienice("Couldn't open simpleforum.conf for reading: $!");
		while (<CONF>) {
			if (/admin_account:(.*?)\n/) { $admin_account = $1; }
		}
	close CONF;
} else {
	&installation;
}

if (!$admin_account or ($qs eq "installation" and !$admin_account)) { &installation; exit; }

&last_visit;

	if (!$simpleforum_dir) { $error .= "<i>the SimpleForum Files Directory is not set.</i><br>To do this, open $script_name in a texteditor and follow the instructions written there.<br><br>"; }
	if ($error) { print header."<html><head><title>Error</title></head><body><b>Error - You got the forum running... BUT:</b><br><br>$error</body></html>"; exit;}

#if the simpleforum_dir does not exist
if (!-e $simpleforum_dir) { print header."<i>Could not locate the SimpleForum Files directory: $!</i>\n<br><br>This directory, called simpleforum_files (default), came with the $script_name script and should be placed in the same directory where you put $script_name. Set its permissions to 777 (chmod 777 $simpleforum_dir). This means that user, group and everyone must have read/write/execute access for the simpleforum-directory ($simpleforum_dir)<br><br>If you have done this, and it's still not working, check if your \$simpleforum_dir variable is set correctly in $script_name.<br>(Default) Example: \$simpleforum_dir = \"simpleforum_files\";<br><br>"; exit; }

	#default settings: do not edit these. They can all be edited from the admin area (on the forum in your browser)
	#in case the conf file has not been created yet, these settings will apply to the forum
	$images_dir = "$simpleforum_dir/images"; #images directory
	$title = "SimpleForum $version"; #Title of your forum (example: John's Forum)
	$subtitle = "W e l c o m e !"; #Subtitle that appears below the Title (see above) on the forum index
	$home_name = "Home"; #Title of your homepage
	$home_url = "http://simpleforum.go.dyndns.org"; #URL for your homepage
	$hour_difference = 0; #If the server time is different from your local time. Can be a negative number as well. Expressed in hours. (example: 1, this will set the hour difference to +1 HOUR)
	$hoursystem = "12"; #12 or 24 (12 will add AM and PM behind in hour notation)
	$date_notation = "ddmmyy"; #Date notation: mmddyy (MM/DD/YY) or ddmmyy (DD/MM/YY)
	$html_protection = "on"; #disable html in posts [on/off]
	$bbcode = "on"; #allow bbcode [on/off]
	$smileys = "on"; #add smileys
	$author_edit = "on"; #allow the other to edit his post or not
	$backgroundcolor = "#FFFFFF"; #The background color of the forum
	$backgroundimage = "$images_dir/background.gif"; #If you want an image for background, specify the URL to the image (e.g. "http://www.domain.com/path/to/image.jpg")
	$menu_display = "text"; #Display the menu as text or images
	$tablecolor1 = "#E9E6E6"; #Table backgroundcolor 1
	$tablecolor2 = "#D8D7D7"; #Table backgroundcolor 2
	$tablecolor3 = "#F8F7F7"; #Table backgroundcolor 3
	$tablebordercolor = "navy";
	$tablewidth = "93%"; #Table width
	$postformbackground = "#E9E6E6"; #Table background color for the post/reply form
	$fontface = "verdana,arial"; #The font you want to use for your forum, note that the visitor must have the font installed on his computer. By adding a "," you can add a secondary font in case the visitor has not got the font installed (e.g. "arial, verdana"). Empty field will apply the standard font.
	$fontsize = "9"; #The size of the font in general, this does not count for headers and such (example: 12, this will make the font size 12pt)
	$fontsizesmall = "8"; #The font size of comments, less important text, ...
	$fontcolor = "#555555"; #Will change the color for most text on your forum
	$topics_per_page = 10; #Amount of topics shown in topic index
	$posts_per_page = 20; #Amount of replies shown in a topic
	$popularnumb = 15; #Amount of replies required to make a topic "Popular"
	$link_color = "#6685CC"; #color of hyperlinks
	$visited_link_color = "#6685CC"; #color of visited hyperlinks
	$link_hover_color = "#CC6666"; #color when hovering mouse over hyperlinks
	$language = "English"; #forum language
	$mail = "on"; #activates the mail function of the forum. However, the sendmail program must be operational and the path to sendmail must be set correctly.
	$mailprog = '/usr/sbin/sendmail'; #mail program, standard set to unix sendmail.
	$show_email_addresses = "off"; #Show/Hide user's email addresses on the forum
	$allow_attachments = "yes"; #attachments feature on/off
	$attachments_dir = "$simpleforum_dir/attachments";
	$attachments_uploadmax = "5120000"; #5 megabites max filesize for uploaded attachments
	$guest_access = "read-only"; #allow guest access on your forum [on/read-only/off]
	$title_lvl1 = "Level 1 User";
	$title_lvl2 = "Level 2 User";
	$title_lvl3 = "Level 3 User";
	$title_lvl4 = "Level 4 User";
	$title_lvl5 = "Level 5 User";
	$title_lvl6 = "Level 6 User";
	$title_lvl1_posts = "0";
	$title_lvl2_posts = "64";
	$title_lvl3_posts = "128";
	$title_lvl4_posts = "256";
	$title_lvl5_posts = "512";
	$title_lvl6_posts = "1024";
	$enable_user_titles = "on";
	$enable_private_messages = "on";
	$enable_guest_registration = "on";

#in case the conf file exists, get and modify the standard variables
open CONF, "$simpleforum_dir/simpleforum.conf" or dienice("Couldn't open simpleforum.conf for reading: $!");
	while (<CONF>) {
		chomp;
		if (/^(.*?):(.*?)$/) { $$1 = $2; }
	}
close CONF;

# define the font classes so that in the script we can use <$standardfont>,<$smallfont> and <$bigfont>
$bigsize = $fontsize + 1;
$standardfont = "font class='standardfont'";
$smallfont = "font class='smallfont'";
$bigfont = "font class='bigfont'";

if (!$images_dir) { $images_dir = "$simpleforum_dir/images"; } else { $images_dir =~ s/\/$//s; }
if (!$attachments_dir) { $attachments_dir = "$simpleforum_dir/attachments"; } else { $attachments_dir =~ s/\/$//s; }
if (!$attachments_url) { $attachments_url = $attachments_dir; }

# assign users directory location and create it if necessary
$users_dir = "$simpleforum_dir/users";
if (!-e $users_dir) {mkdir($users_dir,0777) or dienice("Couldn't create the users directory: $!<br><br>Please contact the forum admin");}

$smileys_dir = "$images_dir/smileys";
$script_dir = url(-absolute=>1);
$script_dir =~ s/(.*)\/(.*?)$/$1\//;

if (!-e "$simpleforum_dir/languages/$language.pm") { print header."<i>The language module ($language.pm) is not installed!</i><br><br>Place this module that came with the official distribution of SimpleFroum in \"$simpleforum_dir/languages/\""; exit; }
require "$simpleforum_dir/languages/$language.pm";
&set_language_vars;
#check if the language files are updated
if (!$lang_page) { dienice("<i>You haven't got the latest version of the language files installed. Please read the \"upgrade_readme.txt\" file that came with the download for more info.</i>"); }

#Check banned IP's
&ipcheck;

#Get the current forum's info
if ($qs =~ /fid=(\d*)/) {
	$forum_id = $1;
	if ($forum_id) {
		$topic_dir = "$simpleforum_dir/forum_$forum_id";
		open(INFO, "< $topic_dir/forum.info") or dienice("Failed to open forum.info (fid=$forum_id): $!<br><br>Could this be because you just deleted the requested forum?<br><br><a href='$script_name'>Back</a>");
			$forum_info = join '', <INFO>;
		close INFO;
		if ($forum_info =~ /<forum_name>(.*?)<\/forum_name>/s) { $forum_name = add_html($1); }
		if ($forum_info =~ /<forum_more>(.*?)<\/forum_more>/s) { $forum_more = add_html($1); }
		if ($forum_info =~ /<forum_pass>(.*?)<\/forum_pass>/s) { $forum_pass = $1; }
		if ($forum_info =~ /<forum_mods>(.*?)<\/forum_mods>/s) { $forum_mods = $1; }
		$frm_lnk = " &raquo; <a href='$script_name?fid=$forum_id'>$forum_name</a>";
	}
}

#Check forum password
if (!&forumpassword_check) { exit; }

	#get user information from profile OR if not logged in, get the remembered user name and email address
	$cookie = cookie('sfusr');
	if ($cookie =~ /^(.*?)\|(.*?)$/s) {
		$cookie_user = $1;
		$cookie_password = $2;
		if (-e "$users_dir/$cookie_user\.prf") {
			$user = $cookie_user; $logged_in = 1;
			open(USER_PROFILE, "< $users_dir/$cookie_user\.prf") or dienice("Couldn't open profile: $!");
				flock USER_PROFILE, 2;
				@user_profile_content = <USER_PROFILE>;
				$user_profile_content = join '', @user_profile_content;
			close USER_PROFILE;
			if ($user_profile_content =~ /<user_password>(.*?)<\/user_password>\n/s) {
				$user_password = $1;
				if ($cookie_password eq $user_password) {
					foreach $line (@user_profile_content) {
						chomp $line;
						if ($line =~ /^<(user_.*?)>(.*?)<\/(user_.*?)>$/) {
							# a single-line variable
							$$1 = $2;
						} elsif ($line =~ /^<(user_.*?)>(.*?)$/) {
							# a multi-line variable
							$var = $1;
							if ($user_profile_content =~ /<$var>(.*?)<\/$var>\n/s) {
								$$var = $1;
							}
						}
					}
				} else {
					$user = "guest";
					$cookie_name = "";
					$cookie_email = $cookie_password;
					$logged_in = "";
				}
			}
		} else {
			$user = "guest";
			$cookie_name = $1;
			$cookie_email = $2;
		}
	} else {
		$user = "guest";
	}

	#access for guests denied when $guest_access eq "off"
	if ($guest_access eq "off" and $user eq "guest" and $qs ne "register" and $qs !~ /^login(.*?)$/) {
		&page_start;
		print "<center><b>Welcome to $title!</b><br><br>";
		print "This Forum does not allow for unregistered users to be used.<br>Please <a href='$script_name?login&ref=$qs_referer'>$lang_log_in</a> or <a href='$script_name?register'>$lang_register</a> in order to gain access to this Forum.<br><br>\n";
&login;
		&page_end;
		exit;
	}

	# check if the user is an administrator
	@admin_accounts = split(/\|/, $admin_account);
	foreach $admin_account(@admin_accounts) {
		if ($admin_account eq $user or $admin_account eq "unknown_admin") { $admin_access = 1; }
	}

	# check if the user is a forum moderator
	@forum_moderators = split(/\|/, $forum_mods);
	foreach $forum_moderator(@forum_moderators) {
		if ($forum_moderator eq $user) { $moderator_access = 1; }
	}

	# add this user to the currently online list
	&currently_online;

	# if this is a registered user: see whether the IP has changed.
	# if the IP has changed, add it to the list of his IP's
	if ($logged_in) {
		while ($user_ip =~ /(\d*?\.\d*?\.\d*?\.\d*?)\|/sg and !$matching_ip) {
			if ($ENV{'REMOTE_ADDR'} eq $1) { $matching_ip = 1; }
		}
		if (!$matching_ip) {
			# add the ip to the list
			$new_ip = $ENV{'REMOTE_ADDR'};
			open (PRF, "+>> $users_dir/$user\.prf") or dienice("couldn't open $user\.prf");
				flock PRF, 2;
				seek PRF, 0, 0;
				$profile_text = join '', <PRF>;
				seek PRF, 0, 0;
				truncate PRF, 0;
				$profile_text =~ s/<user_ip>(.*?)<\/user_ip>\n/<user_ip>\|$new_ip$1<\/user_ip>\n/s;
				print PRF $profile_text;
			close PRF;
		}
	}

	# check for new private messages
	if ($user_pmsg_popped eq "no" and $logged_in) {
		# there's a new message!
		$onload = "onLoad=\"if (confirm('You have received a new Private Message.\\n\\nWould you like to see it now?') == true) { location='$script_name?fid=$forum_id&pmsg=1'; }\"";
		open(PRF, "> $users_dir/$user.prf") or dienice("Could not open user profile");
		flock PRF, 2;
		# we already got the file's contents from parsing its values, so we print them again here, yet modified ($user_pmsg_popped = "yes")
		$user_profile_content =~ s/<user_pmsg_popped>no<\/user_pmsg_popped>\n/<user_pmsg_popped>yes<\/user_pmsg_popped>\n/s;
		print PRF $user_profile_content;
		close PRF;
	}
}


sub date_time {
#Don't edit anything here, unless you know what you're doing.
my($date_time) = @_;
   ($sec,$min,$hour,$mday,$mon,$year,$day,$yday,$isdst) = localtime($date_time + ($hour_difference *3600));

   if ($sec < 10) { $sec = "0$sec"; }
   if ($min < 10) { $min = "0$min"; }
   if ($hour < 10) { $hour = "0$hour"; }
   if ($mon < 10) { $mon = "0$mon"; }
   if ($mday < 10) { $mday = "0$mday"; }

   $mon++;

   if (!@months or !@months_short or !@days) {
		dienice("Incomplete language file!");
	}

	if ($hoursystem eq "12") {
		if ($hour > 11) {
			if ($hour > 12) {
				$hour = $hour - 12;
			}
			$ampm = " PM";
		} else {
			$ampm = " AM";
		}
	}

   $year += 1900;
   $full_date = "$days[$day] $mday $months[$mon] $year @ $hour:$min:$sec";
   $long_date = "$months[$mon] $mday, $year at $hour\:$min\:$sec";
   $date = "$mday $months_short[$mon] $year";

   $year %= 100;
   if ($year < 10) { $year = "0$year"; };

   	if ($date_notation eq "mmddyy") {
   		$short_date = "$mon/$mday/$year";
   	} else {
   		$short_date = "$mday/$mon/$year";
   	}


}


sub page_end {
#Credits are to be left untouched!! For the up to date "terms of use", see http://simpleforum.go.dyndns.org.
#feel free to *add* some text, just make sure that you leave a link to the simpleforum site
	if (!$footer_printed) {
		print "<br><center><div style='width:$tablewidth;' align='center'><a href='javascript:window_open(\"http://simpleforum.go.dyndns.org/index2.html\", 780,680);'><$smallfont>Powered by <i>SimpleForum Pro $version</i></a></div></center><\/body>\n\n<\/HTML>";
		$footer_printed = 1;
	}
}


sub write_to_topic {
	#after submitting and verifying a message, write it to the appropriate topic file
	$time = time;
	$signature = &random_signature; # get a random signature if available

	if (!$topic_id) { # if this is a new topic
		$topic_id = $time;
		edit_statistics_file("tpc_amount++");
	}

	if ($logged_in) { # set the status of the sender
		$status = "registered";
	} else {
		$status = "guest";
	}


	#open topic for writing and write the reply data
	open(TOPIC,"+>> $topic_dir/$topic_id.topic") or dienice("Couldn't open $topic_dir/$topic_id.topic:<br>$!<br><br>Make sure that you set the permissions for the directory \"$topic_dir\" to 777, as described in the readme!");
	flock TOPIC, 2;
	print TOPIC
	#The following is NOT HTML, don't touch!
<<TOPIC_CONTENT;
<post>
<name>$name</name>
<status>$status</status>
<ip>$ENV{'REMOTE_ADDR'}</ip>
<email>$email</email>
<subject>$subject</subject>
<time>$time</time>
<message>$message\n</message>
<signature>$signature<\/signature>
</post>

TOPIC_CONTENT
	close TOPIC;
	if (!$logged_in) {
		$cookie = cookie(-name => 'sfusr',
						 -value => "$name\|$email",
						 -expires => '+365d');
		print "Set-Cookie: $cookie\n";
	}
	edit_statistics_file("msg_amount++");

	# update the profile (user_posts)
	if ($logged_in) {
		open(PROFILE, "+>> $users_dir/$user\.prf") or dienice("Your message has been sent, but the script could not update your profile: $!");
			flock PROFILE, 2;
			seek PROFILE, 0, 0;
			$profile_content = join '', <PROFILE>;
			if ($profile_content =~ /<user_posts>(\d*?)<\/user_posts>\n/s) {
				$user_posts = $1 + 1;
				$profile_content =~ s/<user_posts>(\d*?)<\/user_posts>\n/<user_posts>$user_posts<\/user_posts>\n/s;
			}
			seek PROFILE, 0, 0;
			truncate PROFILE, 0;
			print PROFILE $profile_content;
		close PROFILE;
	}

	# Notify the administrator of this new post if the option is enabled
	if ($admin_email and $admin_email_notify eq "on") { &admin_email_notify; }

	# Send an email-reply if selected by sender
	if (param('send_mail') and $mail = "on") { mail_post('email_reply'); }

	# Subscribe to this post if selected by sender
	if (param('subscribe') and $mail = "on") {
		open(TOPIC,"+>> $topic_dir/$topic_id.topic");
		flock TOPIC, 2;
		seek TOPIC, 0, 0;
		$topic_content = join '', <TOPIC>;
		seek TOPIC, 0, 0;
		while (<TOPIC>) {
			if (/<subscribe>(.*?)<\/subscribe>\n/) {
				$subscribe_tags_exist = 1;
				$subscribed_users = $1."\|$user";
				$topic_content =~ s/<subscribe>(.*?)<\/subscribe>\n/<subscribe>$subscribed_users<\/subscribe>\n/s;
			}
		}
		seek TOPIC, 0, 0;
		truncate TOPIC, 0;
		if (!$subscribe_tags_exist) { # if the subscribe tags do not exist we must place them
			print TOPIC "<subscribe>$user</subscribe>\n\n".$topic_content;
			$subscribed_users = $user;
		} else { # everything has been done above, just print the new data to the topic file
			seek TOPIC, 0, 0;
			truncate TOPIC, 0;
			print TOPIC $topic_content;
		}
		close TOPIC;
	}

	# Send mails to subscribed users
	if ($mail = "on") {
		if (!$subscribed_users) { # get the subscribed users if we haven't already got them from above
			open (TOPIC, "< $topic_dir/$topic_id.topic") or dienice("Couldn't open the topic for reading");
			while (<TOPIC>) {
				if (/<subscribe>(.*?)<\/subscribe>\n/) {
					$subscribed_users = $1;
					$stop_topic_scan2 = 1;
				}
			}
			close TOPIC;
		}

		if ($subscribed_users) { # if at all anyone is subscribed, get the email addresses
			@subscribed_users = split(/\|/, $subscribed_users);
			foreach $subscribed_user(@subscribed_users) {
				# get email address
				$subscribed_user_email = undef;
				open(PRF,"$users_dir/$subscribed_user.prf");
				while (<PRF>) {
					if (/<user_email>(.*?)<\/user_email>\n/) {
						$subscribed_user_email = $1;
					}
				}
				close PRF;

				# send the email
				if ($subscribed_user_email and $subscribed_user ne $user) {
					mail_post('subscribe');
				}
			}
		}
	}
}


sub admin_email_notify {
	if ($mail ne "on") { return; } #for more security - don't execute this if the mail function isn't on
	if (!$email) { $nomail = "no email address given"; }
	$topic_url = param('topic_url');
	$orig_message = param('message');
	$subj = $subject;
	if ($orig_message =~ /\[quoted\]..(.*?)\n\[\/quoted\]/s) {
		$rquote = $1;
		$rquote =~ s/\n/\n\>/sg;
		$orig_message =~ s/\[quoted\](.*?)\[\/quoted\]/\> $rquote/s;
	}
	open (MAIL, "|$mailprog -t") or dienice("Can't access $mailprog! Please make sure your mailprogram is installed and that the path to your mailprogram is set correctly.\n<br>The server returned this error: $!\n<br><br>If the error is something like \"No such file or directory\" this means the path to your mailprog is incorrect. The administrator can set this path in Administrator area > Forum Configuration");
	print MAIL "From: $admin_email ($title)\n";
	print MAIL "To: $admin_email\n";
	print MAIL "Reply-to: $from\n";
	print MAIL "Subject: New Forum Message!\n\n";

	print MAIL <<MailContent;
SimpleForum Administrator

A new message has been posted to your forum at $home_url

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Name: $name
Subject: $subject

$orig_message
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

Read the full topic here:
$topic_url

You are receiving this email because you have activated the Administrator Email Notification function in the forum. You can turn this off in the Forum Configuration.
MailContent
	close(MAIL);
}


sub mail_post {
	my($type) = @_;
	if ($mail ne "on") { return; } #for more security - don't execute this if the mail function isn't on

	if ($type eq "email_reply") { # Type: Email Reply
		if (!$email) { $nomail = "no email address given"; }
		$topic_url = param('topic_url');
		$orig_message = param('message');
		$recipient = param('send_mail_email');
		$from = "$email ($name)";
		$subj = param('send_mail_subject');
		if ($orig_message =~ /\[quoted\]..(.*?)\n\[\/quoted\]/s) {
			$rquote = $1;
			$rquote =~ s/\n/\n\>/sg;
			$orig_message =~ s/\[quoted\](.*?)\[\/quoted\]/\> $rquote/s;
		}
		open (MAIL, "|$mailprog -t") or dienice("Can't access $mailprog! Please make sure your mailprogram is installed and that the path to your mailprogram is set correctly.\n<br>The server returned this error: $!\n<br><br>If the error is something like \"No such file or directory\" this means the path to your mailprog is incorrect. The administrator can set this path in Administrator area > Forum Configuration");
		print MAIL "From: $from\n";
		print MAIL "To: $recipient\n";
		print MAIL "Reply-to: $from\n";
		print MAIL "Subject: $subj\n\n";

		print MAIL <<MailContent;
This is an email reply from $name ($email$nomail) to your post on the the $title forum at $home_url

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subject: $subject

$orig_message
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

A copy of this message was also posted to the forum, read the full topic here:
$topic_url
MailContent

		close(MAIL);
	} elsif ($type eq "subscribe" and $subscribed_user_email) { # Type: Email subscriptions to topic
		$topic_url = param('topic_url');
		$orig_message = param('message');
		$recipient = $subscribed_user_email;
		$from = "$subscribed_user_email ($title)";
		$subj = param('subject');
		open (MAIL, "|$mailprog -t") or dienice("Can't access $mailprog! Please make sure your mailprogram is installed and that the path to your mailprogram is set correctly.\n<br>The server returned this error: $!\n<br><br>If the error is something like \"No such file or directory\" this means the path to your mailprog is incorrect. The administrator can set this path in Administrator area > Forum Configuration");
		print MAIL "From: $from\n";
		print MAIL "To: $recipient\n";
		print MAIL "Reply-to: $from\n";
		print MAIL "Subject: $subj\n\n";

		print MAIL <<MailContent;
Greetings

This is an automatic email sent to you by the forum "$title" at $home_url.
$name has posted a reply on a topic to which you are subscribed.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subject: $subject

$orig_message
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

A copy of this message was also posted to the forum, read the full topic here:
$topic_url

[ To unsubscribe follow this link: (not yet implemented) ]
MailContent
		close(MAIL);
	}
}


sub add_html {
	my($add_html) = @_;

	if ($html_protection eq "on") {
		#HTML protection
		$add_html =~ s/\</&lt;/sg;
		$add_html =~ s/\>/&gt;/sg;
	}

	#smileys
	# hide smileys from http conversion
	$smileys_dir =~ s|http://|smiley://|sg;
	if ($smileys eq "on") {
		$add_html =~ s~\&gt\;:\((\W)~<img src='$smileys_dir/angry.gif' border='0'>$1~sg;
		$add_html =~ s~\>:\((\W)~<img src='$smileys_dir/angry.gif' border='0'>$1~sg;
		$add_html =~ s~8\|(\W)~<img src='$smileys_dir/blink.gif' border='0'>$1~sg;
		$add_html =~ s~o\.O(\W)~<img src='$smileys_dir/blink.gif' border='0'>$1~sg;
		$add_html =~ s~\:blush\:(\W)~<img src='$smileys_dir/blushing.gif' border='0'>$1~sg;
		$add_html =~ s~8\)(\W)~<img src='$smileys_dir/cool.gif' border='0'>$1~sg;
		$add_html =~ s~\:\'\((\W)~<img src='$smileys_dir/crying.gif' border='0'>$1~sg;
		$add_html =~ s~\:cry\:(\W)~<img src='$smileys_dir/crying.gif' border='0'>$1~sg;
		$add_html =~ s~\&gt\;\:\)(\W)~<img src='$smileys_dir/devil.gif' border='0'>$1~sg;
		$add_html =~ s~\>\:\)(\W)~<img src='$smileys_dir/devil.gif' border='0'>$1~sg;
		$add_html =~ s~\:dizzy\:(\W)~<img src='$smileys_dir/dizzy.gif' border='0'>$1~sg;
		$add_html =~ s~\:erm\:(\W)~<img src='$smileys_dir/ermm.gif' border='0'>$1~sg;
		$add_html =~ s~L\.L(\W)~<img src='$smileys_dir/getlost.gif' border='0'>$1~sg;
		$add_html =~ s~l\.l(\W)~<img src='$smileys_dir/getlost.gif' border='0'>$1~sg;
		$add_html =~ s~\:D(\W)~<img src='$smileys_dir/grin.gif' border='0'>$1~sg;
		$add_html =~ s~\^\.\^(\W)~<img src='$smileys_dir/happy.gif' border='0'>$1~sg;
		$add_html =~ s~\:laugh\:(\W)~<img src='$smileys_dir/laughing.gif' border='0'>$1~sg;
		$add_html =~ s~\:\|(\W)~<img src='$smileys_dir/noexpression.gif' border='0'>$1~sg;
		$add_html =~ s~\:geek\:(\W)~<img src='$smileys_dir/online2long.gif' border='0'>$1~sg;
		$add_html =~ s~\&gt\;\.\&lt\;(\W)~<img src='$smileys_dir/pinch.gif' border='0'>$1~sg;
		$add_html =~ s~\:\((\W)~<img src='$smileys_dir/sad.gif' border='0'>$1~sg;
		$add_html =~ s~\:o(\W)~<img src='$smileys_dir/shocked.gif' border='0'>$1~sg;
		$add_html =~ s~\:O(\W)~<img src='$smileys_dir/shocked.gif' border='0'>$1~sg;
		$add_html =~ s~\:x(\W)~<img src='$smileys_dir/sick.gif' border='0'>$1~sg;
		$add_html =~ s~\:X(\W)~<img src='$smileys_dir/sick.gif' border='0'>$1~sg;
		$add_html =~ s~\:zzz\:(\W)~<img src='$smileys_dir/sleeping.gif' border='0'>$1~sg;
		$add_html =~ s~\:\)(\W)~<img src='$smileys_dir/smile.gif' border='0'>$1~sg;
		$add_html =~ s~\:p(\W)~<img src='$smileys_dir/tongue.gif' border='0'>$1~sg;
		$add_html =~ s~\:P(\W)~<img src='$smileys_dir/tongue.gif' border='0'>$1~sg;
		$add_html =~ s~\:S(\W)~<img src='$smileys_dir/unsure.gif' border='0'>$1~sg;
		$add_html =~ s~\:s(\W)~<img src='$smileys_dir/unsure.gif' border='0'>$1~sg;
		$add_html =~ s~\:w00t\:(\W)~<img src='$smileys_dir/w00t.gif' border='0'>$1~sg;
		$add_html =~ s~\:\?(\W)~<img src='$smileys_dir/wassat.gif' border='0'>$1~sg;
		$add_html =~ s~\:whistle\:(\W)~<img src='$smileys_dir/whistling.gif' border='0'>$1~sg;
		$add_html =~ s~\;\)(\W)~<img src='$smileys_dir/wink.gif' border='0'>$1~sg;
	}

	#Reply quote
	$add_html =~ s~\[quoted\]..(.*?)\[/quoted\]~<table border=0 bgcolor='$tablecolor'><tr><td><$smallfont><i>$1</i></font></td></tr></table>~s;

	$add_html =~ s/\n/<br>\n/sg;

	# hide the [url] tag from the general conversion of http://
	$add_html =~ s|\[url=http://(.*?)\]|\[url=temp://$1\]|sg;

	#convert URLs to HTML hyperlinks \\ Disabled ending chars: <>'(),"
	$add_html =~ s/(http:\/\/(.*?))([\<\>\'\(\)\,\"\ \r\n])/\[url=$1\]$1\[\/url\]$3/g;

	# reactivate the [url] tag
	$add_html =~ s|\[url=temp://(.*?)\]|\[url=http://$1\]|sg;

	# reactivate the smiley
	$add_html =~ s|smiley://|http://|sg;
	$smileys_dir =~ s|smiley://|http://|sg;

	#convert Email addresses to HTML hyperlinks
	$add_html =~ s/([\w\-\.]+\@[\w\-\.]+\.[\w\-]+)/<a href='mailto:$1'>$1<\/a>/g;

		#bbcode
	if ($bbcode eq "on") {
		$add_html =~ s|\\\]|&#93;|sg; # escape bbcode by typing \]
		$add_html =~ s|\\\[|&#91;|sg; # escape bbcode by typing \[
		$add_html =~ s|\[quote\](.*?)\[\/quote\]|<i>Quote:\n\&laquo; $1 \&raquo;</i><br>|sg;
		$add_html =~ s|\[url://(.*?)\](.*?)\[\/url\]|<a href='http://$1' target='_blank'>$2</a>|sg;
		$add_html =~ s|\[url=(.*?)\](.*?)\[\/url\]|<a href='$1' target='_blank'>$2</a>|sg;
		$add_html =~ s|\[b\](.*?)\[/b\]|<b>$1</b>|sg;
		$add_html =~ s|\[u\](.*?)\[/u\]|<u>$1</u>|sg;
		$add_html =~ s|\[center\](.*?)\[/center\]|<div align='center'>$1</div>|sg;
		$add_html =~ s|\[justify\](.*?)\[/justify\]|<div align='justify'>$1</div>|sg;
		$add_html =~ s|\[right\](.*?)\[/right\]|<div align='right'>$1</div>|sg;
		$add_html =~ s|\[i\](.*?)\[/i\]|<i>$1</i>|sg;
		$add_html =~ s|\[color:(.*?)\](.*?)\[/color\]|<font color="$1">$2</font>|sg;
		$add_html =~ s|\[pre\](.*?)\[/pre\]|<pre>$1</pre>|sg;
		$add_html =~ s|\[code\](.*?)\[/code\]|<code>$1</code>|sg;
		$add_html =~ s|\[img://(.*?)\]|<img src='http://$1'>|sg;
		$add_html =~ s|\[img:(.*?)\]|<img src='$1'>|sg;
		for ($size=1;$size<7;$size++) {
			$add_html =~ s/\[h$size\]/<h$size>/sg;
			$add_html =~ s/\[\/h$size\]/<\/h$size>/sg;
		}
	}

	return $add_html;
}

sub open_dir {
	#open directories and put the filenames in @files
	$dir = join '', @_;
	opendir(DIR, $dir) or dienice("Couldn't open a directory: $dir: $!");
		@files = readdir DIR;
	closedir (DIR);
}


sub last_visit {
	#lets the script know when you last visited the forum, if cookies are enabled
	$newvisit = time;

	$raw_cookie = cookie('sflvisited');

	if ($raw_cookie =~ /^(\d*)\|(\d*)/s) {
		$lastvisit = $1;
		$oldvisit = $2;
	}

	if (($newvisit - $lastvisit) > 500 and $lastvisit) {
		$oldvisit = $lastvisit;
		$usr_count = 1;
	}

	#if the user first visits the forum (or when cookies are not enabled) we ignore the "New" posts
	if (!$lastvisit) {
		$oldvisit = $newvisit;
	}

	$cookie = cookie(-name => 'sflvisited',
					 -value => "$newvisit\|$oldvisit",
					 -expires => '+365d');

	# write the cookie
	if ($qs !~ /login/ and !$logged_in) { # do not write the cookie when logging in (in case the browser does not support double cookie-writing)
		print "Set-Cookie: $cookie\n";
	}

	if ($usr_count) { edit_statistics_file("usr_amount++"); } #forumvisits + 1
}


sub forumpassword_check {
	if (!$forum_pass or !$forum_id) { return 1; } #If there's no password set in config or forum_id is missing, we don't need to check any passwords...

	$cookie = cookie('sfpwd');
	@sfpwds = split(/\|/, $cookie);
	foreach $sfpwd(@sfpwds) {
		if ($sfpwd =~ /forum_$forum_id=(.*)/s) {
			$cookie_pass = $1;
		}
	}

	if (encrypt(param('forum_pass')) eq $forum_pass or $cookie_pass eq $forum_pass) {
		if (!$cookie_pass) { #let the cookies remember the password
			$cookie = cookie(-name => 'sfpwd',
					 -value => "$cookie\|forum_$forum_id=$forum_pass\|",
					 -expires => '+365d');
			print "Set-Cookie: $cookie\n";
		} elsif ($cookie_pass ne $forum_pass) { #after the password for a forum has been changed, we must change it in the cookies as well (if the user entered the new password correctly)
			$cookie = cookie('sfpwd');
			$cookie =~ s/forum_$forum_id=(.*?)\|/forum_$forum_id=$forum_pass\|/s;
			$cookie = cookie(-name => 'sfpwd',
					 -value => "$cookie",
					 -expires => '+365d');
			print "Set-Cookie: $cookie\n";
		}
		return 1; #password correct, move on
	} else {
		&page_start;
		print <<HTML;
		<center>
		<b>$forum_name</b><br>
		$lang_enter_password
		<br>
		<form method='post' action='$script_name?$qs'>
		<input type='password' name='forum_pass'>
		<br><input type='submit' value='$lang_proceed'><input type='button' value='$lang_back' onClick='javascript:history.go(-1)'>
		</form>
HTML
		&page_end;
		return undef;
	}
}


sub ipcheck {
	open (IPBAN, "+>> $simpleforum_dir/blocked_ips.conf") or return;
	flock IPBAN, 2;
	seek IPBAN, 0, 0;
	while (<IPBAN>) {
		if (/<ip>(.*?)<\/ip><expires>(.*?)<\/expires>/) {
			$banned_ips = $1; $ban_expires = $2;
			if ($ban_expires < time) {
				# expired ban
				seek IPBAN, 0, 0;
				$ipban_content = join '', <IPBAN>;
				$ipban_content =~ s/<ip>$banned_ips<\/ip><expires>$ban_expires<\/expires>\n//sg;
				seek IPBAN, 0, 0;
				truncate IPBAN, 0;
				print IPBABN $ipban_content;
			} else {
				while ($banned_ips =~ /(\d*?\.\d*?\.\d*?\.\d*?)\|/) {
					if ($ENV{'REMOTE_ADDR'} eq $1) {
						# This user has been banned!
						&page_start;
						print "<center>Access denied</center>";
						&page_end;
						exit;
					}
				}
			}
		}
	}
	close IBAN;
}


sub random_signature {
if ($user_sign1) { push @signatures, $user_sign1; }
if ($user_sign2) { push @signatures, $user_sign2; }
if ($user_sign3) { push @signatures, $user_sign3; }
if ($user_sign4) { push @signatures, $user_sign4; }
srand(time() ^ ($$ + ($$ << 15)) );
return $signatures[int(rand($#signatures+1))];
}


sub encrypt {
  my $ipas = shift (@_);
  $encpass = crypt ($ipas, SiMpLeFoRuM);
  return $encpass;
}


sub dienice {
#Makes the script abort on failure, showing the error
$err = join '', @_;
if (!$header_printed) { &page_start; }
print "<center><h3>Whoops!</h3>".$err."</center>";
&page_end;
exit;
}