###############################################################################
# Post.pl                                                                     #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2.2                                                  #
# Packaged:       June 5, 2008                                                #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2008 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$postplver = 'YaBB 2.2.2 $Revision: 1.142.2.28 $';
if ($action eq 'detailedversion') { return 1; }

&LoadLanguage('Post');
&LoadLanguage('Display');
&LoadLanguage('FA');
&LoadLanguage('UserSelect');
require "$sourcedir/Notify.pl";
require "$sourcedir/Palette.pl";
require "$sourcedir/Mailer.pl";
require "$sourcedir/SpamCheck.pl";
if ($iamguest && $gpvalid_en && ($enable_guestposting || $PMenableGuestButton|| $PMAlertButtonGuests)) {
	require "$sourcedir/Decoder.pl";
}
if (!$set_subjectMaxLength) { $set_subjectMaxLength = 50; }
&LoadCensorList;

sub Post {
	if ($iamguest && $enable_guestposting == 0) { &fatal_error("not_logged_in"); }
	if (!$iamadmin && !$iamgmod && !$iammod && $speedpostdetection && ${$uid.$username}{'spamcount'} >= $post_speed_count) {
		$detention_time = ${$uid.$username}{'spamtime'} + $spd_detention_time;
		if($date <= $detention_time){
			$detention_left = $detention_time - $date;
			&fatal_error("speedpostban");
		} else {
			${$uid.$username}{'spamcount'} = 0;
			&UserAccount($username,"update");
		}
	}
	if ($currentboard eq '' && !$iamguest) { &fatal_error("no_access"); }
	my ($filetype_info, $filesize_info);
	my ($subtitle, $x, $mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate, $msubject, $mattach, $mip, $mmessage, $mns, $quotestart, $notify);
	my $quotemsg = $INFO{'quote'};
	$threadid = $INFO{'num'};

	($mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate) = split(/\|/, $yyThreadLine);

	my $icanbypass;
	## only if bypass switched on
	if ($mstate =~ /l/i && $bypass_lock_perm)	{ $icanbypass = &checkUserLockBypass; }
	if ($action eq 'modalert') { $icanbypass = 1; }
	if ($mstate =~ /l/i && !$icanbypass) { &fatal_error('topic_locked'); }
	if ($mstate =~ /a/i && !$iamadmin && !$iamgmod) { &fatal_error('no_access'); }

	# Determine category
	$curcat = ${$uid.$currentboard}{'cat'};
	&BoardTotals("load", $currentboard);

	# Figure out the name of the category
	unless ($mloaded == 1) { require "$boardsdir/forum.master"; }
	($cat, $catperms) = split(/\|/, $catinfo{$curcat});
	&ToChars($cat);

	$pollthread = 0;
	$postthread = 0;
	$INFO{'title'} =~ tr/+/ /;

	if    ($INFO{'title'} eq 'CreatePoll') { $pollthread = 1; $t_title = $post_polltxt{'1a'}; }
	elsif ($INFO{'title'} eq 'AddPoll')    { $pollthread = 2; $t_title = $post_polltxt{'2a'}; }
	elsif ($INFO{'title'} eq 'PostReply')  { $postthread = 2; $t_title = $display_txt{'116'}; }
	else { $postthread = 1; $t_title = $post_txt{'33'}; }
	if ($FORM{'title'} eq 'PostReply')  { $postthread = 2;}
	if ($pollthread == 2 && $useraddpoll == 0) { &fatal_error("no_access"); }
	if ($postthread == 2 && $username ne "Guest") {
		$j           = 0;
		@tmprepliers = ();
		for ($i = 0; $i < @repliers; $i++) {
			chomp $repliers[$i];
			($reptime, $repuser, $isreplying) = split(/\|/, $repliers[$i]);
			$outtime = $date - $reptime;
			if ($outtime > 600) { next; }
			elsif ($repuser eq $username) { $tmprepliers[$j] = qq~$date|$repuser|1~; $isrep = 1; }
			else { $tmprepliers[$j] = qq~$reptime|$repuser|$isreplying~; }
			$j++;
		}
		if (!$isrep) {
			$thisreplier = qq~$date|$username|1~;
			push(@tmprepliers, $thisreplier);
		}
		@repliers = @tmprepliers;
		&MessageTotals("update", $curnum);
	}

	$name_field = $realname eq ''
	  ? qq~      <tr>
    <td class="windowbg" align="left" width="23%"><b>$post_txt{'68'}:</b></td>
    <td class="windowbg" align="left" width="77%"><input type="text" name="name" size="25" value="$FORM{'name'}" maxlength="25" tabindex="2" /></td>
      </tr>~
	  : qq~~;

	$email_field = $realemail eq ''
	  ? qq~      <tr>
    <td class="windowbg" width="23%"><b>$post_txt{'69'}:</b></td>
    <td class="windowbg" width="77%"><input type="text" name="email" size="25" value="$FORM{'email'}" maxlength="40" tabindex="3" /></td>
      </tr>~
	  : qq~~;

	if ($iamguest && $gpvalid_en) {
		&validation_code;
		$verification_field = $verification eq ''
		? qq~
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'1'}:</b></td>
				<td class="windowbg" width="77%">$showcheck<br /><span class="small">$floodtxt{'casewarning'}</span></td>
			</tr>
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'3'}:</b></td>
				<td class="windowbg" width="77%">
				<input type="text" maxlength="30" name="verification" id="verification" size="30" />
				</td>
			</tr>
		~
		: qq~~;
	}
	$sub = '';
	$settofield = 'subject';

	if ($threadid ne '') {
		fopen(FILE, "$datadir/$threadid.txt") || &fatal_error("cannot_open","$datadir/$threadid.txt", 1);
		@messages = <FILE>;
		fclose(FILE);
		if ($quotemsg ne '') {
			($msubject, $mname, $memail, $mdate, $musername, $micon, $mattach, $mip, $mmessage, $mns) = split(/\|/, $messages[$quotemsg]);
			$message = $mmessage;
			$message =~ s~<br>~\n~ig;
			$message =~ s~<br />~\n~g;
			$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;
			if (!$nestedquotes) {
				$message =~ s~\n{0,1}\[quote([^\]]*)\](.*?)\[/quote\]\n{0,1}~\n~isg;
				$message =~ s~\n*\[/*quote([^\]]*)\]\n*~~ig;
			}
			$mname ||= $musername || $post_txt{'470'};
			my $hidename = $musername;
			$hidename = $mname if $musername eq 'Guest';
			$hidename = &cloak($hidename) if $do_scramble_id;
			$quotestart = int($quotemsg / $maxmessagedisplay) * $maxmessagedisplay;
			my $maxlengthofquote = $MaxMessLen - length(qq~[quote author=$hidename link=$threadid/$quotestart#$quotemsg date=$mdate\]\[/quote\]\n~) - 3;
			my $mess_len = $message;
			&ToChars($mess_len);
			$mess_len =~ s/[\r\n ]//ig;
			$mess_len =~ s/&#\d{3,}?\;/X/ig;
			if (length $mess_len >= $maxlengthofquote) {
				&LoadLanguage('Error');
				&alertbox($error_txt{'quote_too_long'});
				$message = substr($message, 0, $maxlengthofquote) . '...';
			}
			undef $mess_len;
			$message    = qq~[quote author=$hidename link=$threadid/$quotestart#$quotemsg date=$mdate\]$message\[/quote\]\n~;
			$msubject =~ s/\bre:\s+//ig;
			$message = &Censor($message);
			if ($mns eq 'NS') { $nscheck = qq~ checked="checked"~; }
		} else {
			($msubject, $mname, $memail, $mdate, $musername, $micon, $mattach, $mip, $mmessage, $mns) = split(/\|/, $messages[0]);
			$msubject =~ s/\bre:\s+//ig;
		}
		$msubject = &Censor($msubject);
		$sub = "Re: $msubject";
		$settofield = 'message';
	}

	if ($postthread == 2) { $set_subjectMaxLength = $set_subjectMaxLength + 4; } ## this allows replies not to have truncated titles  ;)
	if ($ENV{'HTTP_USER_AGENT'} =~ /(MSIE) (\d)/) {
		if ($2 >= 7.0) { $iecopycheck = ''; } else { $iecopycheck = qq~ checked="checked"~; }
	}
	$submittxt   = "$post_txt{'105'}";
	$destination = "post2";
	$icon        = "xx";
	$is_preview  = 0;
	$post        = "post";
	$prevmain    = "";
	$preview     = "preview";
	$yytitle     = "$t_title";
	&Postpage;
	&doshowthread;
	&template;
	exit;
}

##  post message page
sub Postpage {
	my $extra;
	my ($filetype_info, $filesize_info, $extensions);
	$extensions = join(" ", @ext);
	$filetype_info = $checkext == 1 ? qq~$fatxt{'2'} $extensions~ : qq~$fatxt{'2'} $fatxt{'4'}~;
	$filesize_info = $limit != 0    ? qq~$fatxt{'3'} $limit KB~   : qq~$fatxt{'3'} $fatxt{'5'}~;
	$normalquot = $post_txt{'599'};
	$simpelquot = $post_txt{'601'};
	$simpelcode = $post_txt{'602'};
	$edittext   = $post_txt{'603'};
	if (!$fontsizemax) { $fontsizemax = 72; }
	if (!$fontsizemin) { $fontsizemin = 6; }

	if ($postid eq 'Poll')  { $sub = "$post_txt{'66a'}"; }

	$message =~ s~<\/~\&lt\;/~isg;
	&ToChars($message);
	&ToChars($sub);

	# this defines what the top area of the post box will look like: option 1 ) IM area
	# option 2) all other post areas
	#  im stuff now separate
	if ($postid ne 'Poll' && $destination ne 'modalert2' && $destination ne 'guestpm2') {
		$extra = qq~
      <tr>
        <td class="windowbg" width="23%"><b>$post_txt{'71'}:</b></td>
        <td width="77%" class="windowbg">
        <select name="icon" onchange="showimage(); updatTopic();">
         <option value="xx"$ic1>$post_txt{'281'}</option>
         <option value="thumbup"$ic2>$post_txt{'282'}</option>
         <option value="thumbdown"$ic3>$post_txt{'283'}</option>
         <option value="exclamation"$ic4>$post_txt{'284'}</option>
         <option value="question"$ic5>$post_txt{'285'}</option>
         <option value="lamp"$ic6>$post_txt{'286'}</option>
         <option value="smiley"$ic7>$post_txt{'287'}</option>
         <option value="angry"$ic8>$post_txt{'288'}</option>
         <option value="cheesy"$ic9>$post_txt{'289'}</option>
         <option value="grin"$ic10>$post_txt{'290'}</option>
         <option value="sad"$ic11>$post_txt{'291'}</option>
         <option value="wink"$ic12>$post_txt{'292'}</option>
        </select>
        <img src="$imagesdir/$icon.gif" name="icons" border="0" hspace="15" alt="" /></td>
      </tr>
	 	~;
		if ($realname eq '' && $threadid ne '') { $settofield = "name"; }
	}

	# this shows on every post page. regardless of where it is called from
	$yymain .= qq~


~;
	$notify    = "";
	$hasnotify = "";

	if ($pollthread && $iamguest) { $guest_vote = 1; }
	if ($pollthread == 2) {
		$settofield = "question";
	}
	# this defines if the notify on reply is shown or not.
	if ($iamguest || $destination eq "modalert2" ||$destination eq "guestpm2") {
		$notification = '';
	} else {
		$notify = qq~ checked="checked"~ if $FORM{'notify'} eq 'x';
		# check if you are already being notified and if so we check the checkbox.
		# if the mail file exists then we have to check it otherwise we continue on
		$notifytext = qq~$post_txt{'750'}~;
		if (-e "$datadir/$threadid.mail") {
			&ManageThreadNotify("load", $threadid);
			if (exists $thethread{$username}) {
				$notify    = qq~ checked="checked"~;
				$hasnotify = 1;
			}
			undef %thethread;
		}
		if (-e "$boardsdir/$currentboard.mail") {
			&ManageBoardNotify("load", $currentboard);
			if (exists $theboard{$username}) {
				($memlang, $memtype, $memview) = split(/\|/, $theboard{$username});
				if ($memtype == 2) {
					$notify     = qq~ disabled="disabled" checked="checked"~;
					$hasnotify  = 1;
					$notifytext = qq~$post_txt{'132'}~;
				}
			}
			undef %theboard;
		}

		if ($postid ne 'Poll') {
			$notification = qq~
	<tr>
		<td width="23%"><b>$post_txt{'131'}:</b></td>
		<td width="77%"><input type="checkbox" name="notify" value="x"$notify /> <span class="small">$notifytext</span></td>
	</tr>~;
		}
	}

	#add to favorites checkbox code
	$favoriteadd = '';
	if (!$iamguest && $currentboard ne $annboard && $destination ne 'modalert2') {
		$favoritetext = $post_txt{'notfav'};
		require "$sourcedir/Favorites.pl";
		$myfavorite = &IsFav($threadid, '', 1);
		if ($FORM{'favorite'}) {
			$favorite = qq~ checked="checked"~;
		}
		if (!$nofav) {
			$favorite = qq~ disabled="disabled" checked="checked"~;
			$favoritetext = $post_txt{'alreadyfav'};
			$hasfavorite = 1;
		} elsif ($nofav == 2){
			$favorite = qq~ disabled="disabled"~;
			$favoritetext = $post_txt{'maximumfav'};
		}
		$favoriteadd = qq~
	<tr>
		<td width="23%"><b>$post_txt{'favorite'}:</b></td>
		<td width="77%"><input type="checkbox" name="favorite" value="x"$favorite /> <span class="small">$favoritetext</span></td>
	</tr>~;
	}

	if (!$sub) { $subtitle = "<i>$post_txt{'33'}</i>"; }
	else { $subtitle = "<i>$sub</i>"; }
	# this is shown every post page except the IM area.
	if ($destination ne 'modalert2' && $destination ne 'guestpm2') {
		if ($threadid) {
			$threadlink = qq~<a href="$scripturl?num=$threadid" class="nav">$subtitle</a>~;
		} else {
			$threadlink = "$subtitle";
		}
		&ToChars($boardname);
		&ToChars($cat);
		$yynavigation = qq~&rsaquo; <a href="$scripturl?catselect=$catid" class="nav">$cat</a> &rsaquo; <a href="$scripturl?board=$currentboard" class="nav">$boardname</a> &rsaquo; $t_title ( $threadlink )~;
	} else {
		$yynavigation = qq~&rsaquo; $t_title~;
	}
	#this is the end of the upper area of the post page.
	$yymain .= qq~
<script language="JavaScript1.2" src="$postjspath" type="text/javascript"></script>
<script language="JavaScript1.2" type="text/javascript">
<!--
var postas = '$post';
var namefield = '$realname';
var mailfield = '$realemail';

function checkForm(theForm) {
	var isError = 0;
	var msgError = "$post_txt{'751'}\\n";
	if (navigator.appName == "Microsoft Internet Explorer" && document.getElementById('iecopy').checked == true) { theForm.message.createTextRange().execCommand("Copy"); }
	if (postas == "imsend" || postas == "imsend2") {
		if (theForm.toshow.options.length == 0 ) { msgError += "\\n - $post_txt{'752'}"; isError = 1; }
		else { selectNames(); }
	}
	else {
		if (namefield == "") {
			if (theForm.name.value == "" || theForm.name.value == "_" || theForm.name.value == " ") { msgError += "\\n - $post_txt{'75'}"; if(isError == 0) isError = 2; }
			if (theForm.name.value.length > 25)  { msgError += "\\n - $post_txt{'568'}"; if(isError == 0) isError = 2; }
		}
		if (mailfield == "") {
			if (theForm.email.value == "") { msgError += "\\n - $post_txt{'76'}"; if(isError == 0) isError = 3; }
			if (! checkMailaddr(theForm.email.value)) { msgError += "\\n - $post_txt{'500'}"; if(isError == 0) isError = 3; }
		}
	}
	if (theForm.subject.value == "") { msgError += "\\n - $post_txt{'77'}"; if(isError == 0) isError = 4; }
	if (theForm.message.value == "") { msgError += "\\n - $post_txt{'78'}"; if(isError == 0) isError = 5; }
	if(isError >= 1) {
		alert(msgError);
		if(isError == 1) imWin();
		else if(isError == 2) theForm.name.focus();
		else if(isError == 3) theForm.email.focus();
		else if(isError == 4) theForm.subject.focus();
		else if(isError == 5) theForm.message.focus();
		return false;
	}
	return true
}

//-->
</script>

~;

	# if this is an IM from the admin or to groups declare where it goes.
	if ($INFO{'adminim'} || $INFO{'action'} eq "imgroups") {
		$yymain .= qq~<form action="$scripturl?action=imgroups" method="post" name="postmodify" onsubmit="return submitproc()">~;
	} else {
		if ($curnum) { $thecurboard = qq~num=$curnum\;action=$destination~; }
		elsif ($destination eq "guestpm2") { $thecurboard = qq~action=$destination~; }
		else { $thecurboard = qq~board=$currentboard\;action=$destination~; }
		if (&AccessCheck($currentboard, 4) eq "granted" && $allowattach && ${$uid.$currentboard}{'attperms'} == 1) {
			$yymain .= qq~<form action="$scripturl?$thecurboard" method="post" name="postmodify" enctype="multipart/form-data" onsubmit="if(!checkForm(this)) {return false} else {return submitproc()}">~;
		} else {
			$yymain .= qq~<form action="$scripturl?$thecurboard" method="post" name="postmodify" enctype="application/x-www-form-urlencoded" onsubmit="if(!checkForm(this)) {return false} else {return submitproc()}">~;
		}
	}
	if ($postthread == 2) { $yymain .= qq~<input type="hidden" id="title" name="PostReply" value="title" />~; }
	# this declares the beginning of the UBBC section
	$yymain .= qq~

	<div class="bordercolor" style="padding: 1px; width: 100%; margin-left: auto; margin-right: auto;">
	<script language="JavaScript1.2" src="$ubbcjspath" type="text/javascript"></script>
	<script language="JavaScript1.2" type="text/javascript">
	<!--
	~;

	$moresmilieslist = '';
	$more_smilie_array = '';
	$i = 0;
	if ($showadded == 1) {
		while ($SmilieURL[$i]) {
			if ($SmilieURL[$i] =~ /\//i) { $tmpurl = $SmilieURL[$i]; }
			else { $tmpurl = qq~$imagesdir/$SmilieURL[$i]~; }
			$moresmilieslist .= qq~				document.write('<img src="$tmpurl" align="bottom" alt="$SmilieDescription[$i]" border="0" onclick="javascript: MoreSmilies($i);" style="cursor: pointer;" alt="" />$SmilieLinebreak[$i] ');\n~;
			$tmpcode = $SmilieCode[$i];
			$tmpcode =~ s/\&quot;/"+'"'+"/g;    #" Adding that because if not it screws up my syntax view'
			&FromHTML($tmpcode);
			$tmpcode =~ s/&#36;/\$/g;
			$tmpcode =~ s/&#64;/\@/g;
			$more_smilie_array .= qq~" $tmpcode", ~;
			$i++;
		}
	}

	if ($showsmdir == 1) {
		opendir(DIR, "$smiliesdir");
		@contents = readdir(DIR);
		closedir(DIR);
		foreach $line (sort { uc($a) cmp uc($b) } @contents) {
			($name, $extension) = split(/\./, $line);
			if ($extension =~ /gif/i || $extension =~ /jpg/i || $extension =~ /jpeg/i || $extension =~ /png/i) {
				if ($line !~ /banner/i) {
					$moresmilieslist .= qq~				document.write('<img src="$smiliesurl/$line" align="bottom" alt="$name" border="0" onclick="javascript: MoreSmilies($i);" style="cursor: hand;" alt="" />$SmilieLinebreak[$i] ');\n~;
					$more_smilie_array .= qq~" [smiley=$line]", ~;
					$i++;
				}
			}
		}
	}

	$more_smilie_array .= qq~""~;

$yymain .= qq~
	moresmiliecode = new Array($more_smilie_array)
	function MoreSmilies(i) {
		AddTxt=moresmiliecode[i];
		AddText(AddTxt);
	}
~;

	if ($smiliestyle == 1) { $smiliewinlink = qq~$scripturl?action=smilieput~; }
	else { $smiliewinlink = qq~$scripturl?action=smilieindex~; }

$yymain .= qq~
	function smiliewin() {
		window.open("$smiliewinlink", 'list', 'width=$winwidth, height=$winheight, scrollbars=yes');
	}
~;
	
if ($destination ne 'modalert2' && $destination ne 'guestpm2') {
$yymain .= qq~
	function showimage() {
		document.images.icons.src="$imagesdir/"+document.postmodify.icon.options[document.postmodify.icon.selectedIndex].value+".gif";
	}
~;
}

$yymain .= qq~
//-->
</script>
<input type="hidden" name="threadid" value="$threadid" />
<input type="hidden" name="postid" value="$postid" />
<input type="hidden" name="info" value="$idinfo" />
<input type="hidden" name="mename" value="$mename" />
<input type="hidden" name="post_entry_time" value="$date" />

<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
	<tr>
		<td class="titlebg" height="18" width="100%">
			<img src="$imagesdir/$icon.gif" name="icons2" border="0" alt="" /> $yytitle
		</td>
	</tr>
~;

	$iammod = 0;
	if (scalar keys %moderators > 0) {
		while ($_ = each(%moderators)) {
			if ($username eq $_) { $iammod = 1; }
		}
	}
	if (scalar keys %moderatorgroups > 0) {
		&LoadUser($username);
		while ($_ = each(%moderatorgroups)) {
			if (${$uid.$username}{'position'} eq $_) { $iammod = 1; }
			foreach $memberaddgroups (split(/\, /, ${$uid.$username}{'addgroups'})) {
				chomp $memberaddgroups;
				if ($memberaddgroups eq $_) { $iammod = 1; last; }
			}
		}
	}

	$template_viewers = "";
	$topviewers       = 0;

	if ($postthread == 2 && $showtopicrepliers && (($iamadmin || $iamgmod || $iammod) && $sessionvalid == 1)) {
		foreach $thisreplier (@repliers) {
			chomp $thisreplier;
			(undef, $mrepuser, $misreplying) = split(/\|/, $thisreplier);
			if ($misreplying) {
				&LoadUser($mrepuser);
				$template_viewers .= qq~$link{$mrepuser}, ~;
				$topviewers++;
			}
		}
		$template_viewers =~ s/\, \Z/\./;

		if ($template_viewers) {
			$yymain .= qq~
			<tr>
				<td class="windowbg" valign="middle" align="left">
					$display_txt{'646'} ($topviewers): $template_viewers
				</td>
			</tr>
			~;
		}
	}

$yymain .= qq~
</table>

<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
	~;

	if ($pollthread) {
		$maxpq          ||= 60;
		$maxpo          ||= 50;
		$maxpc          ||= 0;
		$numpolloptions ||= 8;
		$vote_limit     ||= 0;

		if ($guest_vote)   { $gvchecked = ' checked="checked"'; }
		if ($hide_results) { $hrchecked = ' checked="checked"'; }
		if ($multi_choice) { $mcchecked = ' checked="checked"'; }

		$yymain .= qq~
		<tr>
                <td width="23%" align="right" class="windowbg2"><b>$post_polltxt{'6'}:</b> &nbsp;</td>
                <td width="77%" align="left"  class="windowbg2">
			<input type="text" size="50" name="question" value="$poll_question" maxlength="$maxpq" />
			<input type="hidden" name="pollthread" value="$pollthread" />
		</td>
		</tr>~;

		for (my $i = 1; $i <= $numpolloptions; $i++) {
			$yymain .= qq~
                    <tr>
                      <td width="23%" align="right" class="windowbg2"> &nbsp; $post_polltxt{'7'} $i: &nbsp;</td>
                      <td width="77%" align="left" class="windowbg2"><input type="text" size="35" maxlength="$maxpo" name="option$i" value="$options[$i]" /></td>
                    </tr>~;
		}

		if ($maxpc > 0) {
			$yymain .= qq~
		<tr>
                <td valign=top class="windowbg2" width="23%"><b>$post_polltxt{'59'}:</b></td>
                <td class="windowbg2" width="77%"><textarea name="poll_comment" rows="3" cols="60" wrap="soft" onkeyup="if (document.postmodify.poll_comment.value.length > $maxpc) {document.postmodify.poll_comment.value = document.postmodify.poll_comment.value.substring(0,$maxpc)}">$poll_comment</textarea></td>
		</tr>~;
		}

		$yymain .= qq~
		<tr>
                <td width="23%" align="left"><b>$post_polltxt{'32'}</b></td>
                <td width="77%" align="left"><input type="checkbox" name="guest_vote" value="1"$gvchecked /> <span  class="small">$post_polltxt{'54'}</span></td>
              </tr><tr>
                <td width="23%" align="left"><b>$post_polltxt{'26'}</b></td>
                <td width="77%" align="left"><input type="checkbox" name="hide_results" value="1"$hrchecked /> <span  class="small">$post_polltxt{'55'}</span></td>
              </tr><tr>
                <td width="23%" align="left"><b>$post_polltxt{'58'}</b></td>
                <td width="77%" align="left"><input type="checkbox" name="multi_choice" value="1"$mcchecked /> <span  class="small">$post_polltxt{'56'}</span></td>
              </tr><tr>
                <td width="23%" align="left"><b>$post_polltxt{'60'}</b></td>
                <td width="77%" align="left"><input type="text" size="6" name="vote_limit" value="$vote_limit" /> <span  class="small">$post_polltxt{'61'}</span></td>
              </tr>
		~;
	}

	$yymain .= qq~
	<tr>
		<td width="23%" align="left" valign="top" class="windowbg"><b>$post_txt{'507'}</b></td>
		<td width="77%" class="windowbg">$prevmain</td>
	</tr>
	~ if $prevmain;

if($postid ne 'Poll') {
	$yymain .= qq~
	<tr>
		<td width="23%" class="windowbg" valign="top">
			<div id="SaveInfo" style="height:16px;">
			 <img name="prevwin" id="prevwin" src="$defaultimagesdir/cat_expand.gif" alt="$npf_txt{'01'}" border="0" style="cursor:pointer; cursor:hand;" onclick="enabPrev();" /> <b>$npf_txt{'04'}</b>
			</div>
		</td>
		<td width="77%" class="windowbg">
			<div id="savetable" class="bordercolor" style="padding:1px; width:100%; margin:auto; visibility:hidden;">
			<table border="0" width="100%" cellpadding="3" cellspacing="0" style="table-layout:fixed;">
			  <tr>
			    <td class="titlebg">
			     <div id="savetopic" style="height:0px; text-align:left; vertical-align:middle; font-weight:bold; overflow:auto;">&nbsp;</div>
			    </td>
			  </tr>
			  <tr>
			    <td class="windowbg2">
			     <div id="saveframe" class="message" style="height:0px; text-align:left; vertical-align:top; overflow:auto;">&nbsp;</div>
			    </td>
			  </tr>
			</table>
			</div>
		</td>
	</tr>
	~;

	$topicstatus_row = "";
	$stselect        = "";
	$lcselect        = "";
	$hdselect        = "";
	$threadclass     = 'thread';

	($mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate) = split(/\|/, $yyThreadLine);
	if($FORM{'topicstatus'}) { $thestatus = $FORM{'topicstatus'}; }
	else { $thestatus = $mstate; }
	if    ($mreplies >= $VeryHotTopic) { $threadclass = 'veryhotthread'; }
	elsif ($mreplies >= $HotTopic)     { $threadclass = 'hotthread'; }
	if($action ne "modalert")	{
		if ($thestatus =~ /s/) { $stselect = qq~selected="selected"~; }
		if ($thestatus =~ /l/) { $lcselect = qq~selected="selected"~; }
		if ($thestatus =~ /h/) { $hdselect = qq~selected="selected"~; }
		$hidestatus = "";

		if ($currentboard ne $annboard && (($iamadmin || $iamgmod || $iammod) && $sessionvalid == 1)) {
			$yymain .= qq~
			<tr>
				<td class="windowbg" align="left" valign="top" width="23%"><b>$post_txt{'34'}:</b></td>
				<td class="windowbg" align="left" valign="middle" width="77%">
					<select multiple="multiple" name="topicstatus" size="3" style="vertical-align: middle;" onchange="showtpstatus()">
					<option value="s" $stselect>$post_txt{'35'}</option>
					<option value="l" $lcselect>$post_txt{'36'}</option>
					<option value="h" $hdselect>$post_txt{'37'}</option>
					</select>
					<img src="$imagesdir/$threadclass.gif" name="thrstat" border="0" hspace="15" alt="" style="vertical-align: middle;" />
				</td>
			</tr>
			~;
		}
		else {
			$hidestatus = qq~<input type="hidden" value="$thestatus" name="topicstatus" />~;
		}
	}
	$yymain .= qq~
	$extra
	$name_field
	$email_field
	$verification_field
	<tr>
		<td align="left" class="windowbg2" width="23%">
			<b>$post_txt{'70'}:</b>
		</td>
		<td align="left" class="windowbg2" width="77%">
			<input type="text" name="subject" value="$sub" size="50" maxlength="$set_subjectMaxLength" tabindex="1" style="width: 437px;" onkeyup="updatTopic()" />
		</td>
	</tr>
	<tr>
		<td class="windowbg2" width="23%" align="left" valign="top">
			<b>$post_txt{'72'}:</b><br /><span class="small">$post_txt{'resizedescript'}</span>
		</td>
		<td rowspan="2" valign="middle" class="windowbg2" width="77%">
	  	~;
		if ($enable_ubbc && $showyabbcbutt) {

			require "$sourcedir/Palette.pl";
			$ubbcpalette .= &Palette("post");

			$yymain .= qq~
			<div style="float: left; width: 440px;">
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "WebTV Plus Receiver" && navigator.appVersion.charAt(0) >= 3) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer;'";
				document.write('<div style="width: 437px; float: left;">');
				document.write("<img src='$imagesdir/url.gif' onclick='hyperlink();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'257'}' title='$post_txt{'257'}' border='0' \/>");
				document.write("<img src='$imagesdir/ftp.gif' onclick='ftp();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'434'}' title='$post_txt{'434'}' border='0' \/>");
				document.write("<img src='$imagesdir/img.gif' onclick='image();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'435'}' title='$post_txt{'435'}' border='0' \/>");
				document.write("<img src='$imagesdir/email2.gif' onclick='emai1();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'258'}' title='$post_txt{'258'}' border='0' \/>");
				document.write("<img src='$imagesdir/media.gif' onclick='flash();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'433'}' title='$post_txt{'433'}' border='0' \/>");
				document.write("<img src='$imagesdir/table.gif' onclick='table();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'436'}' title='$post_txt{'436'}' border='0' \/>");
				document.write("<img src='$imagesdir/tr.gif' onclick='trow();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'449'}' title='$post_txt{'449'}' border='0' \/>");
				document.write("<img src='$imagesdir/td.gif' onclick='tcol();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'437'}' title='$post_txt{'437'}' border='0' \/>");
				document.write("<img src='$imagesdir/hr.gif' onclick='hr();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'531'}' title='$post_txt{'531'}' border='0' \/>");
				document.write("<img src='$imagesdir/tele.gif' onclick='teletype();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'440'}' title='$post_txt{'440'}' border='0' \/>");
				document.write("<img src='$imagesdir/code.gif' onclick='showcode();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'259'}' title='$post_txt{'259'}' border='0' \/>");
				document.write("<img src='$imagesdir/quote2.gif' onclick='quote();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'260'}' title='$post_txt{'260'}' border='0' \/>");
				document.write("<img src='$imagesdir/edit.gif' onclick='edit();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'603'}' title='$post_txt{'603'}' border='0' \/>");
				document.write("<img src='$imagesdir/sup.gif' onclick='superscript();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'447'}' title='$post_txt{'447'}' border='0' \/>");
				document.write("<img src='$imagesdir/sub.gif' onclick='subscript();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'448'}' title='$post_txt{'448'}' border='0' \/>");
				document.write("<img src='$imagesdir/list.gif' onclick='list();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'261'}' title='$post_txt{'261'}' border='0' />");
				document.write("<img src='$imagesdir/me.gif' onclick='me();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'604'}' title='$post_txt{'604'}' border='0' />");
				document.write("<img src='$imagesdir/move.gif' onclick='move();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'439'}' title='$post_txt{'439'}' border='0' \/>");
				document.write("<img src='$imagesdir/timestamp.gif' onclick='timestamp($date);' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'245'}' title='$post_txt{'245'}' border='0' \/><br />");
				document.write('</div>');
				document.write('<div style="width: 115px; float: left;">');
				document.write("<img src='$imagesdir/bold.gif' onclick='bold();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'253'}' title='$post_txt{'253'}' border='0' \/>");
				document.write("<img src='$imagesdir/italicize.gif' onclick='italicize();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'254'}' title='$post_txt{'254'}' border='0' \/>");
				document.write("<img src='$imagesdir/underline.gif' onclick='underline();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'255'}' title='$post_txt{'255'}' border='0' \/>");
				document.write("<img src='$imagesdir/strike.gif' onclick='strike();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'441'}' title='$post_txt{'441'}' border='0' \/>");
				document.write("<img src='$imagesdir/highlight.gif' onclick='highlight();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'246'}' title='$post_txt{'246'}' border='0' />");
				document.write('</div>');
				document.write('<div style="width: 139px; float: left; text-align: center;">');
				document.write('<select name="fontface" id="fontface" onchange="if(this.options[this.selectedIndex].value) fontfce(this.options[this.selectedIndex].value);" style="width: 90px; margin-top: 2px; margin-left: 2px; margin-right: 1px; font-size: 9px;">');
				document.write('<option value="">Verdana<\/option>');
				document.write('<option value="">\\-\\-\\-\\-\\-<\/option>');
				document.write('<option value="Microsoft Sans Serif" style="font-family: Microsoft Sans Serif">MS Sans Serif<\/option>');
				document.write('<option value="Verdana" style="font-family: Verdana" selected="selected">Verdana<\/option>');
				document.write('<option value="Arial" style="font-family: Arial">Arial<\/option>');
				document.write('<option value="Tahoma" style="font-family: Tahoma">Tahoma<\/option>');
				document.write('<option value="Lucida Sans" style="font-family: Lucida Sans">Lucida Sans<\/option>');
				document.write('<option value="Times New Roman" style="font-family: Times New Roman">Times New Roman<\/option>');
				document.write('<option value="Georgia" style="font-family: Georgia">Georgia<\/option>');
				document.write('<option value="Courier" style="font-family: Courier">Courier<\/option>');
				document.write('<option value="Courier New" style="font-family: Courier New">Courier New<\/option>');
				document.write('<option value="Bitstream Vera Sans Mono" style="font-family: Bitstream Vera Sans Mono">Bitstream<\/option>');
				document.write('<option value="Comic Sans MS" style="font-family: Comic Sans MS">Comic Sans MS<\/option>');
				document.write('<option value="Bradley Hand ITC" style="font-family: Bradley Hand ITC">Bradley Hand ITC<\/option>');
				document.write('<option value="Tempus Sans ITC" style="font-family: Tempus Sans ITC">Tempus Sans ITC<\/option>');
				document.write('<option value="Impact" style="font-family: Impact">Impact<\/option>');
				document.write('<option value="Papyrus" style="font-family: Papyrus">Papyrus<\/option>');
				document.write('</select>');
				var fntoptions = ["6", "7", "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "36", "48", "56", "72"]
				document.write('<select name="fontsize" id="fontsize" onchange="if(this.options[this.selectedIndex].value) fntsize(this.options[this.selectedIndex].value);" style="width: 39px; margin-top: 2px; margin-left: 1px; margin-right: 2px; font-size: 9px;">');
				document.write('<option value="">11<\/option>');
				document.write('<option value="">\\-\\-<\/option>');
				for(var i = 0; i < fntoptions.length; i++) {
					if(fntoptions[i] >= $fontsizemin && fntoptions[i] <= $fontsizemax) {
						if(fntoptions[i] == 11) document.write('<option value="11" selected="selected">11<\/option>');
						else document.write('<option value=' + fntoptions[i] + '>' + fntoptions[i] + '<\/option>');
					}
				}
				document.write('</select>');
				document.write('</div>');
			}
			//-->
			</script>
			$ubbcpalette
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if ((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "WebTV Plus Receiver" && navigator.appVersion.charAt(0) >= 3) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer; cursor: hand;'";
				document.write('<div style="width: 92px; float: left;">');
				document.write("<img src='$imagesdir/pre.gif' onclick='pre();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'444'}' title='$post_txt{'444'}' border='0' />");
				document.write("<img src='$imagesdir/left.gif' onclick='left();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'445'}' title='$post_txt{'445'}' border='0' />");
				document.write("<img src='$imagesdir/center.gif' onclick='center();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'256'}' title='$post_txt{'256'}' border='0' />");
				document.write("<img src='$imagesdir/right.gif' onclick='right();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'446'}' title='$post_txt{'446'}' border='0' />");
				document.write('</div>');
			} else { 
				document.write("<span class='small'>$post_txt{'215'}</span>");
			}
			//-->
			</script>
			<noscript>
			<span class="small">$post_txt{'215'}</span>
			</noscript>
			</div>
			~;
		}

			if (!${$uid.$username}{'postlayout'}) { $pheight = 130; $pwidth = 425; $textsize = 11; }
			else { ($pheight, $pwidth, $textsize) = split(/\|/, ${$uid.$username}{'postlayout'}); }
			if(!$textsize || $textsize < 11) { $textsize = 11; }
			if($textsize > 16) { $textsize = 16; }
			if($pheight > 400) { $pheight = 400; }
			if($pheight < 130) { $pheight = 130; }
			if($pwidth > 855) { $pwidth = 855; }
			if($pwidth < 425) { $pwidth = 425; }
			$mtextsize = $textsize . "px";
			$mheight = $pheight . "px";
			$mwidth = $pwidth . "px";
			$dheight = ($pheight + 12) . "px";
			$dwidth = ($pwidth + 12) . "px";
			$jsdragwpos = $pwidth - 425;
			$dragwpos = ($pwidth - 425) . "px";
			$jsdraghpos = $pheight - 130;
			$draghpos = ($pheight - 130) . "px";

			$yymain .= qq~

			<div style="float: left; width: 99%;">
			<input type="hidden" name="messagewidth" id="messagewidth" value="$pwidth" />
			<input type="hidden" name="messageheight" id="messageheight" value="$pheight" />
			<div id="dragcanvas" style="position: relative; top: 0px; left: 0px; height: $dheight; width: $dwidth; border: 0; z-index: 1;">
			<textarea name="message" id="message" rows="8" cols="68" style="position: absolute; top: 0px; left: 0px; z-index: 2; height: $mheight; width: $mwidth; font-family: Verdana; font-size: $mtextsize; padding: 5px; margin: 0px; visibility: visible;" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);" tabindex="4">$message</textarea>
			<div id="dragbgw" style="position: absolute; top: 0px; left: 437px; width: 3px; height: $dheight; border: 0; z-index: 3;">
			<img id="dragImg1" src="$defaultimagesdir/resize_wb.gif" class="drag" style="position: absolute; top: 0px; left: $dragwpos; z-index: 4; width: 3px; height: $dheight; cursor: e-resize;" />
			</div>
			<div id="dragbgh" style="position: absolute; top: 142px; left: 0px; width: $dwidth; height: 3px; border: 0; z-index: 3;">
			<img id="dragImg2" src="$defaultimagesdir/resize_hb.gif" class="drag" style="position: absolute; top: $draghpos; left: 0px; z-index: 4; width: $dwidth; height: 3px; cursor: n-resize;" />
			</div>
			</div>
			<div style="float: left; width: 315px; text-align: left;"> 
			<img src="$imagesdir/green1.gif" name="chrwarn" height="8" width="8" border="0" vspace="0" hspace="0" alt="" align="middle" />
			<span class="small">$npf_txt{'03'} <input value="$MaxMessLen" size="3" name="msgCL" class="windowbg2" style="border: 0px; font-size: 11px; width: 40px; padding: 1px" readonly="readonly" /></span>
			</div>
			<div style="float: left; width: 127px; text-align: right;">
				<span class="small">$post_txt{'textsize'} <input value="$textsize" size="2" name="txtsize" id="txtsize" class="windowbg2" style="border: 0px; font-size: 11px; width: 15px; padding: 1px" readonly="readonly" />px <img src="$imagesdir/smaller.gif" height="11" width="11" border="0" alt="" align="middle" onclick="sizetext(-1);" /><img src="$imagesdir/larger.gif" height="11" width="11" border="0" alt="" align="middle" onclick="sizetext(1);" /></span>
			</div>
			</div>
		</td>
	</tr>
	<tr>
		<td valign="top" class="windowbg2" width="23%">
		~;
		if ($showadded == 2 || $showsmdir == 2) {
			$yymain .= qq~
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			function Smiliextra() {
				AddTxt=smiliecode[document.postmodify.smiliextra_list.value];
				AddText(AddTxt);
			}
			~;

			$smilieslist = '';
			$smilie_url_array = '';
			$smilie_code_array = '';
			$i = 0;
			if ($showadded eq 2) {
				while ($SmilieURL[$i]) {
					$smilieslist .= qq~	document.write('<option value="$i">$SmilieDescription[$i]</option>');\n~;
					if ($SmilieURL[$i] =~ /\//i) { $tmpurl = $SmilieURL[$i]; }
					else { $tmpurl = qq~$defaultimagesdir/$SmilieURL[$i]~; }
					$smilie_url_array .= qq~"$tmpurl", ~;
					$tmpcode = $SmilieCode[$i];
					$tmpcode =~ s/\&quot;/"+'"'+"/g;    # "'
					&FromHTML($tmpcode);
					$tmpcode =~ s/&#36;/\$/g;
					$tmpcode =~ s/&#64;/\@/g;
					$smilie_code_array .= qq~" $tmpcode", ~;
					$i++;
				}
			}
			if ($showsmdir eq 2) {
				opendir(DIR, "$smiliesdir");
				@contents = readdir(DIR);
				closedir(DIR);
				foreach $line (sort { uc($a) cmp uc($b) } @contents) {
					($name, $extension) = split(/\./, $line);
					if ($extension =~ /gif/i || $extension =~ /jpg/i || $extension =~ /jpeg/i || $extension =~ /png/i) {
						if ($line !~ /banner/i) {
							$smilieslist .= qq~	document.write('<option value="$i">$name</option>');\n~;
							$smilie_url_array .= qq~"$smiliesurl/$line", ~;
							$smilie_code_array .= qq~" [smiley=$line]", ~;
							$i++;
						}
					}
				}
			}
			$smilie_url_array  .= qq~""~;
			$smilie_code_array .= qq~""~;

			$yymain .= qq~
			smilieurl = new Array($smilie_url_array)
			smiliecode = new Array($smilie_code_array)
			if ((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4)) {
				document.write('<table class="bordercolor" height="90" width="120" border="0" cellpadding="2" cellspacing="1" align="center"><tr>');
				document.write('<td height="15" align="center" valign="middle" class="titlebg"><span class="small"><b>$post_smiltxt{'1'}</b></span></td>');
				document.write('</tr><tr>');
				document.write('<td height="20" align="center" valign="top" class="windowbg2"><select name="smiliextra_list" onchange="document.images.smiliextra_image.src= smilieurl[document.postmodify.smiliextra_list.value]" style="width:114px; font-size:7pt;">');
				$smilieslist
				document.write('</select></td>');
				document.write('</tr><tr>');
				document.write('<td height="70" align="center" valign="middle" class="windowbg2"><img name="smiliextra_image" src="'+smilieurl[0]+'" alt="" border="0" onclick="javascript: Smiliextra();" style="cursor: pointer;"></td>');
				document.write('</tr><tr>');
				document.write('<td height="15" align="center" valign="middle" class="windowbg2"><span class="small"><a href="javascript: smiliewin();">$post_smiltxt{'17'}</a></span></td>');
				document.write('</tr></table>');
			}
			//-->
			</script>
			~;
		} else {
			$yymain .= qq~
			&nbsp;
			~;
		}

$yymain .= qq~
		</td>
	</tr>
	<tr>
		<td class="windowbg2" width="23%">
			&nbsp;
		</td>
		<td width="77%" valign="middle" class="windowbg2">
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if ((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer; cursor: hand;'";
				document.write("<img src='$imagesdir/smiley.gif' onclick='smiley();' "+HAND+" align='bottom' alt='$post_txt{'287'}' title='$post_txt{'287'}' border='0'> ");
				document.write("<img src='$imagesdir/wink.gif' onclick='wink();' "+HAND+" align='bottom' alt='$post_txt{'292'}' title='$post_txt{'292'}' border='0'> ");
				document.write("<img src='$imagesdir/cheesy.gif' onclick='cheesy();' "+HAND+" align='bottom' alt='$post_txt{'289'}' title='$post_txt{'289'}' border='0'> ");
				document.write("<img src='$imagesdir/grin.gif' onclick='grin();' "+HAND+" align='bottom' alt='$post_txt{'293'}' title='$post_txt{'293'}' border='0'> ");
				document.write("<img src='$imagesdir/angry.gif' onclick='angry();' "+HAND+" align='bottom' alt='$post_txt{'288'}' title='$post_txt{'288'}' border='0'> ");
				document.write("<img src='$imagesdir/sad.gif' onclick='sad();' "+HAND+" align='bottom' alt='$post_txt{'291'}' title='$post_txt{'291'}' border='0'> ");
				document.write("<img src='$imagesdir/shocked.gif' onclick='shocked();' "+HAND+" align='bottom' alt='$post_txt{'294'}' title='$post_txt{'294'}' border='0'> ");
				document.write("<img src='$imagesdir/cool.gif' onclick='cool();' "+HAND+" align='bottom' alt='$post_txt{'295'}' title='$post_txt{'295'}' border='0'> ");
				document.write("<img src='$imagesdir/huh.gif' onclick='huh();' "+HAND+" align='bottom' alt='$post_txt{'296'}' title='$post_txt{'296'}' border='0'> ");
				document.write("<img src='$imagesdir/rolleyes.gif' onclick='rolleyes();' "+HAND+" align='bottom' alt='$post_txt{'450'}' title='$post_txt{'450'}' border='0'> ");
				document.write("<img src='$imagesdir/tongue.gif' onclick='tongue();' "+HAND+" align='bottom' alt='$post_txt{'451'}' title='$post_txt{'451'}' border='0'> ");
				document.write("<img src='$imagesdir/embarassed.gif' onclick='embarassed();' "+HAND+" align='bottom' alt='$post_txt{'526'}' title='$post_txt{'526'}' border='0'> ");
				document.write("<img src='$imagesdir/lipsrsealed.gif' onclick='lipsrsealed();' "+HAND+" align='bottom' alt='$post_txt{'527'}' title='$post_txt{'527'}' border='0'> ");
				document.write("<img src='$imagesdir/undecided.gif' onclick='undecided();' "+HAND+" align='bottom' alt='$post_txt{'528'}' title='$post_txt{'528'}' border='0'> ");
				document.write("<img src='$imagesdir/kiss.gif' onclick='kiss();' "+HAND+" align='bottom' alt='$post_txt{'529'}' title='$post_txt{'529'}' border='0'> ");
				document.write("<img src='$imagesdir/cry.gif' onclick='cry();' "+HAND+" align='bottom' alt='$post_txt{'530'}' title='$post_txt{'530'}' border='0'> ");$moresmilieslist
			} else { 
				document.write("<span  class='small'>$post_txt{'215'}</span>");
			}
			//-->
			</script>
~;
			if (($showadded == 3 && $showsmdir != 2) || ($showsmdir == 3 && $showadded != 2)) {
				$yymain .= qq~
				<a href="javascript: smiliewin();">$post_smiltxt{'1'}</a>
				~;
			}
$yymain .= qq~
			<noscript>
			<span class="small">$post_txt{'215'}</span>
			</noscript>
		</td>
	</tr>

~;

# File Attachment's Browse Box Code
	if (&AccessCheck($currentboard, 4) eq 'granted') {
		if ($action eq 'modify2' && $FORM{'oldattach'} ne '' && $FORM{'w_file'} ne '' && $postid ne 'Poll') {
			$isatt = $FORM{'oldattach'};
			chomp $isatt;
		}
		if ($allowattach == 1 && ${$uid.$currentboard}{'attperms'} == 1 && $fa_ok == 1 && ($action eq 'post' || $action eq 'post2' || $action eq 'modify' || $action eq 'modify2') && (($allowguestattach == 0 && !$iamguest) || $allowguestattach == 1)) {
			$selnewatt = '';
			if ($action eq 'modify' && $isatt || $action eq 'modify2' && $isatt) {
				$selnewatt = qq~ onchange="selectNewattach();"~;
			}
			$yymain .= qq~
			<tr>
				<td width="23%" valign="top"><b>$fatxt{'6'}</b></td>
				<td width="77%"><input type="file" name="file" size="50"$selnewatt /></td>
			</tr>
			<tr>
				<td width="23%" align="right"></td>
				<td width="77%"><span class="small">$filetype_info<br />$filesize_info</span>
			~;

			if (($action eq 'modify' || $action eq 'modify2') && $isatt ne '') {
				if ($isatt ne '') {
					$oldattcheck = qq~ selected="selected"~;
					$newattcheck = '';
					$atistxt = qq~$fatxt{'40'}: <a href="$uploadurl/$isatt">$isatt</a>~;
				} else {
					$newattcheck = qq~ selected="selected"~;
					$oldattcheck = '';
					$atistxt = '';
				}
				$yymain .= qq~
				<tr>
					<td width="23%" valign="top"></td>
					<td width="77%"><font size="1">
					<select id="w_file" name="w_file" size="1">
					<option value="attachdel">$fatxt{'6c'}</option>
					<option value="attachnew"$newattcheck>$fatxt{'6b'}</option>
					<option value="attachold"$oldattcheck>$fatxt{'6a'}</option>
					</select>&nbsp;$atistxt</font>
					<input type="hidden" name="oldattach" id="oldattach" value="$isatt" /></td>
				</tr>
				~;
			}
			elsif ($action eq 'modify' || $action eq 'modify2') {
				$yymain .= qq~
				<input type="hidden" id="w_file" name="w_file" value="attachnew" />
				<input type="hidden" name="oldattach" id="oldattach" value="$mfn" />
					</td>
				</tr>
				~;
			} else {
				$yymain .= qq~
					</td>
				</tr>
				~;
			}
			if ($is_preview == 1 && $FORM{'file'}) {
				$yymain .= qq~
				<tr>
					<td width="23%" align="right"></td>
					<td width="77%"><b>$fatxt{'7'}</b><br /><br /></td>
				</tr>
				~;
			}

		}
	}
# /File Attachment's Browse Box Code

		$yymain .= qq~
$notification
$favoriteadd
      <tr>
        <td class="windowbg" width="23%">
		<b>$post_txt{'276'}:</b>
	</td>
        <td class="windowbg" width="77%">
		<input type="checkbox" name="ns" value="NS"$nscheck /> <span class="small"> $post_txt{'277'}</span>
	</td>
      </tr>

      <tr>
        <td class="windowbg" width="23%">
		<div id="enable_iecopytext" style="display: none;">
		<b>$post_txt{'iecopytext'}:</b><br /><br />
		</div>
	</td>
        <td class="windowbg" width="77%">
		<div id="enable_iecopy" style="display: none;">
		<input type="checkbox" name="iecopy" id="iecopy"$iecopycheck /> <span class="small"> $post_txt{'iecopycheck'}</span><br /><br />
		</div>
	</td>
      </tr>

$lastmod
~;
	}

	#these are the buttons to submit
	if ($is_preview) { $post_txt{'507'} = $post_txt{'771'}; }
	$yymain .= qq~
      <tr>
        <td align="center" class="titlebg" colspan="2">
	$hidestatus
        <span class="small">$post_txt{'329'}</span><br />
		<input type="submit" name="$post" id="$post" value="$submittxt" accesskey="s" tabindex="5" class="button" />~;

	$yymain .= qq~&nbsp;&nbsp;<input type="submit" id="$preview" name="$preview" value="$post_txt{'507'}" accesskey="p" tabindex="6" class="button" />~;
	unless ($is_preview){ $yymain .= qq~&nbsp;&nbsp;<input type="reset" value="$post_txt{'278'}" accesskey="r" tabindex="7" class="button" />~; }

	if ($destination eq 'modalert2') {
		$yymain .= qq~<input type="hidden" name="tomods" id="tomods" value="${$uid.$currentboard}{'mods'}" />
		<input type="hidden" name="tomodgroups" id="tomodgroups" value="${$uid.$currentboard}{'modgroups'}" />
		~;
	}

	if ($speedpostdetection){
		$yymain .= qq~
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		var postdelay = $min_post_speed*1000;
		document.postmodify.$post.value='$post_txt{"delay"}';
		document.postmodify.$post.disabled=true;
		document.postmodify.$post.style.cursor='default';
		var delay = window.setInterval('releasepost()',postdelay );
		function releasepost() {
			document.postmodify.$post.value='$submittxt';
			document.postmodify.$post.disabled=false;
			document.postmodify.$post.style.cursor='pointer';
			window.clearInterval(delay);
		}
		//-->
		</script>
	~;
	}

	$yymain .= qq~
        </td>
      </tr>
</table>
</div>
</form>
~;
if($postid ne 'Poll') {
$yymain .= qq~
<script type="text/javascript" language="JavaScript1.2">
<!--

var oldwidth = parseInt(document.getElementById('message').style.width) - $jsdragwpos;
var olddragwidth = parseInt(document.getElementById('dragbgh').style.width) - $jsdragwpos;
var oldheight = parseInt(document.getElementById('message').style.height) - $jsdraghpos;
var olddragheight = parseInt(document.getElementById('dragbgw').style.height) - $jsdraghpos;

var skydobject={
x: 0, y: 0, temp2 : null, temp3 : null, targetobj : null, skydNu : 0, delEnh : 0,

initialize:function() {
	document.onmousedown = this.skydeKnap
	document.onmouseup=function(){
		this.skydNu = 0;
		document.getElementById('messagewidth').value = parseInt(document.getElementById('message').style.width);
		document.getElementById('messageheight').value = parseInt(document.getElementById('message').style.height);
	}
},
changeSize:function(deleEnh, knapId) {
	if (knapId == "dragImg1") {
		newwidth = oldwidth+parseInt(deleEnh);
		newdragwidth = olddragwidth+parseInt(deleEnh);
		document.getElementById('message').style.width = newwidth+'px';
		document.getElementById('dragbgh').style.width = newdragwidth+'px';
		document.getElementById('dragImg2').style.width = newdragwidth+'px';
	}
	if (knapId == "dragImg2") {
		newheight = oldheight+parseInt(deleEnh);
		newdragheight = olddragheight+parseInt(deleEnh);
		document.getElementById('message').style.height = newheight+'px';
		document.getElementById('dragbgw').style.height = newdragheight+'px';
		document.getElementById('dragImg1').style.height = newdragheight+'px';
		document.getElementById('dragcanvas').style.height = newdragheight+'px';

	}
},
flytKnap:function(e) {
	var evtobj = window.event ? window.event : e
	if (this.skydNu == 1) {
		sizestop = f_clientWidth()
		maxstop = parseInt(((sizestop*66)/100)-427)
		if(maxstop > 413) maxstop = 413
		if(maxstop < 60) maxstop = 60

		glX = parseInt(this.targetobj.style.left)
		this.targetobj.style.left = this.temp2 + evtobj.clientX - this.x + "px"
		nyX = parseInt(this.temp2 + evtobj.clientX - this.x)
		if (nyX > glX) retning = "vn"; else retning = "hj";
		if (nyX < 1 && retning == "hj") { this.targetobj.style.left = 0 + "px"; nyX = 0; retning = "vn"; }
		if (nyX > maxstop && retning == "vn") { this.targetobj.style.left = maxstop + "px"; nyX = maxstop; retning = "hj"; }
		delEnh = parseInt(nyX)
		var knapObj = this.targetobj.id
		skydobject.changeSize(delEnh, knapObj)
		return false
	}
	if (this.skydNu == 2) {
		glY = parseInt(this.targetobj.style.top)
		this.targetobj.style.top = this.temp3 + evtobj.clientY - this.y + "px"
		nyY = parseInt(this.temp3 + evtobj.clientY - this.y)
		if (nyY > glY) retning = "vn"; else retning = "hj";
		if (nyY < 1 && retning == "hj") { this.targetobj.style.top = 0 + "px"; nyY = 0; retning = "vn"; }
		if (nyY > 270 && retning == "vn") { this.targetobj.style.top = 270 + "px"; nyY = 270; retning = "hj"; }
		delEnh = parseInt(nyY)
		var knapObj = this.targetobj.id
		skydobject.changeSize(delEnh, knapObj)
		return false
	}
},
skydeKnap:function(e) {
	var evtobj = window.event ? window.event : e
	this.targetobj = window.event ? event.srcElement : e.target
	if (this.targetobj.className == "drag") {
		if(this.targetobj.id == "dragImg1") this.skydNu = 1
		if(this.targetobj.id == "dragImg2") this.skydNu = 2
		this.knapObj = this.targetobj
		if (isNaN(parseInt(this.targetobj.style.left))) this.targetobj.style.left = 0
		if (isNaN(parseInt(this.targetobj.style.top))) this.targetobj.style.top = 0
		this.temp2 = parseInt(this.targetobj.style.left)
		this.temp3 = parseInt(this.targetobj.style.top)
		this.x = evtobj.clientX
		this.y = evtobj.clientY
		if (evtobj.preventDefault) evtobj.preventDefault()
		document.onmousemove = skydobject.flytKnap
	}
}
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel))) n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

var orgsize = $textsize;

function sizetext(sizefact) {
	orgsize = orgsize + sizefact;
	if(orgsize < 11) orgsize = 11;
	if(orgsize > 16) orgsize = 16;
	document.getElementById('message').style.fontSize = orgsize+'px';
	document.getElementById('txtsize').value = orgsize;
}

skydobject.initialize()
//-->
</script>
~;
}
	if ($postid ne 'Poll' && $currentboard ne $annboard && $post ne 'imsend' && (($iamadmin || $iamgmod || $iammod) && $sessionvalid == 1)) {
		$yymain .= qq~
	<script language="JavaScript1.2" type="text/javascript">
	<!--
	function showtpstatus() {
		var z = 0;
		var x = 0;
		var theimg = '$threadclass';
		for(var i=0; i<document.postmodify.topicstatus.length; i++) {
			if (document.postmodify.topicstatus[i].selected) { z++; x += i; }
		}
		if(z == 1 && x == 0)  theimg = 'sticky';
		if(z == 1 && x == 1)  theimg = 'locked';
		if(z == 2 && x == 1)  theimg = 'stickylock';
		if(z == 1 && x == 2)  theimg = 'hide';
		if(z == 2 && x == 2)  theimg = 'hidesticky';
		if(z == 2 && x == 3)  theimg = 'hidelock';
		if(z == 3 && x == 3)  theimg = 'hidestickylock';
		document.images.thrstat.src='$imagesdir/'+theimg+'.gif';
	}
	document.onload = showtpstatus();
	//-->
	</script>
	~;
	}

	if ($action eq "modify" || $action eq "modify2") {
		$displayname = qq~$mename~;
	} else {
		$displayname = ${$uid.$username}{'realname'};
	}

	require "$templatesdir/$usedisplay/Display.template";

	foreach (@months) { $jsmonths .= qq~'$_',~; }
	$jsmonths =~ s~\,\Z~~;
	$jstimeselected = ${$uid.$username}{'timeselect'} || $timeselected;

	if($postid ne 'Poll') {
		$yymain .= qq~
<script language="JavaScript1.2" src="$yabbcjspath" type="text/javascript"></script>
<script type="text/javascript" language="JavaScript"> <!--
var noalert = true, gralert = false, rdalert = false, clalert = false;
var prevsec = 5
var prevtxt
var cntsec = 0

function tick() {
  cntsec++
  calcCharLeft()
  var timerID = setTimeout("tick()",1000)
}

var autoprev = false
var topicfirst = true;

post_txt_807 = "$post_txt{'807'}";

function enabPrev() {
	if ( autoprev == false ) {
		autoprev = true
		topicfirst = true
		document.getElementById("savetable").style.visibility = "visible";
		document.getElementById("SaveInfo").style.height = "auto";
		document.getElementById("savetopic").style.height = "auto";
		document.getElementById("saveframe").style.height = "auto";
		document.images.prevwin.alt = "$npf_txt{'02'}";
		document.images.prevwin.title = "$npf_txt{'02'}";
		document.images.prevwin.src="$defaultimagesdir/cat_collapse.gif";
		autoPreview();
	}
	else {
		autoprev = false;
		ubbstr = '';
		document.getElementById("savetable").style.visibility = "hidden";
		document.getElementById("SaveInfo").style.height = "16px";
		document.getElementById("savetopic").style.height = "0px";
		document.getElementById("saveframe").style.height = "0px";
		document.postmodify.message.focus();
		document.images.prevwin.alt = "$npf_txt{'01'}";
		document.images.prevwin.title = "$npf_txt{'01'}";
		document.images.prevwin.src="$defaultimagesdir/cat_expand.gif";
	}
	calcCharLeft();
}

function calcCharLeft() {
  var clipped = false
  var maxLength = $MaxMessLen
  if (document.postmodify.message.value.length > maxLength) {
	document.postmodify.message.value = document.postmodify.message.value.substring(0,maxLength)
	var charleft = 0
	clipped = true
  } else {
	charleft = maxLength - document.postmodify.message.value.length
  }
  prevsec++
  if(autoprev && prevsec > 5 && prevtxt != document.postmodify.message.value) {
	autoPreview()
	prevtxt = document.postmodify.message.value
  }
  document.postmodify.msgCL.value = charleft
  if (charleft >= 100 && noalert) { noalert = false; gralert = true; rdalert = true; clalert = true; document.images.chrwarn.src="$defaultimagesdir/green1.gif"; }
  if (charleft < 100 && charleft >= 50 && gralert) { noalert = true; gralert = false; rdalert = true; clalert = true; document.images.chrwarn.src="$defaultimagesdir/green0.gif"; }
  if (charleft < 50 && charleft > 0 && rdalert) { noalert = true; gralert = true; rdalert = false; clalert = true; document.images.chrwarn.src="$defaultimagesdir/red0.gif" }
  if (charleft == 0 && clalert) { noalert = true; gralert = true; rdalert = true; clalert = false; document.images.chrwarn.src="$defaultimagesdir/red1.gif"; }
  return clipped
}

var codestr = '$simpelcode';
var quotstr = '$normalquot';
var squotstr = '$simpelquot';
var fontsizemax = '$fontsizemax';
var fontsizemin = '$fontsizemin';
var edittxt = '$edittext';
var dispname = '$displayname';
var scrpurl = '$scripturl';
var imgdir = '$defaultimagesdir';
var ubsmilieurl = '$smiliesurl';
var parseflash = '$parseflash';
var autolinkurl = '$autolinkurls';
var Month = new Array($jsmonths);
var timeselected = '$jstimeselected';
var splittext = "$maintxt{'107'}";
var dontusetoday = '$dontusetoday';
var todaytext = "$maintxt{'769'}";
var yesterdaytext = "$maintxt{'769a'}";
var timetext1 = "$timetxt{'1'}";
var timetext2 = "$timetxt{'2'}";
var timetext3 = "$timetxt{'3'}";
var timetext4 = "$timetxt{'4'}";
var jsmilieurl = new Array($smilie_url_array);
var jsmiliecode = new Array($smilie_code_array);

function autoPreview() {
	if (topicfirst)  { updatTopic(); }
	var scrlto = parseInt(180) + 5;
	var vismessage = document.postmodify.message.value;
	while ( c=vismessage.match(/date=(\\d+?)\\]/i) ) {
		var qudate=c[1];
		qudate=qudate * 1000;
		qdate=new Date()
		qdate.setTime(qudate);
		qdate=qdate.toLocaleString();
		vismessage=vismessage.replace(/(date=)\\d+?(\\])/i, "\$1"+qdate+"\$2");
	}
	if($enable_ubbc) {
		var ubbstr = jsDoUbbc(vismessage,codestr,quotstr,squotstr,edittxt,dispname,scrpurl,imgdir,ubsmilieurl,parseflash,fontsizemax,fontsizemin,autolinkurl,Month,timeselected,splittext,dontusetoday,todaytext,yesterdaytext,timetext1,timetext2,timetext3,timetext4,jsmilieurl,jsmiliecode);
	}
	else {
		var ubbstr = vismessage;
	}
	document.getElementById("saveframe").innerHTML=ubbstr;
	scrlto += parseInt(document.getElementById("saveframe").scrollTop) + parseInt(document.getElementById("saveframe").offsetHeight);
	document.getElementById("saveframe").scrollTop = scrlto;
	prevsec = 0
}

var visikon = '';

function updatTopic() {
	var topicfirst = false;
	~;

	if ($destination ne 'modalert2' && $destination ne 'guestpm2') {
		$yymain .= qq~
	var visicon = document.postmodify.icon.value;
	visicon=visicon.replace(/http\\:\\/\\/.*\\/(.*?)\\.gif/g, "\$1");
	visicon=visicon.replace(/[^A-Za-z]/g, "");
	visicon=visicon.replace(/\\\\/g, "");
	visicon=visicon.replace(/\\//g, "");
	if (visicon != "xx" && visicon != "thumbup" && visicon != "thumbdown" && visicon != "exclamation") {
		if (visicon != "question" && visicon != "lamp" && visicon != "smiley" && visicon != "angry") {
			if (visicon != "cheesy" && visicon != "grin" && visicon != "sad" && visicon != "wink") {
				visicon = "xx";
			}
		}
	}
	visikon = "<img border='0' src='$imagesdir/"+visicon+".gif' alt='"+visicon+"' \/> ";
		~;
	}

		$yymain .= qq~
	var vistopic = document.postmodify.subject.value;
	var htmltopic = jsDoTohtml(vistopic);
	document.getElementById("savetopic").innerHTML=visikon+htmltopic;
	//document.postmodify.message.focus();
}

document.postmodify.$settofield.focus();

~;
	if ($post eq 'imsend') {
		$yymain .= qq~
	if(document.getElementById('toshowcc').length > 0) document.getElementById('toshowcc').style.display = 'inline';
	if(document.getElementById('toshowbcc').length > 0) document.getElementById('toshowbcc').style.display = 'inline';
~;
}
		$yymain .= qq~
if (navigator.appName == "Microsoft Internet Explorer") {
	document.getElementById('enable_iecopytext').style.display = 'inline';
	document.getElementById('enable_iecopy').style.display = 'inline';
}
tick();
//--> </script>
~;
	}

}

##  preview message
sub Preview {
	&clear_temp;
	my $error = $_[0];
	&ToHTML($e);

	# allows the following HTML-tags in error messages: <br /> <b>
	$error =~ s/&lt;br( \/)&gt;/<br \/>/ig;
	$error =~ s/&lt;(\/?)b&gt;/<$1b>/ig;
	$poll_question = $FORM{'question'};

	$maxpq ||= 60;
	$maxpo ||= 50;
	$maxpc ||= 0;
	$numpolloptions ||= 8;
	$vote_limit ||= 0;

	for (my $i = 1; $i <= $numpolloptions; $i++) {
		$options[$i] = $FORM{"option$i"};
		&FromHTML($options[$i]);
		&FromChars($options[$i]);
		$convertstr = $options[$i];
		$convertcut = $maxpo;
		&CountChars;
		$options[$i] = $convertstr;
		&ToHTML($options[$i]);
	}

	$guest_vote   = $FORM{'guest_vote'};
	$hide_results = $FORM{'hide_results'};
	$multi_choice = $FORM{'multi_choice'};
	$poll_comment = $FORM{'poll_comment'};
	$vote_limit   = $FORM{'vote_limit'};

	$pollthread = $FORM{'pollthread'} || 0;

	&FromHTML($poll_question);
	&FromChars($poll_question);
	$convertstr = $poll_question;
	$convertcut = $maxpq;
	&CountChars;
	$poll_question = $convertstr;
	&ToHTML($poll_question);
	
	&ToHTML($poll_comment);

	$name = $FORM{'name'};
	$email = $FORM{'email'};
	$sub = $FORM{'subject'};
	$FORM{'message'} =~ s~\r~~g;
	$mess = $FORM{'message'};
	$message = $FORM{'message'};
	$icon = $FORM{'icon'};
	$ns = $FORM{'ns'};
	$threadid = $FORM{'threadid'};
	$notify = $FORM{'notify'};
	$postid = $FORM{'postid'};
	$thestatus = $FORM{'topicstatus'};
	$isBMess = $FORM{'isBMess'};
	if (!$iamguest) {
		$textareawidth = $FORM{'messagewidth'};
		$textareaheight = $FORM{'messageheight'};
		$textareafont = $FORM{'txtsize'};
		${$uid.$username}{'postlayout'} = qq~$textareaheight|$textareawidth|$textareafont~;
		&UserAccount($username, "update");
	}
	$postthread = 2 if ($threadid);

	if (!$sub && $pollthread != 2) { $error = $post_txt{'77'}; }
	$sub =~ s/[\r\n]//g;
	my $testsub = $sub;
	$testsub =~ s/\&nbsp;//g;
	$testsub =~ s/ //g;

	&FromHTML($sub);
	&FromChars($sub);
	$convertstr = $sub;
	$convertcut = $set_subjectMaxLength;
	if ($postthread == 2) { $convertcut += 4; $set_subjectMaxLength += 4; } ## this allows replies not to have truncated titles  ;)
	&CountChars;
	$sub = $convertstr;
	&ToHTML($sub);

	my $testmessage = $mess;
	$testmessage =~ s/[\r\n\ ]//g;
	$testmessage =~ s/\&nbsp;//g;
	$testmessage =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
	$testmessage =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
	$testmessage =~ s/\[.*?\]//g;
	if ($testmessage eq "" && $mess ne "" && $pollthread != 2) { fatal_error("useless_post","$testmessage"); }
	$message =~ s/\cM//g;
	$message =~ s~\[([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[$1$2\]~g;
	$message =~ s~\[/([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[/$1$2\]~g;
#	$message =~ s~(\w+://[^<>\s\n\"\]\[]+)\n([^<>\s\n\"\]\[]+)~$1$2~g;
	&FromChars($message);
	&ToHTML($message);
	$message =~ s/\t/ \&nbsp; \&nbsp; \&nbsp;/g;
	$message =~ s/\n/<br \/>/g;
	$message =~ s/([\000-\x09\x0b\x0c\x0e-\x1f\x7f])/\x0d/g;
	&CheckIcon;

	if    ($icon eq "xx")          { $ic1  = " selected=\"selected\" "; }
	elsif ($icon eq "thumbup")     { $ic2  = " selected=\"selected\" "; }
	elsif ($icon eq "thumbdown")   { $ic3  = " selected=\"selected\" "; }
	elsif ($icon eq "exclamation") { $ic4  = " selected=\"selected\" "; }
	elsif ($icon eq "question")    { $ic5  = " selected=\"selected\" "; }
	elsif ($icon eq "lamp")        { $ic6  = " selected=\"selected\" "; }
	elsif ($icon eq "smiley")      { $ic7  = " selected=\"selected\" "; }
	elsif ($icon eq "angry")       { $ic8  = " selected=\"selected\" "; }
	elsif ($icon eq "cheesy")      { $ic9  = " selected=\"selected\" "; }
	elsif ($icon eq "grin")        { $ic10 = " selected=\"selected\" "; }
	elsif ($icon eq "sad")         { $ic11 = " selected=\"selected\" "; }
	elsif ($icon eq "wink")        { $ic12 = " selected=\"selected\" "; }
	if ($FORM{'status'} eq 'c')    { $icon = 'confidential'; }
	elsif ($FORM{'status'} eq 'u') { $icon = 'urgent'; }
	elsif ($FORM{'status'} eq 's') { $icon = 'standard'; }

	$name_field = $realname eq ''
	  ? qq~      <tr>
    <td class="windowbg" align="left" width="23%"><b>$post_txt{'68'}:</b></td>
    <td class="windowbg" align="left" width="77%"><input type="text" name="name" size="25" value="$FORM{'name'}" maxlength="25" tabindex="2" /></td>
      </tr>~
	  : qq~~;

	$email_field = $realemail eq ''
	  ? qq~      <tr>
    <td class="windowbg" width="23%"><b>$post_txt{'69'}:</b></td>
    <td class="windowbg" width="77%"><input type="text" name="email" size="25" value="$FORM{'email'}" maxlength="40" tabindex="3" /></td>
      </tr>~
	  : qq~~;
	if ($iamguest && $gpvalid_en) {
		$usename = substr($date,1,length($date)-4);
		$sesname = substr($date,0,length($date)-4);
		$verification = $FORM{'verification'};
		$sessionid = $FORM{$sesname};
		$regdate = $FORM{$usename};
		my $prvpepper = &scramble($username, $masterkey);
		my $prvsessionid = &scramble($verification,$masterkey);
		my $prvsesname = &encode_password("A$FORM{'base'}");
		my $prvses2name = &encode_password("B$FORM{'base'}");
		$verification_field = $verification ne ''
		? qq~
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'3'}:</b></td>
				<td class="windowbg" width="77%">$verification
				<input type="hidden" name="verification" id="verification" value="$verification" />
				<input type="hidden" name="base" id="base" value="$FORM{'base'}" />
				<input type="hidden" name="$prvsesname" id="$prvsesname" value="$prvsessionid" />
				<input type="hidden" name="$prvses2name" id="$prvses2name" value="$prvpepper" />
				</td>
			</tr>
		~
			: qq~~;
	}
	if ($FORM{'notify'} eq 'x')  { $notify  = qq~ checked="checked"~; }
	if ($FORM{'ns'} eq 'NS') { $nscheck = qq~ checked="checked"~; }
	if ($FORM{'iecopy'}) { $iecopycheck = qq~ checked="checked"~; }

	if ($iamguest) {
		$name .= "($post_txt{'772'})";
	}

	&wrap;
	if ($action eq 'modify2') {
		$displayname = $FORM{'mename'};
	} else {
		$displayname = ${$uid.$username}{'realname'};
	}
	if ($enable_ubbc) {
		if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }
		&DoUBBC;
	}
	&wrap2;
	if ($FORM{'previewmodify'} || $FORM{'postmodify'}) {
		$submittxt = $post_txt{'10'};
		$is_preview = 1;
		$post = 'postmodify';
		$preview = 'previewmodify';
		$destination = 'modify2';
	} elsif (!$FORM{'previewim'} && $INFO{'action'} ne 'modalert2' && $INFO{'action'} ne 'guestpm2') {
		$notification = $iamguest ? '' : qq~
    <tr>
      <td width="23%" class="windowbg"><b>$post_txt{'131'}:</b></td>
      <td width="77%" class="windowbg"><input type="checkbox" name="notify" value="x"$notify /> <span  class="small">$post_txt{'750'}</span></td>
    </tr>
~;
		$destination = 'post2';
		$submittxt = $post_txt{'105'};
		$is_preview = 1;
		$post = 'post';
		$preview = 'preview';
	}

	if ($INFO{'action'} eq 'imgroups') { $destination = 'imgroups'; }

	if ($INFO{'action'} eq 'modalert2') {
		$t_title = $post_txt{'alertmod'};
		$destination = 'modalert2';
		$submittxt = $post_txt{'148'};
		$is_preview = 1;
		$post = 'modalert';
		$preview = 'preview';
		$yytitle = $post_txt{'alertmod'};
	}
	if ($INFO{'action'} eq 'guestpm2') {
		$t_title = $display_txt{'guestpost'};
		$destination = 'guestpm2';
		$submittxt = $post_txt{'105'};
		$is_preview = 1;
		$post = 'guestpm';
		$preview = 'preview';
		$yytitle = $display_txt{'guestpost'};
	}

	$csubject = $sub;
	$csubject = &Censor($csubject);
	$message  = &Censor($message);
	&ToChars($csubject);
	&ToChars($message);
	require "$templatesdir/$usedisplay/Display.template";

	$prevmain .= qq~
		<script language="JavaScript1.2" type="text/javascript" src="$ubbcjspath"></script>
		<div class="bordercolor" style="padding: 1px; width: 100%; margin-left: auto; margin-right: auto;">
		<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
		 <tr>
		  <td class="titlebg">
		   <img src="$imagesdir/$icon.gif" name="icons2" border="0" alt="" /> $csubject
		  </td>
		 </tr>
		</table>
		<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
		 <tr>
		  <td class="windowbg2">
		   <span class="message">$message</span>
		  </td>
		 </tr>
		</table>
		</div>\n~;

	if ($error) {
		&LoadLanguage('Error');
		$prevmain .= qq~
		<div class="bordercolor" style="padding: 1px; width: 100%; margin-left: auto; margin-right: auto;">
		<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
		 <tr>
		  <td class="titlebg">
		   <img src="$imagesdir/exclamation.gif" border="0" alt="" /> $error_txt{'error_occurred'}
		  </td>
		 </tr>
		</table>
		<table border="0" width="100%" cellpadding="3" cellspacing="0" class="windowbg" style="table-layout: fixed;">
		 <tr>
		  <td class="windowbg2">
		   <span class="message"><br />$error<br /><br /></span>
		  </td>
		 </tr>
		</table>
		</div>\n~;
	}

	$message = $mess;
	&FromChars($message);
	&ToHTML($message);
	if ($error) { $csubject = $error; }
	$yytitle = $error ? "$error_txt{'error_occurred'} $csubject" : "$post_txt{'507'} - $csubject";
	$settofield = "message";
	$postthread = 2;
	&MessageTotals("load", $threadid);
	if (!$view) {
		&Postpage;
		if ($threadid ne '' && $post eq 'post') { &doshowthread; }
		&template;
		exit;
	}
}

sub Post2 {

	if ($iamguest && $enable_guestposting == 0) { &fatal_error("not_logged_in"); }
	if ($currentboard eq $annboard && !$iamadmin && !$iamgmod) { &fatal_error('not_allowed'); }
	if (!$iamadmin && !$iamgmod && !$iammod && $speedpostdetection && ${$uid.$username}{'spamcount'} >= $post_speed_count) {
		$detention_time = ${$uid.$username}{'spamtime'} + $spd_detention_time;
		if($date <= $detention_time){
			$detention_left = $detention_time - $date;
			&fatal_error("speedpostban");
		} else {
			${$uid.$username}{'spamcount'} = 0;
			&UserAccount($username,"update");
		}
	}
	if ($iamguest && $gpvalid_en) {
		&validation_check($FORM{'verification'});
	}
	my ($email, $ns, $notify, @memberlist, $i, $realname, $membername, $testname, @reserve, @reservecfg, $matchword, $matchcase, $matchuser, $matchname, $namecheck, $reserved, $reservecheck, @messages, $mnum, $msub, $mname, $memail, $mdate, $musername, $micon, $mstate, $pageindex, $tempname);

	&BoardTotals("load", $currentboard);

	# If poster is a Guest then evaluate the legality of name and email
	if (!${$uid.$username}{'email'}) {
		$FORM{'name'} =~ s/\A\s+//;
		$FORM{'name'} =~ s/\s+\Z//;
		&Preview($post_txt{'75'}) unless ($FORM{'name'} ne '' && $FORM{'name'} ne '_' && $FORM{'name'} ne ' ');
		&Preview($post_txt{'568'}) if (length($FORM{'name'}) > 25);
		&Preview("$post_txt{'76'}") if ($FORM{'email'} eq '');
		&Preview("$post_txt{'240'} $post_txt{'69'} $post_txt{'241'}") if ($FORM{'email'} !~ /[\w\-\.\+]+\@[\w\-\.\+]+\.(\w{2,4}$)/);
		&Preview("$post_txt{'500'}") if (($FORM{'email'} =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\.$)/) || ($FORM{'email'} !~ /^.+@\[?(\w|[-.])+\.([a-zA-Z]{2,4}|[0-9]{1,4})\]?$/));
	}

	# Get the form values
	$name       = $FORM{'name'};
	$email      = $FORM{'email'};
	$subject    = $FORM{'subject'};
	$message    = $FORM{'message'};
	$icon       = $FORM{'icon'};
	$ns         = $FORM{'ns'};
	$ann        = $FORM{'ann'};
	$threadid   = $FORM{'threadid'};
	$pollthread = $FORM{'pollthread'} || 0;
	$posttime   = $FORM{'post_entry_time'};
	if ($threadid =~ /\D/) { &fatal_error("only_numbers_allowed"); }
	$notify    = $FORM{'notify'};
	$favorite    = $FORM{'favorite'};
	$thestatus = $FORM{'topicstatus'};
	$thestatus =~ s/\, //g;
	chomp $thestatus;

	# Check if poster isn't using a distilled email domain
	&email_domain_check($email);
	$spamdetected = &spamcheck("$name $subject $message");
	if (!${$uid.$FORM{$username}}{'spamcount'}) { ${$uid.$FORM{$username}}{'spamcount'} = 0; }
	$postspeed = $date - $posttime;
	if (!$iamadmin && !$iamgmod && !$iammod){
		if (($speedpostdetection && $postspeed < $min_post_speed) || $spamdetected == 1) {
			${$uid.$username}{'spamcount'}++;
			${$uid.$username}{'spamtime'} = $date;
			&UserAccount($username,"update");
			$spam_hits_left_count = $post_speed_count - ${$uid.$username}{'spamcount'};
			if($spamdetected == 1){ &fatal_error("tsc_alert"); } else { &fatal_error("speed_alert"); }
		}
	}
	# Permission checks for posting.
	if (!$threadid) {
		# Check for ability to post new threads
		unless (&AccessCheck($currentboard, 1) eq 'granted' || $pollthread) { &fatal_error('no_perm_post'); }
	} else {
		# Check for ability to reply to threads
		unless (&AccessCheck($currentboard, 2) eq 'granted' || $pollthread) { &fatal_error('no_perm_reply'); }
		$postthread = 2;
	}
	if ($pollthread) {
		# Check for ability to post polls
		unless (&AccessCheck($currentboard, 3) eq 'granted') { &fatal_error('no_perm_poll'); }
	}
	if ($FORM{'file'}) {
		# Check for ability to post attachments
		unless (&AccessCheck($currentboard, 4) eq 'granted') { &fatal_error('no_perm_att'); }
	}
	# End Permission Checks

	## clean name and email - remove | from name and turn any _ to spaces fro amil
	if ($name && $email) {
		&ToHTML($name);
		$email =~ s/\|//g;
		&ToHTML($email);
		$tempname = $name;
		$name =~ s/\_/ /g;
	}

	# Fixes a bug with posting hexed characters.
	$name =~ s~amp;~~g;

	&Preview($post_txt{'75'}) unless ($username || $name);
	&Preview($post_txt{'76'}) unless (${$uid.$username}{'email'} || $email);
	&Preview($post_txt{'77'}) unless ($subject && $subject !~ m~\A[\s_.,]+\Z~);
	&Preview($post_txt{'78'}) unless ($message);

	# Check Message Length Precisely
	my $mess_len = $message;
	$mess_len =~ s/[\r\n ]//ig;
	$mess_len =~ s/&#\d{3,}?\;/X/ig;
	if (length($mess_len) > $MaxMessLen) {
		&Preview($post_txt{'536'} . " " . (length($mess_len) - $MaxMessLen) . " " . $post_txt{'537'});
	}
	undef $mess_len;

	if ($FORM{'preview'}) { &Preview; }
	&spam_protection;

	my $testsub = $subject;
	$testsub =~ s/[\r\n\ ]//g;
	$testsub =~ s/\&nbsp;//g;
	$testsub =~ s/ //g;

	if ($testsub eq "" && $pollthread != 2) { fatal_error("useless_post","$testsub"); }
	my $testmessage = $message;
	$testmessage =~ s/[\r\n\ ]//g;
	$testmessage =~ s/\&nbsp;//g;
	$testmessage =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
	$testmessage =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
	$testmessage =~ s/\[.*?\]//g;
	if ($testmessage eq "" && $message ne "" && $pollthread != 2) { fatal_error("useless_post","$testmessage"); }

	if (!$minlinkpost){ $minlinkpost = 0 ;}
	if (${$uid.$username}{'postcount'} < $minlinkpost && !$iamadmin && !$iamgmod && !$iammod) { 
		if ($message =~ m~http:\/\/~ || $message =~ m~https:\/\/~ || $message =~ m~ftp:\/\/~ || $message =~ m~www.~ || $message =~ m~ftp.~ =~ m~\[url~ || $message=~ m~\[link~ || $message=~ m~\[img~ || $message=~ m~\[ftp~) {
			&fatal_error("no_links_allowed");
		}
	}

	&FromHTML($subject);
	&FromChars($subject);
	$convertstr = $subject;
	$convertcut = $set_subjectMaxLength;
	if ($postthread == 2) { $convertcut += 4; $set_subjectMaxLength += 4; } ## this allows replies not to have truncated titles  ;)
	&CountChars;
	$subject = $convertstr;
	&ToHTML($subject);

	$subject =~ s/[\r\n]//g;
	$doadsubject = $subject;
	$message =~ s/\cM//g;
	$message =~ s~\[([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[$1$2\]~g;
	$message =~ s~\[/([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[/$1$2\]~g;
#	$message =~ s~(\w+://[^<>\s\n\"\]\[]+)\n([^<>\s\n\"\]\[]+)~$1\n$2~g;
	&FromChars($message);
	&ToHTML($message);
	$message =~ s~\t~ \&nbsp; \&nbsp; \&nbsp;~g;
	$message =~ s~\n~<br />~g;
	$message =~ s/([\000-\x09\x0b\x0c\x0e-\x1f\x7f])/\x0d/g;
	&CheckIcon;

	if (-e ("$datadir/.txt")) { unlink("$datadir/.txt"); }

	if (!$iamguest) {

		# If not guest, get name and email.
		$name  = ${$uid.$username}{'realname'};
		$email = ${$uid.$username}{'email'};
	} else {

		# If user is Guest, then make sure the chosen name and email
		# is not reserved or used by a member.
		if (lc $name eq lc &MemberIndex("check_exist", $name)) { &fatal_error("guest_taken","($name)"); }
		if (lc $email eq lc &MemberIndex("check_exist", $email)) { &fatal_error("guest_taken","($email)"); }

# 		$name .= "($post_txt{'772'})"; # Removed to un-hardcode the guest text
	}

	my @poll_data;
	if ($pollthread) {
		$maxpq          ||= 60;
		$maxpo          ||= 50;
		$maxpc          ||= 0;
		$numpolloptions ||= 8;

		$numcount = 0;
		$FORM{"question"} =~ s/\&nbsp;/ /g;
		$testspaces = $FORM{"question"};
		$testspaces =~ s/[\r\n\ ]//g;
		$testspaces =~ s/\&nbsp;//g;
		$testspaces =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
		$testspaces =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
		$testspaces =~ s/\[.*?\]//g;
		if (length($testspaces) == 0 && length($FORM{"question"}) > 0) { fatal_error("useless_post","$testmessage"); }

		&ToHTML($FORM{'question'});
		&FromChars($FORM{'question'});
		$convertstr = $FORM{'question'};
		$convertcut = $maxpq;
		&CountChars;
		$FORM{'question'} = $convertstr;
		&FromHTML($FORM{'question'});
		if ($cliped) { &Preview("$post_polltxt{'40'} $post_polltxt{'34a'} $maxpq $post_polltxt{'34b'} $post_polltxt{'36'}"); }

		&ToHTML($FORM{"question"});
		$guest_vote   = $FORM{'guest_vote'}   || 0;
		$hide_results = $FORM{'hide_results'} || 0;
		$multi_choice = $FORM{'multi_choice'} || 0;
		$vote_limit   = $FORM{'vote_limit'}   || 0;

		if ($vote_limit =~ /\D/) { $vote_limit = 0; &Preview("$post_polltxt{'62'}"); }

		$poll_comment = $FORM{'poll_comment'} || "";

		&ToHTML($poll_comment);
		&FromChars($poll_comment);
		$convertstr = $poll_comment;
		$convertcut = $maxpc;
		&CountChars;
		$poll_comment = $convertstr;

		if ($cliped) { &Preview("$post_polltxt{'57'} $post_polltxt{'34a'} $maxpc $post_polltxt{'34b'} $post_polltxt{'36'}"); }

		$poll_comment =~ s~\n~<br />~g;
		$poll_comment =~ s~\r~~g;
		push @poll_data, qq~$FORM{"question"}|0|$username|$name|$email|$date|$guest_vote|$hide_results|$multi_choice|||$poll_comment|$vote_limit\n~;

		for ($i = 1; $i <= $numpolloptions; $i++) {
			if ($FORM{"option$i"}) {
				$FORM{"option$i"} =~ s/\&nbsp;/ /g;
				$testspaces = $FORM{"option$i"};
				$testspaces =~ s/[\r\n\ ]//g;
				$testspaces =~ s/\&nbsp;//g;
				$testspaces =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
				$testspaces =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
				$testspaces =~ s/\[.*?\]//g;
				if (length($testspaces) == 0 && length($FORM{"option$i"}) > 0) { fatal_error("useless_post","$testmessage"); }

				&ToHTML($FORM{"option$i"});
				&FromChars($FORM{"option$i"});
				$convertstr = $FORM{"option$i"};
				$convertcut = $maxpo;
				&CountChars;
				$FORM{"option$i"} = $convertstr;
				if ($cliped) { &Preview("$post_polltxt{'7'} $i  $post_polltxt{'34a'} $maxpo $post_polltxt{'34b'} $post_polltxt{'36'}"); }

				$numcount++;
				push @poll_data, qq~0|$FORM{"option$i"}\n~;
			}
		}
		unless ($FORM{"question"}) { &Preview("$post_polltxt{'37'}"); }
		if     ($numcount < 2)     { &Preview("$post_polltxt{'38'}"); }
	}

	if ($FORM{'file'} ne "") {
		$file = $FORM{'file'};
		$OS   = $^O;             # operating system name
		if    ($OS =~ /darwin/i) { $isUNIX = 1; }
		elsif ($OS =~ /win/i)    { $isWIN  = 1; }
		else { $isUNIX = 1; }
		$mylimit    = 1024 * $limit;
		$mydirlimit = 1024 * $dirlimit;
		$fixfile    = $file;
		$fixfile =~ s/.+\\([^\\]+)$|.+\/([^\/]+)$/$1/;
		$fixfile =~ s/[\(\)\$#%+,\/:?"<>'\*\;|@^!]//g;    #" edit in between [ ] to include characters you dont want to allow in filenames (dont put a . there or you wont be able to get any file extensions).
		$fixfile =~ s/ /_/g;                              # replaces spaces in filenames with a "_" character.
		$fixfile =~ s/&//g;                               # replaces ampersands with nothing.
		$fixfile =~ s/\+//g;                              # replaces + with nothing

		$fixfile =~ s~[^/\\0-9A-Za-z#%+\,\-\ \.\:@^_]~~g; # Remove all inappropriate characters.

		# replace . with _ in the filename except for the extension
		$fixname = $fixfile;
		$fixname =~ s/(\S+)(\.\S+\Z)/$1/gi;

		$spamdetected = &spamcheck("$fixname");
		if (!$iamadmin && !$iamgmod && !$iammod){
			if ($spamdetected == 1) {
				${$uid.$username}{'spamcount'}++;
				${$uid.$username}{'spamtime'} = $date;
				&UserAccount($username,"update");
				$spam_hits_left_count = $post_speed_count - ${$uid.$username}{'spamcount'};
				&fatal_error("tsc_alert");
			}
		}

		$fixext = $2;
		$fixext  =~ s/(pl|cgi|php)/_$1/gi;
		$fixname =~ s/\./\_/g;
		$fixfile = qq~$fixname$fixext~;

		if ($overwrite == 2 && (-e "$uploaddir/$fixfile")) { &fatal_error("file_overwrite"); }
		if (!$overwrite) {
			$fixfile = check_existence($uploaddir, $fixfile);
		}
		if ($checkext == 0) { $match = 1; }
		else {
			foreach $ext (@ext) {
				chomp($ext);
				if (grep /$ext$/i, $fixfile) { $match = 1; last; }
			}
		}
		if ($match) {
			if ($allowattach == 1 && (($allowguestattach == 0 && $username ne 'Guest') || $allowguestattach == 1)) {
				$upload_okay = 1;
			}
		} else {
			&Preview("<br /><br />$fatxt{'20'} @ext ($fixfile)")
		}
		if ($mydirlimit > 0) {
			&dirstats;
		}
		$filesize   = $ENV{'CONTENT_LENGTH'} - $postsize;
		$filesizekb = int($filesize / 1024);
		if ($filesize > $mylimit && $mylimit != 0) {
			$filesizediff = $filesizekb - $limit;
			if ($filesizediff == 1) { $sizevar = "kilobyte"; }
			else { $sizevar = "kilobytes"; }
			&Preview("<br /><br />$fatxt{'21'} $filesizediff $sizevar $fatxt{'21b'}")

		} elsif ($filesize > $spaceleft && $mydirlimit != 0) {
			$filesizediff = $filesizekb - $kbspaceleft;
			if ($filesizediff == 1) { $sizevar = "kilobyte"; }
			else { $sizevar = "kilobytes"; }
			&Preview("<br /><br />$fatxt{'22'} $filesizediff $sizevar $fatxt{'22b'}");
		}

		if ($upload_okay == 1) {
			# create a new file on the server using the formatted ( new instance ) filename
			if (fopen(NEWFILE, ">$uploaddir/$fixfile")) {
				if ($isWIN) { binmode NEWFILE; }

				# start reading users HD.
				while (<$filename>) {
					# print to the new file on the server
					print NEWFILE;
				}

				# close the new file on the server and we're done
				fclose(NEWFILE);
			} else {

				# return the server's error message if the new file could not be created
				&fatal_error("file_not_open","$uploaddir");
			}
		}

		# check if file has actually been uploaded, by checking the file has a size
		if (-s "$uploaddir/$fixfile") {
			$upload_ok = 1;
		} else {

			# delete the file as it has no content
			unlink("$uploaddir/$fixfile");
			&fatal_error("file_not_uploaded","$fixfile");
		}

		if ($fixfile =~ /(jpg|gif|png|jpeg)$/i) {
			my $okatt = 1;
			if ($fixfile =~ /(gif)$/i) {
				fopen(ATTFILE, "$uploaddir/$fixfile");
				read(ATTFILE, $header, 10);
				my ($giftest, undef, undef, undef, undef, undef) = unpack("a3a3C4", $header );
				fclose(ATTFILE);
				if ($giftest ne "GIF") { $okatt = 0; }
			}
			fopen(ATTFILE, "$uploaddir/$fixfile");
			while ( read(ATTFILE, $buffer, 1024) ) {
				if ($buffer =~ /\<html/ig || $buffer =~ /\<script/ig) { $okatt = 0; last; }
			}
			fclose(ATTFILE);
			if(!$okatt) {
				# delete the file as it contains illegal code
				unlink("$uploaddir/$fixfile");
				&fatal_error("file_not_uploaded","$fixfile");
			}
		}

		&clear_temp;
	}

	# If no thread specified, this is a new thread.
	# Find a valid random ID for it.
	if ($threadid eq '') {
		$newthreadid = &getnewid;
	} else {
		$newthreadid = '';
	}
	$mreplies = 0;

	# set announcement flag according to status of current board
	if ($newthreadid) {
		if($thestatus && ($iammod || $iamgmod || $iamadmin)) { $mstate = "0$thestatus"; }
		else { $mstate = 0; }
		if ($currentboard eq $annboard) { $mstate = '0a'; }

		# This is a new thread. Save it.
		fopen(FILE, "+<$boardsdir/$currentboard.txt", 1) || &fatal_error("cannot_open","$boardsdir/$currentboard.txt", 1);
		seek FILE, 0, 0;
		my @buffer = <FILE>;
		truncate FILE, 0;
		seek FILE, 0, 0;
		print FILE qq~$newthreadid|$subject|$name|$email|$date|0|$username|$icon|$mstate\n~;
		print FILE @buffer;
		fclose(FILE);
		fopen(FILE, ">$datadir/$newthreadid.txt") || &fatal_error("cannot_open","$datadir/$newthreadid.txt", 1);
		print FILE qq~$subject|$name|$email|$date|$username|$icon|0|$user_ip|$message|$ns|||$fixfile\n~;
		fclose(FILE);
		$mreplies = 0;

		if ($file) {
			fopen(AMP, ">>$vardir/attachments.txt") || &fatal_error("cannot_open","$vardir/attachments.txt");
			print AMP qq~$newthreadid|$mreplies|$subject|$name|$currentboard|$filesizekb|$date|$fixfile\n~;
			fclose(AMP);
		}
		if ($pollthread) {    # Save Poll data for new thread
			fopen(POLL, ">$datadir/$newthreadid.poll");
			print POLL @poll_data;
			fclose(POLL);
		}
		## write the ctb file for the new thread
		${$newthreadid}{'board'}        = $currentboard;
		${$newthreadid}{'replies'}      = 0;
		${$newthreadid}{'views'}        = 0;
		${$newthreadid}{'lastposter'}   = $iamguest ? qq~Guest-$name~ : $username;
		${$newthreadid}{'lastpostdate'} = $newthreadid;
		${$newthreadid}{'threadstatus'} = $mstate;

		&MessageTotals("update", $newthreadid);
		if ($enable_notification && -e "$boardsdir/$currentboard.mail") {
			$subject = &Censor($subject);
			&NewNotify($newthreadid, $subject);
		}

	} else {
		# This is an old thread. Save it.
		# first load the current ctb info on this existing thread.
		&MessageTotals("load", $threadid);

		# Check if thread has moved. And do necessary access check
		if (${$threadid}{'board'} ne $currentboard) {
			unless (&AccessCheck(${$threadid}{'board'}, 2) eq "granted") { &fatal_error("no_perm_reply"); }

			# Thread has moved, but we can still post
			# the current board is now the new board.
			$currentboard = ${$threadid}{'board'};
		}

		if ($pollthread) { # Save new Poll data
			fopen(POLL, ">$datadir/$threadid.poll");
			print POLL @poll_data;
			fclose(POLL);
		}
		# and save new reply data
		($mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate) = split(/\|/, $yyThreadLine);
		chomp $mstate;
		my $icanbypass;
		## only if bypass switched on
		if ($mstate =~ /l/i && $bypass_lock_perm)	{ $icanbypass = &checkUserLockBypass; }
		if ($mstate =~ /l/i && !$icanbypass) { &fatal_error('topic_locked'); }
		$mreplies = ${$threadid}{'replies'};
		if ($thestatus && ($iammod || $iamgmod || $iamadmin)) { $mstate = "0$thestatus"; }
		# Leave the status alone if the user isn't allowed to change it
		if ($currentboard eq $annboard) { $mstate = '0a'; }
		$mreplies++;
		fopen(BOARDFILE, "+<$boardsdir/$currentboard.txt", 1) || &fatal_error("cannot_open","$boardsdir/$currentboard.txt", 1);
		seek BOARDFILE, 0, 0;
		my @buffer = <BOARDFILE>;
		truncate BOARDFILE, 0;

		for ($i = 0; $i < @buffer; $i++) {
			if ($buffer[$i] =~ m~\A$mnum\|~o) { $buffer[$i] = ""; last; }
		}
		seek BOARDFILE, 0, 0;
		print BOARDFILE qq~$mnum|$msub|$mname|$memail|$date|$mreplies|$musername|$micon|$mstate\n~;
		print BOARDFILE @buffer;
		fclose(BOARDFILE);
		fopen(THREADFILE, ">>$datadir/$threadid.txt") || &fatal_error("cannot_open","$datadir/$threadid.txt", 1);
		print THREADFILE qq~$subject|$name|$email|$date|$username|$icon|0|$user_ip|$message|$ns|||$fixfile\n~;
		fclose(THREADFILE);

		if ($fixfile) {
			fopen(AMP, ">>$vardir/attachments.txt") || &fatal_error("cannot_open","$vardir/attachments.txt");
			print AMP qq~$mnum|$mreplies|$subject|$name|$currentboard|$filesizekb|$date|$fixfile\n~;
			fclose(AMP);
		}

		# update the ctb file for the existing thread with number of replies and lastposter
		${$threadid}{'board'} = $currentboard;
		${$threadid}{'replies'} = $mreplies;
		${$threadid}{'lastposter'} = $iamguest ? qq~Guest-$name~ : $username;
		${$threadid}{'lastpostdate'} = $date;
		${$threadid}{'threadstatus'} = $mstate;

		$subject = &Censor($subject);
		&MessageTotals("update", $threadid);
		&ReplyNotify($threadid, $subject, $mreplies) if $enable_notification;
	}    # end else

	if (!$iamguest) {
		$textareawidth = $FORM{'messagewidth'};
		$textareaheight = $FORM{'messageheight'};
		$textareafont = $FORM{'txtsize'};
		${$uid.$username}{'postlayout'} = qq~$textareaheight|$textareawidth|$textareafont~;
		&UserAccount($username, "update");

		# Increment post count and lastpost date for the member.
		# Check whether zeropost board

		if (!${$uid.$currentboard}{'zero'}) {
			${$uid.$username}{'postcount'}++;
			&UserAccount($username, "update", "lastpost+lastonline");

			if (${$uid.$username}{'position'}) {
				$grp_after = qq~${$uid.$username}{'position'}~;
			} else {
				foreach $postamount (sort { $b <=> $a } keys %Post) {
					if (${$uid.$username}{'postcount'} >= $postamount) {
						($title, undef) = split(/\|/, $Post{$postamount}, 2);
						$grp_after = $title;
						last;
					}
				}
			}
			&ManageMemberinfo("update", $username, '', '', $grp_after, ${$uid.$username}{'postcount'});
		} else {
			&UserAccount($username, "update", "lastpost+lastonline");
		}
	}

	# The thread ID, regardless of whether it's a new thread or not.
	$thread = $newthreadid || $threadid;

	# Let's figure out what page number to show
	$start     = 0;
	$pageindex = int($mreplies / $maxmessagedisplay);
	$start     = $pageindex * $maxmessagedisplay;

	# Mark thread as read for the member.
	&dumplog($currentboard, $date);

	${$uid.$currentboard}{'messagecount'}++;
	unless ($FORM{'threadid'}) {
		${$uid.$currentboard}{'threadcount'}++;
		++$threadcount;
	}
	$myname = $iamguest ? qq~Guest-$name~ : $username;
	${$uid.$currentboard}{'lastposttime'} = $date;
	${$uid.$currentboard}{'lastposter'} = $myname;
	${$uid.$currentboard}{'lastpostid'} = $thread;
	${$uid.$currentboard}{'lastreply'} = $mreplies;
	${$uid.$currentboard}{'lastsubject'} = $doadsubject;
	${$uid.$currentboard}{'lasttopicstate'} = $mstate;
	${$uid.$currentboard}{'lasticon'} = $icon;
	&BoardTotals("update", $currentboard);

	if(!$iamguest) { &Recent_Write("incr", $thread, $username); }

	if ($favorite && !$hasfavorite) {
		require "$sourcedir/Favorites.pl";
		&AddFav($thread, $mreplies, 1);
	}

	if ($notify && !$hasnotify) {
		$INFO{'thread'} = $thread;
		$INFO{'start'}  = $start;
		&Notify2;
	} else {
		&ManageThreadNotify("delete", $thread, $username);
	}

	if ($currentboard eq $annboard) {
		$yySetLocation = qq~$scripturl?virboard=$currentboard;num=$thread/$start#$mreplies~;
	} else {
		$yySetLocation = qq~$scripturl?num=$thread/$start#$mreplies~;
	}

	$start = $mreplies;
	#&template;
	#&exit;
	&redirectexit;
}

# To fix the foreign-language notification email bug
# We load all the notification strings from a given language and store them in memory
sub LoadNotifyMessages {
	my(@languages) = @_;

	unshift(@languages, $language); # Load the current language first
	foreach my $lang (@languages) {
		next if $notifystrings{$lang}{'boardnewtopicnotificationemail'}; # Needed so we don't redefine it inproperly
		$language = $lang;
		&LoadLanguage('Email');
		$notifystrings{$lang} = {
			'boardnewtopicnotificationemail' => $boardnewtopicnotificationemail,
			'boardnotificationemail' => $boardnotificationemail,
			'topicnotificationemail' => $topicnotificationemail,
		};
		&LoadLanguage('Notify');
		$notifysubjects{$lang} = {
			'127' => $notify_txt{'127'},
			'136' => $notify_txt{'136'},
		};
		$notifycharset{$lang} = {
			'emailcharset' => $emailcharset,
		};
		#$yymain .= qq~<br /><b>Loaded language <tt>$lang</tt> (successfully?)</b>\n~;
	}
}

sub NewNotify {
	my(@languages, $actlang);
	my $thisthread = $_[0];
	my $thissubject = $_[1];

	require "$sourcedir/Mailer.pl";

	&ManageMemberinfo("load");
	&ManageBoardNotify("load", $currentboard);
	foreach my $value (sort(values(%theboard))) {
		my ($curlang, undef) = split(/\|/, $value, 2);
		next if $curlang eq $actlang;
		push(@languages, $curlang);
		$actlang = $curlang;
	}
	&LoadNotifyMessages(@languages);

	while (my($curuser, $value) = each(%theboard)) {
		my ($curlang, undef) = split(/\|/, $value, 2);
		if ($curuser ne $username) {
			&UserCheck($curuser, "im_notify");
 			if ($usercheck{'im_notify'}) {
 			    (undef, $curmail, undef) = split(/\|/, $memberinf{$curuser}, 3);
 			    &sendmail($curmail, $notifysubjects{$curlang}{'136'}, &template_email($notifystrings{$curlang}{'boardnewtopicnotificationemail'}, {'subject' => $thissubject, 'num' => $thisthread}), '', $notifycharset{$curlang}{'emailcharset'});
 			}
 		}
	}
	undef %theboard;
	undef %memberinf;
}

sub ReplyNotify {
	my $thisthread = $_[0];
	my $thissubject = $_[1];
	my $page = qq~$_[2]#$_[2]~;

	my (%mailsent, $actlang);
	&ManageMemberinfo("load");
	if (-e "$boardsdir/$currentboard.mail") {
		&ManageBoardNotify("load", $currentboard);
		foreach my $value (sort(values(%theboard))) {
			my($curlang, $notify_type, undef) = split(/\|/, $value);
			next if $curlang eq $actlang;
			push(@languages, $curlang);
			$actlang = $curlang;
		}
		&LoadNotifyMessages(@languages);

		while (my($curuser, $value) = each(%theboard)) {
			my($curlang, $notify_type, undef) = split(/\|/, $value);
			if ($curuser ne $username && $notify_type == 2) {
				&UserCheck($curuser, "im_notify");
 				if ($usercheck{'im_notify'}) {
 				    (undef, $curmail, undef) = split(/\|/, $memberinf{$curuser}, 3);
 				    &sendmail($curmail, $notifysubjects{$curlang}{'127'}, &template_email($notifystrings{$curlang}{'boardnotificationemail'}, {'subject' => $thissubject, 'num' => $thisthread, 'start' => $page}), '', $notifycharset{$curlang}{'emailcharset'});
 				    $mailsent{$curuser} = 1;
 				}
 			}
		}
		undef %theboard;
	}
	if (-e "$datadir/$thisthread.mail") {
		&ManageThreadNotify("load", $thisthread);
		foreach my $value (sort(values(%thethread))) {
			my($curlang, $notify_type);
			($curlang, $notify_type, undef) = split(/\|/, $value);
			next if $curlang eq $actlang;
			push(@languages, $curlang);
			$actlang = $curlang;
		}
		&LoadNotifyMessages(@languages);

		while (my($curuser, $value) = each(%thethread)) {
			my($curlang, $notify_type, $hasviewed) = split(/\|/, $value);
			if ($curuser ne $username && !exists $mailsent{$curuser} && $hasviewed) {
				(undef, $curmail, undef) = split(/\|/, $memberinf{$curuser}, 3);
				my $message = &template_email($notifystrings{$curlang}{'topicnotificationemail'}, {'subject' => $thissubject, 'num' => $thisthread, 'start' => $page});
				&sendmail($curmail, $notifysubjects{$curlang}{'127'}, $message, '', $notifycharset{$curlang}{'emailcharset'});
				$hasviewed = 0;
				$thethread{$curuser} = qq~$curlang|$notify_type|$hasviewed~;
			}
		}
		&ManageThreadNotify("save", $thisthread);
	}
	undef %memberinf;
}


sub doshowthread {
	my ($line, $tempname, $tempdate, $temppost);
	if ($INFO{'start'}) { $INFO{'start'} = "/$INFO{'start'}"; }
	
	if (!@messages && $threadid ne '') {
		fopen(THREADFILE, "$datadir/$threadid.txt") || &fatal_error('cannot_open', "$datadir/$threadid.txt", 1);
		@messages = <THREADFILE>;
		fclose(THREADFILE);
	}

	if (@messages) {
		if (@messages <= $cutamount) { $cutamount = @messages; }
		$yymain .= qq~
	<br /><br />
<table cellspacing="1" cellpadding="4" width="100%" align="center" class="bordercolor" style="table-layout: fixed;">
	<tr><td align="left" class="titlebg" colspan="2">
~;
		$showall = $post_cutts{'3'};

		if (@messages => $cutamount && $showpageall) {
			$showall .= qq~ $post_cutts{'3a'} <a href="$scripturl?action=post;num=$threadid;title=PostReply$INFO{'start'};showall=yes" style="text-decoration: underline;">$post_cutts{'4'}</a> $post_cutts{'5'} ~;
		}

		if ($INFO{'showall'} ne '' || $cutamount eq 'all') {
			$origcutamount = $cutamount;
			$cutamount = $pidtxt{'01'};
			$showall = qq~$post_cutts{'3'} $post_cutts{'3a'} <a href="$scripturl?action=post;num=$threadid;title=PostReply/$INFO{'start'}" style="text-decoration: underline;"> $post_cutts{'4'}</a> $post_cutts{'6'} ~;
		}
		$yymain .= qq~
		<b>$post_txt{'468'} - $post_cutts{'2'} $cutamount $showall</b>
		</td></tr>~;
		if ($tsreverse == 1) { @messages = reverse(@messages); }
		if ($INFO{'showall'} ne '' || $cutamount eq "all") { $cutamount = 1000; }
		for ($amounter; $amounter ne $cutamount; $amounter++) {
			(undef, $temprname, undef, $tempdate, $tempname, undef, undef, undef, $message, $ns) = split(/\|/, $messages[$amounter]);
			$messagedate = $tempdate;
			$tempdate = &timeformat($tempdate);
			$parseflash = 0;
			$message = &Censor($message);

			if ($tempname ne 'Guest' && -e ("$memberdir/$tempname.vars")) { &LoadUser($tempname); }
			if (${$uid.$tempname}{'regtime'}) {
				$registrationdate = ${$uid.$tempname}{'regtime'};
			} else {
				$registrationdate = int(time);
			}
			if (${$uid.$tempname}{'regdate'} && $messagedate > $registrationdate) {
				$displaynamelink = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$tempname}" class="catbg a">${$uid.$tempname}{'realname'}</a>~;
			} elsif ($tempname !~ m~Guest~ && $messagedate < $registrationdate) {
				$displaynamelink = qq~$tempname - $display_txt{'470a'}~;
			} else {
				$displaynamelink = $temprname;
			}

			&wrap;
			$displayname = ${$uid.$tempname}{'realname'};
			if ($enable_ubbc) {
				if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }
				&DoUBBC;
			}
			&ToChars($message);
			&wrap2;
			unless ($message eq '') {
				$yymain .= qq~
<tr><td align="left" class="catbg">
<span class="small">$post_txt{'279'}: $displaynamelink</span></td>
<td class="catbg" align="right">
<span class="small">$post_txt{'280'}: $tempdate</span></td>
</tr>
<tr><td class="windowbg2" colspan="2">
<div style="max-height: 150px; overflow: auto;">
$message
</div>
</td></tr>~;
			}
		}
		$yymain .= "</table>\n";
	} else {
		$yymain .= "<!--no summary-->";
	}
}

## Guest can send a PM to FA
## this is a hybrid broadcast message, with fixed audience of FA
## and some guest posting elements in, where id/email are required.
sub sendGuestPM	{
	if (!$iamguest) { $yySetLocation = $scripturl; &redirectexit; }
	if (!$PMenableGuestButton) { &fatal_error('no_access'); }
	if ($PMenableBm_level == 0) { &fatal_error('no_access'); }

	$INFO{'title'} = 'PostReply';
	$postthread = 2;

	$name_field = qq~      <tr>
    <td class="windowbg" align="left" width="23%"><b>$post_txt{'68'}:</b></td>
    <td class="windowbg" align="left" width="77%"><input type="text" name="name" size="25" value="$FORM{'name'}" maxlength="25" tabindex="2" /></td>
      </tr>~;
	$email_field = qq~      <tr>
    <td class="windowbg" width="23%"><b>$post_txt{'69'}:</b></td>
    <td class="windowbg" width="77%"><input type="text" name="email" size="25" value="$FORM{'email'}" maxlength="40" tabindex="3" /></td>
      </tr>~;

	if ($gpvalid_en) {
		&validation_code;
		$verification_field = $verification eq ''
		? qq~
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'1'}:</b></td>
				<td class="windowbg" width="77%">$showcheck<br /><span class="small">$floodtxt{'casewarning'}</span></td>
			</tr>
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'3'}:</b></td>
				<td class="windowbg" width="77%">
				<input type="text" maxlength="30" name="verification" id="verification" size="30" />
				</td>
			</tr>
		~
		: qq~~;
	}
	$sub = '';
	$settofield = 'subject';
	if ($ENV{'HTTP_USER_AGENT'} =~ /(MSIE) (\d)/) {
		if ($2 >= 7.0) { $iecopycheck = ''; } else { $iecopycheck = qq~ checked="checked"~; }
	}
	$t_title = $display_txt{'guestpost'};
	$submittxt = $post_txt{'105'};
	$destination = 'guestpm2';
	$icon = 'exclamation';
	$is_preview  = 0;
	$post = 'guestpm';
	$prevmain = '';
	$preview = 'preview';
	$yytitle = $display_txt{'guestpost'};
	&Postpage;
	&template;
	&exit;
}


sub sendGuestPM2 {

	if (!$iamguest) { $yySetLocation = $scripturl; &redirectexit; }
	if (!$PMenableGuestButton) { &fatal_error('no_access'); }
	if ($PMenableBm_level == 0) { &fatal_error('no_access'); }
	if ($gpvalid_en) {
		&validation_check($FORM{'verification'});
	}

	# Poster is a Guest then evaluate the legality of name and email
	$FORM{'name'} =~ s/\A\s+//;
	$FORM{'name'} =~ s/\s+\Z//;
	&Preview($post_txt{'75'}) unless ($FORM{'name'} ne '' && $FORM{'name'} ne '_' && $FORM{'name'} ne ' ');
	&Preview($post_txt{'568'}) if (length($FORM{'name'}) > 25);
	&Preview($post_txt{'76'}) if ($FORM{'email'} eq '');
	&Preview("$post_txt{'240'} $post_txt{'69'} $post_txt{'241'}") if ($FORM{'email'} !~ /[\w\-\.\+]+\@[\w\-\.\+]+\.(\w{2,4}$)/);
	&Preview($post_txt{'500'}) if (($FORM{'email'} =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\.$)/) || ($FORM{'email'} !~ /^.+@\[?(\w|[-.])+\.[a-zA-Z]{2,4}|[0-9]{1,4}\]?$/));

	# Get the form values
	$name = $FORM{'name'};
	$email = $FORM{'email'};
	$subject = $FORM{'subject'};
	$message = $FORM{'message'};
	$ns = $FORM{'ns'};
	$threadid = $FORM{'threadid'};
	$posttime = $FORM{'post_entry_time'};
	if ($threadid =~ /\D/) { &fatal_error("only_numbers_allowed"); }

	# Check if poster isn't using a distilled email domain
	&email_domain_check($email);
	$spamdetected = &spamcheck("$name $subject $message");
	${$uid.$username}{'spamcount'} = 0;
	$postspeed = $date - $posttime;
	if (($speedpostdetection && $postspeed < $min_post_speed) || $spamdetected == 1) {
		${$uid.$username}{'spamcount'}++;
		$spam_hits_left_count = $post_speed_count - ${$uid.$username}{'spamcount'};
		if ($spamdetected == 1) { &fatal_error('tsc_alert'); } else { &fatal_error('speed_alert'); }
	}

	## clean name and email - remove | from name and turn any _ to spaces fro amil
	if ($name && $email) {
		&ToHTML($name);
		$tempname = $name;
		$name =~ s/\_/ /g;
		$email =~ s/\|//g;
		&ToHTML($email);
	}

	# Fixes a bug with posting hexed characters.
	$name =~ s~amp;~~g;

	&Preview($post_txt{'75'}) unless ($username || $name);
	&Preview($post_txt{'76'}) unless (${$uid.$username}{'email'} || $email);
	&Preview($post_txt{'77'}) unless ($subject && $subject !~ m~\A[\s_.,]+\Z~);
	&Preview($post_txt{'78'}) unless ($message);

	# Check Message Length Precisely
	my $mess_len = $message;
	$mess_len =~ s/[\r\n ]//ig;
	$mess_len =~ s/&#\d{3,}?\;/X/ig;
	if (length($mess_len) > $MaxMessLen) {
		&Preview($post_txt{'536'} . " " . (length($mess_len) - $MaxMessLen) . " " . $post_txt{'537'});
	}
	undef $mess_len;

	if ($FORM{'preview'}) { &Preview; }
	&spam_protection;

	my $testsub = $subject;
	$testsub =~ s/[\r\n\ ]//g;
	$testsub =~ s/\&nbsp;//g;
	$testsub =~ s/ //g;

	if ($testsub eq '') { fatal_error('useless_post', $testsub); }
	my $testmessage = $message;
	$testmessage =~ s/[\r\n\ ]//g;
	$testmessage =~ s/\&nbsp;//g;
	$testmessage =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
	$testmessage =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
	$testmessage =~ s/\[.*?\]//g;
	if ($testmessage eq '' && $message ne '') { fatal_error('useless_post', $testmessage); }

	&FromHTML($subject);
	&FromChars($subject);
	$convertstr = $subject;
	$convertcut = $set_subjectMaxLength;
	&CountChars;
	$subject = $convertstr;
	&ToHTML($subject);

	$subject =~ s/[\r\n]//g;
	$doadsubject = $subject;
	$message =~ s/\cM//g;
	$message =~ s~\[([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[$1$2\]~g;
	$message =~ s~\[/([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[/$1$2\]~g;
#	$message =~ s~(\w+://[^<>\s\n\"\]\[]+)\n([^<>\s\n\"\]\[]+)~$1\n$2~g;
	&FromChars($message);
	&ToHTML($message);
	$message =~ s~\t~ \&nbsp; \&nbsp; \&nbsp;~g;
	$message =~ s~\n~<br />~g;
	$message =~ s/([\000-\x09\x0b\x0c\x0e-\x1f\x7f])/\x0d/g;
	&CheckIcon;

	if (-e ("$datadir/.txt")) { unlink("$datadir/.txt"); }

	# User is Guest, then make sure the chosen name and email is not reserved or used by a member
	if (lc $name eq lc &MemberIndex('check_exist', $name)) { &fatal_error('guest_taken', "($name)"); }
	if (lc $email eq lc &MemberIndex('check_exist', $email)) { &fatal_error('guest_taken', "($email)"); }

	# Find a valid random ID for it
	$newthreadid = &getnewid;
	# Encode spaces in name, to avoid confusing bm
	$name =~ s/ /%20/g;
	$mreplies = 0;

	# set announcement flag according to status of current board
	if(-e "$memberdir/broadcast.messages")	{
		fopen(INBOX, "$memberdir/broadcast.messages");
		@bmessages = <INBOX>;
		fclose(INBOX);
	}
	fopen(INBOX, ">$memberdir/broadcast.messages");
	# new format:  #messageid|from user|touser(s)|(ccuser(s))|(bccuser(s))|
	#    subject|date|message|(parentmid)|(reply#)|ip|
	#		messagestatus|flags|storefolder|attachment
	print INBOX "$newthreadid|$name $email|admin|||$subject|$date|$message|$newthreadid|0|$ENV{'REMOTE_ADDR'}|g|||\n";
	print INBOX @bmessages;
	fclose(INBOX);
	undef @bmessages;

	# The thread ID, regardless of whether it's a new thread or not
	$thread = $newthreadid || $threadid;
	$yySetLocation = $scripturl;
	&redirectexit;
}


sub modAlert {

	if ($iamguest && !$PMAlertButtonGuests) { &fatal_error('not_logged_in'); }
	if (!$iamguest && !$PMenableAlertButton) { &fatal_error('no_access'); }
	if ($currentboard eq '' && !$iamguest) { &fatal_error('no_access'); }
	if ($PM_level == 0 && $PMenableBm_level == 0) { &fatal_error('no_access'); }

	my $quotemsg = $INFO{'quote'};
	$postid = $INFO{'quote'};
	$threadid = $INFO{'num'};
	my ($mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate) = split(/\|/, $yyThreadLine);

	# Determine category
	$curcat = ${$uid.$currentboard}{'cat'};
	&BoardTotals("load", $currentboard);

	# Figure out the name of the category
	unless ($mloaded == 1) { require "$boardsdir/forum.master"; }
	($cat, $catperms) = split(/\|/, $catinfo{$curcat});
	&ToChars($cat);
	
	$INFO{'title'} =~ tr/+/ /;
	$postthread = 2;

	$name_field = $realname eq ''
	  ? qq~      <tr>
    <td class="windowbg" align="left" width="23%"><b>$post_txt{'68'}:</b></td>
    <td class="windowbg" align="left" width="77%"><input type="text" name="name" size="25" value="$FORM{'name'}" maxlength="25" tabindex="2" /></td>
      </tr>~
	  : qq~~;

	$email_field = $realemail eq ''
	  ? qq~      <tr>
    <td class="windowbg" width="23%"><b>$post_txt{'69'}:</b></td>
    <td class="windowbg" width="77%"><input type="text" name="email" size="25" value="$FORM{'email'}" maxlength="40" tabindex="3" /></td>
      </tr>~
	  : qq~~;
	  
	if ($iamguest && $gpvalid_en) {
		&validation_code;
		$verification_field = $verification eq ''
		? qq~
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'1'}:</b></td>
				<td class="windowbg" width="77%">$showcheck<br /><span class="small">$floodtxt{'casewarning'}</span></td>
			</tr>
			<tr>
				<td class="windowbg" width="23%" valign="top"><b>$floodtxt{'3'}:</b></td>
				<td class="windowbg" width="77%">
				<input type="text" maxlength="30" name="verification" id="verification" size="30" />
				</td>
			</tr>
		~
		: qq~~;
	}

	$sub = '';
	$settofield = 'subject';
	if ($threadid ne '') {
		fopen(FILE, "$datadir/$threadid.txt") || &fatal_error('cannot_open', "$datadir/$threadid.txt", 1);
		@messages = <FILE>;
		fclose(FILE);
		if ($quotemsg ne '') {
			($msubject, $mname, $memail, $mdate, $musername, $micon, $mattach, $mip, $mmessage, $mns) = split(/\|/, $messages[$quotemsg]);
			$message = $mmessage;
			$message =~ s~<br>~\n~ig;
			$message =~ s~<br />~\n~g;
			$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;
			if (!$nestedquotes) {
				$message =~ s~\n{0,1}\[quote([^\]]*)\](.*?)\[/quote\]\n{0,1}~\n~isg;
				$message =~ s~\n*\[/*quote([^\]]*)\]\n*~~ig;
			}
			$mname ||= $musername || $post_txt{'470'};
			my $hidename = $musername;
			$hidename = $mname if $musername eq 'Guest';
			$hidename = &cloak($hidename) if $do_scramble_id;
			$quotestart = int($quotemsg / $maxmessagedisplay) * $maxmessagedisplay;
			my $maxlengthofquote = $MaxMessLen - length(qq~[quote author=$hidename link=$threadid/$quotestart#$quotemsg date=$mdate\]\[/quote\]\n~) - 3;
			if(length $message >= $maxlengthofquote) {
				require "$sourcedir/System.pl";
				&LoadLanguage('Error'); &alertbox($error_txt{'quote_too_long'});
				$message = substr($message, 0, $maxlengthofquote) . '...';
			}
			$message    = qq~[quote author=$hidename link=$threadid/$quotestart#$quotemsg date=$mdate\]$message\[/quote\]\n~;
			$msubject =~ s/\bre:\s+//ig;
			if ($mns eq 'NS') { $nscheck = 'checked'; }
		} else {
			($msubject, $mname, $memail, $mdate, $musername, $micon, $mattach, $mip, $mmessage, $mns) = split(/\|/, $messages[0]);
			$msubject =~ s/\bre:\s+//ig;
		}
		$sub = "Re: $msubject";
		$settofield = 'message';
	}
	
	if ($postthread == 2) { $set_subjectMaxLength = $set_subjectMaxLength + 4; } ## this allows replies not to have truncated titles  ;)
	if ($ENV{'HTTP_USER_AGENT'} =~ /(MSIE) (\d)/) {
		if($2 >= 7.0) { $iecopycheck = ''; } else { $iecopycheck = qq~ checked="checked"~; }
	}
	$t_title = $post_txt{'alertmod'};
	$submittxt = $post_txt{'148'};
	$destination = 'modalert2';
	$icon = 'exclamation';
	$is_preview  = 0;
	$post = 'modalert';
	$prevmain = '';
	$preview = 'preview';
	$yytitle = $post_txt{'alertmod'};
	&Postpage;
	&template;
	exit;
}

sub modAlert2	{

	if ($iamguest && !$PMAlertButtonGuests) { &fatal_error('not_logged_in'); }
	if (!$iamguest && !$PMenableAlertButton) { &fatal_error('no_access'); }
	if ($PM_level == 0 && $PMenableBm_level == 0) { &fatal_error('no_access'); }
	if ($iamguest && $gpvalid_en) {
		&validation_check($FORM{'verification'});
	}

	# Get the form values
	$name = $FORM{'name'};
	$email = $FORM{'email'};
	$subject = $FORM{'subject'};
	$message = $FORM{'message'};
	$ns = $FORM{'ns'};
	$threadid = $FORM{'threadid'};
	$postid = $FORM{'postid'};
	$posttime = $FORM{'post_entry_time'};
	if ($threadid =~ /\D/) { &fatal_error('only_numbers_allowed'); }

	if ($iamguest) {
		$name =~ s/\A\s+//;
		$name =~ s/\s+\Z//;
		&Preview($post_txt{'75'}) unless ($name ne '' && $name ne '_' && $name ne ' ');
		&Preview($post_txt{'568'}) if (length($name) > 25);
		&Preview($post_txt{'76'}) if ($email eq '');
		&Preview("$post_txt{'240'} $post_txt{'69'} $post_txt{'241'}") if ($email !~ /[\w\-\.\+]+\@[\w\-\.\+]+\.(\w{2,4}$)/);
		&Preview($post_txt{'500'}) if (($email =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\.$)/) || ($email !~ /^.+@\[?(\w|[-.])+\.[a-zA-Z]{2,4}|[0-9]{1,4}\]?$/));

		## clean name and email - remove | from name and turn any _ to spaces fro amil
		&ToHTML($name);
		$tempname = $name;
		$name =~ s/\_/ /g;
		$email =~ s/\|//g;
		&ToHTML($email);

		# Fixes a bug with posting hexed characters
		$name =~ s~amp;~~g;

		# If user is Guest, then make sure the chosen name and email is not reserved or used by a member
		if (lc $name eq lc &MemberIndex('check_exist', $name)) { &fatal_error('guest_taken',"($name)"); }
		if (lc $email eq lc &MemberIndex('check_exist', $email)) { &fatal_error('guest_taken',"($email)"); }

		# Encode spaces in name, to avoid confusing!
		$name =~ s/ /%20/g;
		$name .= qq~ $email~;
	} else {
		$name = $username;
	}

	# Check if poster isn't using a distilled email domain
	&email_domain_check($email);
	$spamdetected = &spamcheck("$name $subject $message");
	if (!${$uid.$FORM{$username}}{'spamcount'}) { ${$uid.$FORM{$username}}{'spamcount'} = 0; }
	$postspeed = $date - $posttime;
	if (!$iamadmin && !$iamgmod && !$iammod){
		if (($speedpostdetection && $postspeed < $min_post_speed) || $spamdetected == 1) {
			${$uid.$username}{'spamcount'}++;
			${$uid.$username}{'spamtime'} = $date;
			&UserAccount($username,"update");
			$spam_hits_left_count = $post_speed_count - ${$uid.$username}{'spamcount'};
			if ($spamdetected == 1){ &fatal_error('tsc_alert'); } else { &fatal_error('speed_alert'); }
		}
	}

	&Preview($post_txt{'75'}) unless ($username || $name);
	&Preview($post_txt{'76'}) unless (${$uid.$username}{'email'} || $email);
	&Preview($post_txt{'77'}) unless ($subject && $subject !~ m~\A[\s_.,]+\Z~);
	&Preview($post_txt{'78'}) unless ($message);

	# Check Message Length Precisely
	my $mess_len = $message;
	$mess_len =~ s/[\r\n ]//ig;
	$mess_len =~ s/&#\d{3,}?\;/X/ig;
	if (length($mess_len) > $MaxMessLen) {
		&Preview($post_txt{'536'} . " " . (length($mess_len) - $MaxMessLen) . " " . $post_txt{'537'});
	}
	undef $mess_len;

	if ($FORM{'preview'}) { &Preview; }
	&spam_protection;

	my $testsub = $subject;
	$testsub =~ s/[\r\n\ ]//g;
	$testsub =~ s/\&nbsp;//g;
	$testsub =~ s/ //g;

	if ($testsub eq '') { fatal_error('useless_post', $testsub); }
	my $testmessage = $message;
	$testmessage =~ s/[\r\n\ ]//g;
	$testmessage =~ s/\&nbsp;//g;
	$testmessage =~ s~\[table\].*?\[tr\].*?\[td\]~~g;
	$testmessage =~ s~\[/td\].*?\[/tr\].*?\[/table\]~~g;
	$testmessage =~ s/\[.*?\]//g;
	if ($testmessage eq '' && $message ne '') { fatal_error('useless_post', $testmessage); }

	&FromHTML($subject);
	&FromChars($subject);
	$convertstr = $subject;
	$convertcut = $set_subjectMaxLength;
	if ($postthread == 2) { $convertcut += 4; $set_subjectMaxLength += 4; } ## this allows replies not to have truncated titles  ;)
	&CountChars;
	$subject = $convertstr;
	&ToHTML($subject);

	$subject =~ s/[\r\n]//g;
	$doadsubject = $subject;
	$message =~ s/\cM//g;
	$message =~ s~\[([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[$1$2\]~g;
	$message =~ s~\[/([^\]\[]{0,30})\n([^\]\[]{0,30})\]~\[/$1$2\]~g;
#	$message =~ s~(\w+://[^<>\s\n\"\]\[]+)\n([^<>\s\n\"\]\[]+)~$1\n$2~g;
	&FromChars($message);
	&ToHTML($message);
	$message =~ s~\t~ \&nbsp; \&nbsp; \&nbsp;~g;
	$message =~ s~\n~<br />~g;
	$message =~ s/([\000-\x09\x0b\x0c\x0e-\x1f\x7f])/\x0d/g;

	if (-e ("$datadir/.txt")) { unlink("$datadir/.txt"); }
	
	# Find a valid random ID for it
	$newthreadid = &getnewid;

	if ($FORM{'tomods'} ne '') {
		foreach my $toBoardMod (split(/\,/, $FORM{'tomods'})) {
			chomp $toBoardMod;
			# Send message to user
			fopen(INBOX, "$memberdir/$toBoardMod.msg");
			my @inmessages = <INBOX>;
			fclose(INBOX);
			fopen(INBOX, ">$memberdir/$toBoardMod.msg");
			# new format:  #messageid|from user|touser(s)|(ccuser(s))|(bccuser(s))|
			#    subject|date|message|(parentmid)|(reply#)|ip|
			#		messagestatus|flags|storefolder|attachment
			print INBOX "$newthreadid|$name|$toBoardMod|||$subject|$date|$message|$newthreadid|0|$ENV{'REMOTE_ADDR'}|a|u||\n";
			print INBOX @inmessages;
			fclose(INBOX);
		}
	}

	if ($FORM{'tomodgroups'} ne '') {
		# set announcement flag according to status of current board
		fopen(INBOX, "$memberdir/broadcast.messages") || &fatal_error("cannot_open","$memberdir/broadcast.messages");
		my @inmessages = <INBOX>;
		fclose(INBOX);
		fopen(INBOX, ">$memberdir/broadcast.messages");
		# new format:  #messageid|from user|touser(s)|(ccuser(s))|(bccuser(s))|
		#    subject|date|message|(parentmid)|(reply#)|ip|
		#		messagestatus|flags|storefolder|attachment
		print INBOX "$newthreadid|$name|$FORM{'tomodgroups'}|||$subject|$date|$message|$newthreadid|0|$ENV{'REMOTE_ADDR'}|ab|||\n";
		print INBOX @inmessages;
		fclose(INBOX);
	}

	$yySetLocation = qq~$scripturl?num=$threadid/$postid#$postid~;
	&redirectexit;
}


1;
