#############################################################
#  LeoBoard ver.5000 / LB5000 / 雷傲超級論壇 ver.5000
#
#  版權所有: 雷傲工作室(原藍寶石軟件工作室)
#
#  製作人  : 山鷹糊 (Shining Hu)
#            花無缺 (Ifairy Han)
#
#  首頁網址:     http://www.CGIer.com/      CGI 編程者之家
#	        http://www.LeoBoard.com/   雷傲論壇支援首頁
#	        http://www.leoBBS.com/     本論壇直通車
#
#############################################################
$versionnumber = "LB5000XP v0830";
$maxweiwang = 5 if (($maxweiwang < 5)||($maxweiwang eq ""));
$signaturesplit="aShDFSiod"; 
$wordfilterto = " *** ";
$ENV{'REMOTE_ADDR'} = $ENV{'HTTP_X_FORWARDED_FOR'} if (($ENV{'REMOTE_ADDR'} eq "127.0.0.1")&&($ENV{'HTTP_X_FORWARDED_FOR'} ne "")&&($ENV{'HTTP_X_FORWARDED_FOR'} ne "unknow"));

opendir (DIRS, "$lbdir");
my @files2 = readdir(DIRS);
closedir (DIRS);
my @memdir = grep(/^members/i, @files2);
$memdir = $memdir[0];
my @msgdir = grep(/^messages/i, @files2);
$msgdir = $msgdir[0];

sub temppost {
    my $tmp=shift;
    $tmp =~ s/\#Moderation Mode//isg;
    $tmp =~ s/\[quote\](.*)\[\/quote\]//isg;
    $tmp =~ s/\[post=(.+?)\](.+?)\[\/post\]//isg;
    $tmp =~ s/\[hide\](.+?)\[\/hide\]//isg;
    $tmp =~ s/\[(.+?)\]//isg;
    $tmp =~ s/(http|https|ftp):\/\/(.*?)\.(png|jpg|jpeg|bmp|gif|swf)//isg;
    $tmp =~ s/<(.|\n)+?>//isg;
    $tmp =~ s/\:.{0,20}\://isg;
    $tmp =~ s/[\a\f\n\e\0\r\t]//isg;
    $tmp =~ s/  / /isg;
    $tmp =~ s/^( )+//isg;
    return $tmp;
}

sub dofilter {
    my $infiltermessage=shift;
    my $keepinfiltermessage=$infiltermessage;
    $infiltermessage=&postwordfilter($infiltermessage);
    if ($infiltermessage ne $keepinfiltermessage) { &error("文章有問題&您所發表的文章中也\許\包含了$hk0001些本論壇不允\許\發表的言論，請仔細檢查後，重新發表，謝謝！"); }
    return $infiltermessage;
}

sub postwordfilter {
    my $infiltermessage=shift;
    my $keepinfiltermessage=$infiltermessage;
    &badwordfile if (($badwords eq "")&&($wordfilter eq ""));
    if ($badwords) {
	my @pairs = split(/\&/,$badwords);
	foreach (@pairs) {
	    my ($bad, $good) = split(/=/,$_);
	    chomp $good;
	    $infiltermessage =~ s/$bad/$good/isg;
        }
    }
    if ($wordfilter) { $infiltermessage =~ s/$wordfilter/$wordfilterto/isg; }
    return $infiltermessage;
}

sub badwordfile {
    if (open (FILE, "${lbdir}data/badwords.cgi")) {
	$badwords = <FILE>;
	close (FILE);
	$badwords=~ s/[\a\f\n\e\0\r\t]//ig;
	$badwords=~ s/(\.|\*|\(|\)|\||\\|\/|\?|\+|\[|\])/\\$1/ig;
    }
    else { $badwords = "";}
    
    if (open (FILE, "${lbdir}data/wordfilter.cgi")) {
	$wordfilter = <FILE>;
	close (FILE);
	$wordfilter=~ s/(\.|\*|\(|\)|\||\\|\/|\?|\+|\[|\])/\\$1/ig;
	$wordfilter=~ s/\t/\|/ig;
	$wordfilter=~ s/\|\|/\|/ig;
	$wordfilter=~ s/^\|//ig;
	$wordfilter=~ s/\|$//ig;
    }
    else { $wordfilter = "";}
}

sub ipbanned {
    my $term_filetoopen ="$lbdir" . "data/ipbans.cgi";
    if (open(FILE,"$term_filetoopen")) {
        my @term_bannedmembers = <FILE>;
	close(FILE);
	my $term_bannedmembers = @term_bannedmembers;
	if ($term_bannedmembers > 0) {
	    my $ipaddress  = $ENV{'REMOTE_ADDR'};
	    $trueipaddress = $ENV{'HTTP_X_FORWARDED_FOR'};
	    $trueipaddress = $ipaddress if (($trueipaddress eq "")||($trueipaddress eq "unknown"));
	    my $trueipaddress1 = $ENV{'HTTP_CLIENT_IP'};
	    $trueipaddress = $trueipaddress1 if (($trueipaddress1 ne "")&&($trueipaddress1 ne "unknown"));
	    foreach $term_bannedip (@term_bannedmembers) {
            	$term_bannedip =~ s/\r//ig;
	    	chomp $term_bannedip;
	    	next if ($term_bannedip eq "");
	    	if (($trueipaddress =~ /^$term_bannedip/)||($ipaddress =~ /^$term_bannedip/)) { &error(" IP 被禁止&由於您沒遵守本站規定！您的 IP ($term_postipaddress) 被禁止！如有疑問，請聯絡管理員。"); }
	    }
	}
    }
    $inmembername = $query->cookie("amembernamecookie") if ($inmembername eq "");
    if (($inmembername ne "")&&($inmembername ne "訪客")) {
	my $term_idfiletoopen ="$lbdir" . "data/idbans.cgi";
	if (open(FILE,"$term_idfiletoopen")) {
           $term_idbannedmembers = <FILE>;  
           close(FILE);
           $term_idbannedmembers =~ s/\t/\_/isg;
           $term_idbannedmembers = "\_$term_idbannedmembers";
           $term_idbannedmembers =~ s/\_\_/\_/isg;
	   $term_idbannedmembers =~ s/(\.|\*|\(|\)|\||\\|\/|\?|\+|\[|\])/\\$1/ig;
           $tempinmembername = "\_$inmembername\_";
           if ($term_idbannedmembers =~ /$tempinmembername/i) { &error(" ID 被禁止&由於您沒遵守本站規定！您的 ID ($inmembername) 被禁止！如有疑問，請聯絡管理員。"); }
	}
    }
}

sub title {
    my $newmail = "<p>";
    if ($mainonoff == 1) { &InMaintenance; }
    if ($inmembername eq "" || $inmembername eq "訪客") {
	$inmembername = "訪客";
	$loggedinas = qq~<b>訪客</b>： <a href="loginout.cgi?forum=$inforum" title=從這裡開始進入論壇>登入論壇</a> | <a href="register.cgi" title=註冊了$hk2088能發表文章喔！>會員註冊</a> | <a href="profile.cgi?action=lostpassword" title=好慘啊，忘記密碼登入不了 style="cursor:help">忘記密碼</a> | <a href="whosonline.cgi" title=看看有誰在線上……>線上名單</a> | <a href="search.cgi?forum=$inforum" title=按關鍵字、$hk0155者來搜尋>搜尋文章</a> | <a href="javascript:openScript('help.cgi',500,400)" title=常見問題的解答>使用說明</a>~;
	if (($regaccess eq "on")&&($thisprog ne "loginout.cgi")&&($thisprog ne "register.cgi")&&($thisprog ne "profile.cgi")&&($thisprog ne "viewavatars.cgi")) {
	    print header(-cookie=>[$namecookie, $passcookie], -charset=>big5);
	    print "<script language='javascript'>document.location = 'loginout.cgi?forum=$inforum'</script>";
	    exit;
	}
	if(($regpuonoff eq "ontop")&&($thisprog eq "leoboard.cgi")||($regpuonoff eq "oneach")&&($thisprog ne "loginout.cgi")&&($thisprog ne "register.cgi")) {
	    if ($boardlogo =~ /\.swf$/i) {$forumgraphic1 = qq~<PARAM NAME=PLAY VALUE=TRUE><PARAM NAME=LOOP VALUE=TRUE><PARAM NAME=QUALITY VALUE=HIGH><embed src=$imagesurl/myimages/$boardlogo quality=high width=$boardlogow height=$boardlogoh pluginspage="http:\/\/www.macromedia.com\/shockwave\/download\/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application\/x-shockwave-flash"><\/embed>~}
            else {$forumgraphic1 = qq~<img src=$imagesurl/myimages/$boardlogo border=0>~};		
            $popupmsg = qq~請先註冊以避免此視窗出現~ if(!$popupmsg);
            $popupmsg = &HTML("$popupmsg");
	    $loggedinas .=qq~<script language="JavaScript" src="$imagesurl/images/lbpopup.js"></script><div id="lbplocation" style="position: absolute;visibility: hidden;height: 1;width: 1;top: 100;left: 50"><table width=520 height=320 bgcolor=$titleborder style="border: 1 outset $miscbackone"><tr><td><table width=490 height=290 bgcolor=$menubackground align=center style="border: 1 inset $miscbacktwo"><tr><td align=center valign=middle><a href=leoboard.cgi>$forumgraphic1</a><br>$popupmsg<br><br><b><a href=register.cgi title=按這裡進行註冊><U>註 冊</U></a> 　 <a href=loginout.cgi?forum=$inforum title=從這裡開始進入論壇><U>登 入</U></a></b><p>(此視窗將於 5 秒後自動關閉)</td></tr></table></td></tr></table></div>~;
	}
    }
    else {
    	if (($thisprog eq "leoboard.cgi")||($thisprog eq "leoboard.cgi")||($thisprog eq "topic.cgi")) {
	    my $memberfilename = $inmembername;
	    $memberfilename =~ s/ /\_/g;
	    $memberfilename =~ tr/A-Z/a-z/;
	    my $filetoopen = "$lbdir". "$msgdir/in/$memberfilename" . "_msg.cgi";
	    open (MSGIN, "$filetoopen");
	    @allmessages = <MSGIN>;
	    close (MSGIN);

   	    my @newmessages=grep(/^＊＃！＆＊(.+)\tno\t/,@allmessages);
   	    $unread = @newmessages;

	    my $intanchumsg = $query->cookie("tanchumsg");
	    my $popnew = '<script>openScript(\'misc.cgi?action=newmsg\',420,320)</script>' if ((($newmsgpop eq "on")||($newmsgpop eq "popup"))&&($intanchumsg eq ""));
	    my $lightnew = qq~<script language="JavaScript">pmBox.bgColor='Lightblue';setInterval("Timer()", 500);x=1;function Timer(){set=1;if(x==0 && set==1){pmBox.bgColor='Lightblue';x=1;set=0;}if(x==1 && set==1){pmBox.bgColor='';x=0;set=0;}}</script>~ if ((($newmsgpop eq "on")||($newmsgpop eq "light")));
	    $newmail = qq(<table width=$tablewidth cellpadding=2 cellspacing=0 align=center><tr><td width="*"></td><td align=right id="pmBox" width=225><bgsound src=$imagesurl/images/mail.wav border=0>$lightnew$popnew<a href="javascript:openScript('messanger.cgi?action=inbox',420,320)"><img src=$imagesurl/images/newmail.gif border=0><font color=$fonthighlight>您有 <B>$unread</B> 條新的私人訊息，請注意查收</font></a></td></tr></table>) if $unread;
	}
	$loggedinas = qq~$inmembername：<a href=loginout.cgi?forum=$inforum>重新登入</a> | <a href="javascript:openScript('messanger.cgi?action=inbox',420,320)" title=密密斟私人訊息中心>私人訊息</a> | <a href="javascript:openScript('friendlist.cgi',420,320)">通訊錄</a> | <a href=profile.cgi?action=modify title=編輯您的個人資料>更改資料</a> | <a href="javascript:openScript('$boardurl/newposts.cgi',500,400)">新文章</a> | <a href=search.cgi?forum=$inforum title=按關鍵字、$hk0155者來搜尋>搜尋文章</a> | <a href=whosonline.cgi title=看看有誰在線上……>線上名單</a> | <a href="javascript:openScript('help.cgi',500,400)" title=常見問題的解答>使用說明</a> | <a href=loginout.cgi?action=logout title=在公眾的地方上網記得要按登出喔><font color=$fonthighlight>登出</font></a>&nbsp;~;
    }
    $pluginadd = "";
    if ($inmembername ne "" && $inmembername ne "訪客" && $thisprog eq "leoboard.cgi") {
	my @fileinfo = stat("${lbdir}data/boardskin.cgi");
	if ((-e "${lbdir}data/boardskin.cgi")&&($fileinfo[7] > 50)) {
	    require "${lbdir}data/boardskin.cgi"; require "${lbdir}addplugin.pl";
	}
    }
    $loggedinas .= qq~| <a href=admincenter.cgi target=_blank>管理中心</a>~ if (($membercode eq "ad")||($membercode eq "smo"));

    if ($headmark ne ""){$headmark=&HTML($headmark);$headmark =~ s/\n/<BR>/isg;}
    if ($footmark ne "") {$footmark=&HTML($footmark);$footmark =~ s/\n/<BR>/isg;}

    if ($menubackpic ne "") { $menubackpic = "background=$imagesurl/myimages/$menubackpic"; }
    $output = qq~$pluginadd<table width=$tablewidth align=center cellspacing=0 cellpadding=1 border=0 bgcolor=$titleborder>$headmark<tr><td><table width=100% cellspacing=0 cellpadding=4 border=0><tr><td bgcolor=$menubackground $menubackpic><font color=$menufontcolor>>> 歡迎您，$loggedinas </td><td bgcolor=$menubackground align=right $menubackpic><a href=$homeurl target=_blank><img src=$imagesurl/images/gohome.gif width=48 height=16 border=0></a>&nbsp;</td></tr></table></td></tr></table>$newmail~;
    $output .= qq~<base onmouseover="window.status='$statusbar';return true">~ if ($statusbar ne "");
    if ($forumlastvisit) {
	my $fulldate  = &fulldatetime($forumlastvisit+$timedifferencevalue*3600+$timezone*3600);
	$lastvisitdata = qq~ 最近瀏覽論壇時間： $fulldate~;
    }
    else { $lastvisitdata = qq~>> $forumname歡迎您的到來 <<~; }
    $uservisitdata = qq~<tr><td valign=bottom align=right><font color=$menufontcolor><a href=forums.cgi?forum=$inforum&action=resetposts>標記論壇所有內容為已讀</a>  <a href="javascript:openScript('help.cgi?helpon=瀏覽標記',500,400)"><img src=$imagesurl/images/$help_blogo border=0></a>&nbsp;<br>$lastvisitdata&nbsp;</td></tr>~;
}

sub mischeader {
    local($misctype) = @_;
    my $filetoopen = "${lbdir}forum$inforum/foruminfo.cgi";
#    &winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    open(FILE, "$filetoopen");
#    flock (FILE, 1) if ($OS_USED eq "Unix");
    my $forums = <FILE>;
    close(FILE);
#    &winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    ($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum,$teamlogo,$teamurl, $fgwidth, $fgheight, $miscadd3, $miscadd4, $miscad5) = split(/\t/,$forums);
#    if ($#forums < 1) {
#	my $filetoopen = "$lbdir" . "data/allforums.cgi";
#	&winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
#	open(FILE, "$filetoopen");
#	flock (FILE, 1) if ($OS_USED eq "Unix");
#	@forums = <FILE>;
#	close(FILE);
#	&winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
#	foreach (@forums) {
#	    chomp $_;
#	    next if ($_ eq "");
#	    (my $tempno, my $trash) = split(/\t/,$_);
#	    if ($inforum eq $tempno) {
#		($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum,$teamlogo,$teamurl, $fgwidth, $fgheight, $miscadd3, $miscadd4, $miscad5) = split(/\t/,$_);
#		last;
#	    }
#	}
#    }

    if ($forumgraphic) {
        if ($forumgraphic =~ /\.swf$/i) {$forumgraphic1 = qq~<PARAM NAME=PLAY VALUE=TRUE><PARAM NAME=LOOP VALUE=TRUE><PARAM NAME=QUALITY VALUE=HIGH><embed src=$imagesurl/myimages/$forumgraphic quality=high width=$fgwidth height=$fgheight pluginspage="http:\/\/www.macromedia.com\/shockwave\/download\/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application\/x-shockwave-flash"><\/embed>~}
            else {$forumgraphic1 = qq~<img src=$imagesurl/myimages/$forumgraphic border=0>~};
    } else {
        if ($boardlogo =~ /\.swf$/i) {$forumgraphic1 = qq~<PARAM NAME=PLAY VALUE=TRUE><PARAM NAME=LOOP VALUE=TRUE><PARAM NAME=QUALITY VALUE=HIGH><embed src=$imagesurl/myimages/$boardlogo quality=high width=$boardlogow height=$boardlogoh pluginspage="http:\/\/www.macromedia.com\/shockwave\/download\/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application\/x-shockwave-flash"><\/embed>~}
            else {$forumgraphic1 = qq~<img src=$imagesurl/myimages/$boardlogo>~};
    }

    &title;
    $output .= qq~<table cellpadding=0 cellspacing=0 border=0 width=$tablewidth align=center><tr><td width=30% rowspan=2 valign=top>$forumgraphic1</td><td valign=top>~;
    if ($indexforum ne "no") { $output .= qq~<font color=$fontcolormisc> <img src=$imagesurl/images/closedfold.gif width=15 height=11> <a href=leoboard.cgi>$boardname</a><br> <img src=$imagesurl/images/bar.gif width=15 height=15><img src=$imagesurl/images/closedfold.gif width=15 height=11> <a href=forums.cgi?forum=$inforum>$forumname</a><br>  　 <img src=$imagesurl/images/bar.gif width=15 height=15><img src=$imagesurl/images/openfold.gif width=15 height=11> $misctype~; }
                        else { $output .= qq~<font color=$fontcolormisc><img src=$imagesurl/images/closedfold.gif width=15 height=11> <a href=forums.cgi?forum=$inforum>$forumname</a><br><img src=$imagesurl/images/bar.gif width=15 height=15><img src=$imagesurl/images/openfold.gif width=15 height=11> $misctype~; }
    $output .= qq~</td></tr></table><p>~;
}

sub getoneforum {
    my $inforum = shift;
    my $filetoopen = "${lbdir}forum$inforum/foruminfo.cgi";
#    &winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    open(FILE, "$filetoopen");
#    flock (FILE, 1) if ($OS_USED eq "Unix");
    my $forums = <FILE>;
    close(FILE);
#    &winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    ($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum,$teamlogo,$teamurl, $fgwidth, $fgheight, $miscadd3, $miscadd4, $miscad5) = split(/\t/,$forums);
    $forummoderator =~ s/\, /\,/gi;
    $forummoderator =~ s/ \,/\,/gi;
    $forummoderator =~ s/\,$//gi;
    $forummoderator =~ s/^\,//gi;
    my @forummodnames = split(/\,/, $forummoderator);
    $forummodnamestemp = "\,$forummoderator\,";
    my $tempinmembername = "\,$inmembername\,";
    if ($forummodnamestemp =~ /$tempinmembername/i) { $inmembmod = "yes"; } else { $inmembmod = "no"; }
}

sub moderator {
    my $inforum = shift;
    if ($#forums < 1) {
	my $filetoopen = "$lbdir" . "data/allforums.cgi";
	&winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	open(FILE, "$filetoopen");
	flock (FILE, 1) if ($OS_USED eq "Unix");
	@forums = <FILE>;
	close(FILE);
	&winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    }
    my @thisforums=grep(/^$inforum\t/,@forums);
    ($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum,$teamlogo,$teamurl, $fgwidth, $fgheight, $miscadd3, $miscadd4, $miscad5) = split(/\t/,$thisforums[0]);
    $forummoderator =~ s/\, /\,/gi;
    $forummoderator =~ s/ \,/\,/gi;
    $forummoderator =~ s/\,$//gi;
    $forummoderator =~ s/^\,//gi;
    my @forummodnames = split(/\,/, $forummoderator);
    $inmembmod = "no";
    my $modnumber=@forummodnames;
    if ($modnumber ne "0") {
	$modoutput = qq~
<SCRIPT LANGUAGE="JavaScript">
function surfto(list) { var myindex1  = list.selectedIndex; if (myindex1 != 0 & myindex1 != 1) { var newwindow = list.options[myindex1].value; var msgwindow = window.open(newwindow,"",""); }}
</SCRIPT>
<form action="profile.cgi" method=post name="modjump"><img src=$imagesurl/images/team2.gif width=19 height=19 align=absmiddle>
<input type=hidden name=action value=show><select onchange="surfto(this)">
<option>本論壇板主：</option><option>------------</option>
~;
	foreach (@forummodnames) {
	    chomp $_;
	    next if ($_ eq "");
	    my $cleanedmodname = $_;
#	    $cleanedmodname =~ s/ /\_/g;
#	    $cleanedmodname =~ tr/A-Z/a-z/;
	    $inmembmod = "yes" if (lc($inmembername) eq lc($_));
    	    $modoutput .= qq~<option value="profile.cgi?action=show&member=$cleanedmodname">$_</option>~;
	}
	$modoutput .= qq~</select>\n~;
    }
    undef $modnumber;
}

sub getforum {
    my $inforum = shift;
    if ($#forums < 1) {
	my $filetoopen = "$lbdir" . "data/allforums.cgi";
	&winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	open(FILE, "$filetoopen");
        flock(FILE, 1) if ($OS_USED eq "Unix");
	@forums = <FILE>;
	close(FILE);
	&winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
    }
    my @thisforums=grep(/^$inforum\t/,@forums);
    ($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum,$teamlogo,$teamurl, $fgwidth, $fgheight, $miscadd3, $miscadd4, $miscad5) = split(/\t/,$thisforums[0]);
}

sub getmember {
    my $nametocheck = shift;
    $nametocheck =~ s/ /\_/g;
    $nametocheck =~ tr/A-Z/a-z/;
    $userregistered = "";
    undef $filedata;
    my $filetoopen = "$lbdir" . "$memdir/$nametocheck.cgi";
    $filetoopen = &stripMETA($filetoopen);
    if ((-e $filetoopen)&&($nametocheck !~ /^訪客/)) {
	&winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
        open(FILE3,"$filetoopen");
        flock(FILE3, 1) if ($OS_USED eq "Unix");
        my $filedata = <FILE3>;
        close(FILE3);
	&winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	chomp($filedata);
	($membername, $password, $membertitle, $membercode, $numberofposts, $emailaddress, $showemail, $ipaddress, $homepage, $oicqnumber, $icqnumber ,$location ,$interests, $joineddate, $lastpostdate, $signature, $timedifference, $privateforums, $useravatar, $userflag, $userxz, $usersx, $personalavatar, $personalwidth, $personalheight, $rating, $lastgone, $visitno, $addjy, $meili, $mymoney, $postdel, $sex, $education, $marry, $work, $born, $chatlevel, $chattime, $jhmp, $useradd3,$useradd4,$useradd5,$userquestion,$useradd6,$useradd7,$useradd8) = split(/\t/,$filedata);
	($signatureorigin, $signaturehtml) = split(/$signaturesplit/,$signature); 
	$signatureorigin =~ s/<br>/\n/g; 
	$timedifferencevalue = $timedifference;
	($numberofposts, $numberofreplys) = split(/\|/,$numberofposts);
        chomp $privateforums;
        if($privateforums) {
	    @private = split(/&/,$privateforums);
	    foreach (@private) {
		chomp $_;
		($access, $value) = split(/=/,$_);
		$allowedentry{$access} = $value;
	    }
	}
    }
    else { $userregistered = "no"; }
}

sub getmembernolock {
    my $nametocheck = shift;
    $nametocheck =~ s/ /\_/g;
    $nametocheck =~ tr/A-Z/a-z/;
    $userregistered = "";
    undef $filedata;
    my $filetoopen = "$lbdir" . "$memdir/$nametocheck.cgi";
    if ((-e $filetoopen)&&($nametocheck !~ /^訪客/)) {
        open(FILE6,"$filetoopen");
        my $filedata = <FILE6>;
        close(FILE6);
	chomp($filedata);
	($membername, $password, $membertitle, $membercode, $numberofposts, $emailaddress, $showemail, $ipaddress, $homepage, $oicqnumber, $icqnumber ,$location ,$interests, $joineddate, $lastpostdate, $signature, $timedifference, $privateforums, $useravatar, $userflag, $userxz, $usersx, $personalavatar, $personalwidth, $personalheight, $rating, $lastgone, $visitno, $addjy, $meili, $mymoney, $postdel, $sex, $education, $marry, $work, $born, $chatlevel, $chattime, $jhmp, $useradd3,$useradd4,$useradd5,$userquestion,$useradd6,$useradd7,$useradd8) = split(/\t/,$filedata);
	($signatureorigin, $signaturehtml) = split(/$signaturesplit/,$signature); 
	$signatureorigin =~ s/<br>/\n/g; 
	$timedifferencevalue = $timedifference;
	($numberofposts, $numberofreplys) = split(/\|/,$numberofposts);
        chomp $privateforums;
        if($privateforums) {
	    @private = split(/&/,$privateforums);
	    foreach (@private) {
		chomp $_;
		($access, $value) = split(/=/,$_);
		$allowedentry{$access} = $value;
	    }
	}
    }
    else { $userregistered = "no"; }
}

sub error {
    my $errorinfo = shift;
    (my $where, my $errormsg,my $ismsg) = split(/\&/, $errorinfo);
    print header(-charset=>big5);
    if (! $inmembername) { $inmembername = cookie("amembernamecookie"); }
    $inpassword = cookie("apasswordcookie");
    $inmembername =~ s/\///g;
    $inmembername =~ s/\.\.//g;
    $inmembername =~ s/\\//g;
    if ($ismsg ne "msg") {
	&title;
	$output .= qq~<table cellpadding=0 cellspacing=0 border=0 width=$tablewidth align=center><tr><td width=30% rowspan=2 valign=top><img src="$imagesurl/myimages/$boardlogo"></td><td valign=top>~;
        if ($indexforum ne "no") { $output .= qq~<font color=$fontcolormisc> <img src=$imagesurl/images/closedfold.gif width=15 height=11> <a href="leoboard.cgi">$boardname</a><br> <img src=$imagesurl/images/bar.gif width=15 height=15><img src=$imagesurl/images/openfold.gif width=15 height=11> 錯$hk6137： $where~; }
                            else { $output .= qq~<font color=$fontcolormisc><img src=$imagesurl/images/openfold.gif width=15 height=11> 錯$hk6137： $where~; }
	$output .= qq~</td></tr></table><p><table cellpadding=0 cellspacing=0 border=0 width=$tablewidth bgcolor=$tablebordercolor align=center><tr><td><table cellpadding=6 cellspacing=1 border=0 width=100%>~;
    }
    else { $versionnumber="msg"; }

    $output .= qq~<tr><td bgcolor=$miscbacktwo align=center><font color=$fontcolormisc><b>錯$hk6137： $where</b></font></td></tr>
<tr><td bgcolor=$miscbackone><font color=$fontcolormisc>
<b>關於$where錯$hk6137的詳細原因：</b>
<ul><li><b>$errormsg</b>
<li>您是否需要查看<a href="javascript:openScript('help.cgi',500,400)">說明檔案</a>?
</ul><b>產生$where錯$hk6137的可能原因：</b>
<ul><li>密碼錯$hk6137<li>會員名稱錯$hk6137<li>您不是<a href="register.cgi" >註冊</a>會員</ul>
<br><br><center><font color=$fontcolormisc> << <a href="javascript:history.go(-1)">返回上$hk0001頁</a></center>
</tr></td></table></td></tr></table>
~;
    &output( -Title   => $boardname, -ToPrint => $output, -Version => $versionnumber );
    exit;
}

sub uplogintime {
        my($nametocheck,$visit) = @_;
	my $nametochecktemp = $nametocheck;
	$nametocheck =~ s/ /\_/g;
	$nametocheck =~ tr/A-Z/a-z/;
	$userregistered = "";
	my $filetoopen = "$lbdir" . "$memdir/$nametocheck.cgi";
	$filetoopen = &stripMETA($filetoopen);
	if (-e $filetoopen) {
	    &winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	    open(FILE6,"$filetoopen");
	    flock (FILE6, 1) if ($OS_USED eq "Unix");
            my $filedata = <FILE6>;
            close(FILE6);
	    chomp($filedata);
	    (my $membername, my $password, my $membertitle, my $membercode, my $numberofposts, my $emailaddress, my $showemail, my $ipaddress, my $homepage, my $oicqnumber, my $icqnumber ,my $location ,my $interests, my $joineddate, my $lastpostdate, my $signature, my $timedifference, my $privateforums, my $useravatar, my $userflag,my  $userxz, my $usersx, my $personalavatar, my $personalwidth, my $personalheight, my $rating, my $lastgone, my $visitno,my  $addjy,my  $meili, my $mymoney, my $postdel, my $sex, my $education, my $marry, my $work, my $born, my $chatlevel,my  $chattime, my $jhmp,my $useradd3,my $useradd4,my $useradd5,my $userquestion,my $useradd6, my $useradd7, my $useradd8) = split(/\t/,$filedata);

    	    $visitno++ if ($visit eq "T");
	    if (($membername ne "")&&($password ne "")) {
	      if (open(FILE6,">$filetoopen")) {
	      flock (FILE6, 2) if ($OS_USED eq "Unix");
	      $lastgone=time;
	      print FILE6 "$nametochecktemp\t$password\t$membertitle\t$membercode\t$numberofposts\t$emailaddress\t$showemail\t$ipaddress\t$homepage\t$oicqnumber\t$icqnumber\t$location\t$interests\t$joineddate\t$lastpostdate\t$signature\t$timedifference\t$privateforums\t$useravatar\t$userflag\t$userxz\t$usersx\t$personalavatar\t$personalwidth\t$personalheight\t$rating\t$lastgone\t$visitno\t$addjy\t$meili\t$mymoney\t$postdel\t$sex\t$education\t$marry\t$work\t$born\t$chatlevel\t$chattime\t$jhmp\t$useradd3\t$useradd4\t$useradd5\t$userquestion\t$useradd6\t$useradd7\t$useradd8\t\n";
	      close(FILE6);
	      }
	    }
	    &winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	}
}
sub numerically { $a <=> $b }
sub alphabetically { lc($a) cmp lc($b) }
sub whosonline {
	local($instruct) = @_;
	(my $tempusername, my $where, my $method, my $where2) = split(/\t/, $instruct);
	my $ipaddress  = $ENV{'REMOTE_ADDR'};
	$trueipaddress = $ENV{'HTTP_X_FORWARDED_FOR'};
	$trueipaddress = $ipaddress if (($trueipaddress eq "")||($trueipaddress eq "unknown"));
	my $trueipaddress1 = $ENV{'HTTP_CLIENT_IP'};
	$trueipaddress = $trueipaddress1 if (($trueipaddress1 ne "")&&($trueipaddress1 ne "unknown"));
	my $ipall      = "$ipaddress=$trueipaddress";
	my $tempusername1=$tempusername;
	if ($tempusername eq "訪客") {
	    $tempusername = "訪客($ipaddress)";
	}
	$guests  = 0;
	$members = 0;
	$onlineuserlist       = "\_";
	$onlineuserlisthidden = "\_";
	undef @onlinedata;
	undef @onlinedata1;
	$currenttime = time;
	$membergone = 5 if ($membergone< 5);
	$membergone = 60 if ($membergone> 60);
	my $userexpire = $currenttime - ($membergone * 60);
	my $memberprinted = "no";
	$screenmode=9 if ($screenmode eq "");

     my $filetoopen = "$lbdir" . "data/onlinedata.cgi";
     my @fileinfo = stat("$filetoopen");
     my $filelength1 = $fileinfo[7];
        @fileinfo = stat("$filetoopen.cgi");
     my $filelength2 = $fileinfo[7];
     if ((($filelength1 <60)&&($filelength2 > 60)&&($currenttime-$fileinfo[9] <= 300))||(($currenttime-$fileinfo[9] <= 300)&&($filelength2-$filelength1>1200)&&($filelength2<3000))||(($currenttime-$fileinfo[9] <= 300)&&($filelength2 > $filelength1*2)&&($filelength2>3000)&&($filelength2<50000))||(($currenttime-$fileinfo[9] <= 300)&&($filelength2*2 > $filelength1*3)&&($filelength2>50000))) {
	if (open(FILE5,"$filetoopen.cgi")) {
	  @onlinedata1 = <FILE5>;
	  close(FILE5);
	  $onlinedatanumber=@onlinedata1;
	}
     }
     else {
        &winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
        if (open(FILE5,"$filetoopen")) {
	  flock (FILE5, 1) if ($OS_USED eq "Unix");
	  @onlinedata1 = <FILE5>;
	  close(FILE5);
	  $onlinedatanumber=@onlinedata1;
	}
        &winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
     }
     
        foreach my $line (@onlinedata1) {
                chomp $line;
                (my $savedusername, my $savedcometime, my $savedtime, my $savedwhere, my $savedipaddress, my $saveosinfo, my $savebrowseinfo, my $savedwhere2, my $fromwhere, my $savemembercode, $savehidden) = split(/\t/, $line);
 		(my $lookfor, my $no) = split(/\(/,$savedusername);
                next if (((length($savedusername)>12)&&($lookfor ne "訪客"))||($lookfor eq ""));
                $fromwhere = "未知" if (length($fromwhere) > 30);
                $saveosinfo = "未知" if (length($saveosinfo) > 15);
                $savebrowseinfo = "未知" if (length($savebrowseinfo) > 28);
		$lookfor =~ s/[\a\f\n\e\0\r\t\`\~\!\@\#\$\%\^\&\*\(\)\+\=\\\{\}\;\'\:\"\,\.\/\<\>\?\[\]]//isg;

                $savedusername =~ s/\_/ /g;
                $tempusername =~ s/\_/ /g;

		if ($userexpire <= $savedtime) {
		    if (($thisprog eq "topic.cgi")||($thisprog eq "team.cgi")) { if ($savedusername !~ /^訪客/) { if ($savehidden ne 1) { $onlineuserlist = "$onlineuserlist$savedusername\_"; } else { $onlineuserlisthidden = "$onlineuserlisthidden$savedusername\_"; } } }
                    if ((lc($savedusername) eq lc($tempusername))||(($savedusername eq "訪客($ipaddress)")&&($ipall eq $savedipaddress)&&($tempusername =~ /^訪客/))) {
                         if ((($currenttime - $savedtime) <= $banfreshtime - 1)&&($savedwhere eq $where)&&($savedwhere2 eq $where2)&&(($thisprog eq "post.cgi")||($thisprog eq "leoboard.cgi")||($thisprog eq "forums.cgi")||($thisprog eq "topic.cgi")||($thisprog eq "printpage.cgi")||($thisprog eq "whosonline.cgi"))) {
                             print header(-charset=>big5);
                             print "<BR>伺服器忙，請 $banfreshtime 秒後按重新整理鍵$hk4949續。<BR><BR>出錯原因：您重新整理頁面過快，或者您開啟了過多視窗來瀏覽本網站。";
                             exit;
                         }
                         if ($memberprinted eq "no") {
                             $savehidden = $hidden if ($hidden ne "");
                             $tempdata = "$tempusername\t$savedcometime\t$currenttime\t$where\t$ipall\t$saveosinfo\t$savebrowseinfo\t$where2\t$fromwhere\t$membercode\t$savehidden\t" ;
			     $osinfo=$saveosinfo;
	   		     $browseinfo=$savebrowseinfo;
                             $tempdata =~ s/[\a\f\n\e\0\r]//isg;
                             $fromwhere1 = $fromwhere;
                             push(@onlinedata,$tempdata);
                             $memberprinted = "yes";
                         }
                    }
                    else {
                         $line =~ s/[\a\f\n\e\0\r]//isg;
                         push(@onlinedata,$line);
                    }
                }
                else {
                	&uplogintime("$savedusername","") if (($savedusername !~ /^訪客/)&&(($thisprog eq "forums.cgi")||($thisprog eq "leoboard.cgi")));
                }
        }

        if ($memberprinted eq "no") {
	   if (($onlinedatanumber >= $arrowonlinemax)&&($arrowonlinemax > 0)&&($membercode ne "ad")&&($membercode ne "smo")&&($membercode ne "mo")) {
       	      print header(-charset=>big5);
              print "<BR>伺服器忙，已經超出論壇允\許\的最大在線人數。<BR><BR>目前論壇在線 $onlinedatanumber 人，最大允\許\同時在線 $arrowonlinemax 人。";
              exit;
           }
	   require "${lbdir}testinfo.pl";
	   $osinfo=&osinfo();
	   $browseinfo=&browseinfo();
           my $fromwhere = &ipwhere("$trueipaddress");
           my $tempdata = "$tempusername\t$currenttime\t$currenttime\t$where\t$ipall\t$osinfo\t$browseinfo\t$where2\t$fromwhere\t$membercode\t$hidden\t" ;
	   if ((($thisprog eq "forums.cgi")||($thisprog eq "leoboard.cgi"))&&($recordviewstat eq "yes")) {
	     $filetomake = "$lbdir" . "data/stats.cgi";
             my $filetoopens = &lockfilename($filetomake);
  	     if (!(-e "$filetoopens.lck")) {
	        if (open(LOGFILE, ">>$filetomake")) {
	        print LOGFILE "$currenttime|$browseinfo|$osinfo|$fromwhere|\n";
	        close(LOGFILE);
	        }
             }

	     $filetomake = "$lbdir" . "data/refers.cgi";
             $filetoopens = &lockfilename($filetomake);
	     $laiyuan = $ENV{'HTTP_REFERER'};
	     if ($noself eq "on") {
	     	$recoder=1;
	     }
	     else {
	        if ($laiyuan =~ m/$homeurl/isg) { $recoder=0; } else { $recoder=1; }
	     }
  	     if ((!(-e "$filetoopens.lck"))&&($laiyuan ne "")&&($laiyuan !~ m/unknow /i)&&($laiyuan !~ m/$boardurl/isg)&&($recoder==1)) {
		if (-e "$filetomake") {
	          &winlock($filetomake) if ($OS_USED eq "Nt");
	          open(LOGFILE, "$filetomake");
                  flock(LOGFILE, 1) if ($OS_USED eq "Unix");
	          my @refersall= <LOGFILE>;
	          close(LOGFILE);
		  my $refersall = @refersall;
      		  if ($refersall<$newrefers) {  $newrefers=$refersall; }  else {  $newrefers--; }
	          if (open(LOGFILE, ">$filetomake")) {
                  flock(LOGFILE, 2) if ($OS_USED eq "Unix");
                  unless (($noself eq "off")&&($laiyuan =~ m/$homeurl/isg)) {
	              print LOGFILE "$laiyuan|$ipall|$currenttime|\n";
	          }
		  for ($i=0;$i<$newrefers;$i++) {
         	    print LOGFILE $refersall[$i];
      		  }
	          close(LOGFILE);
	          }
	          &winunlock($filetomake) if ($OS_USED eq "Nt");
	        }
	        else {
	           if (open(LOGFILE, ">>$filetomake")) {
	           print LOGFILE "$laiyuan|$ipall|$currenttime|\n";
	           close(LOGFILE);
	           }
	        }
             }
           }
           $fromwhere1 = $fromwhere;
           &uplogintime("$tempusername","T") if ($tempusername !~ /^訪客/);
           $tempdata =~ s/[\a\f\n\e\0\r]//isg;
           push(@onlinedata,$tempdata);
        }

        my $filetoopen = "$lbdir" . "data/onlinedata.cgi";
        $filetoopens = &lockfilename($filetoopen);
  	if (!(-e "$filetoopens.lck")) {
	    &winlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
            if (open(FILE4,">$filetoopen")) {
              flock(FILE4, 2) if ($OS_USED eq "Unix");
              foreach $line (@onlinedata) {
                chomp $line;
                next if ($line eq "");
                (my $fileusername, my $no) = split(/\t/, $line);
                 next if (($fileusername eq "訪客($ipaddress)")&&($memberprinted eq "no")&&($tempusername !~ m/^訪客/));
                 print FILE4 "$line\n";
	      }
              close(FILE4);
            }
            if ($currenttime-$fileinfo[9] >= 200) {
             if (open(FILE4,">$filetoopen.cgi")) {
              flock(FILE4, 2) if ($OS_USED eq "Unix");
              foreach $line (@onlinedata) {
                chomp $line;
                print FILE4 "$line\n" if ($line ne "");
	      }
              close(FILE4);
             }
            }
            &winunlock($filetoopen) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
        }
	if (($thisprog eq "leoboard.cgi")||($thisprog eq "forums.cgi")||($thisprog eq "index.cgi")) {
	    $filetomake = "$lbdir" . "data/counter.cgi";

	    my $countfiles=1 if (-e "$filetomake");

	    $onlinemax = @onlinedata;

	    &winlock($filetomake) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	    open(FILE,"$filetomake");
	    flock (FILE, 1) if ($OS_USED eq "Unix");
	    my $count = <FILE>;
	    close(FILE);
	    &winunlock($filetomake) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));

	    ($count1,$count2,$onlinemax1,$onlinemaxtime1) = split(/\t/, $count);
	    $onlinemaxtime1 = $currenttime if ($onlinemaxtime1 eq "");
	    $count2++;
	    $count1++ if ($memberprinted eq "no");
	    $count1=0 if ($count1 eq "");
	    if ($onlinemax < $onlinemax1) {
	        $onlinemax = $onlinemax1;
	        $onlinemaxtime = $onlinemaxtime1;
	    }
	    else {
	        $onlinemaxtime = $currenttime;
	    }
	    unless (($count2 eq 1)&&($countfiles eq 1)) {
              $filetoopens = &lockfilename($filetomake);
	      if (!(-e "$filetoopens.lck")) {
	      	if (($count1 > 0)&&($count2 > 0)&&($onlinemax > 0)&&($onlinemax <= 5000)) {
	            &winlock($filetomake) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	            if (open(FILE, ">$filetomake")) {
	                flock (FILE, 2) if ($OS_USED eq "Unix");
	                print FILE "$count1\t$count2\t$onlinemax\t$onlinemaxtime\t\n";
	                close(FILE);
	            }
	            &winunlock($filetomake) if (($OS_USED eq "Unix")||($OS_USED eq "Nt"));
	        }
	      }
	    }
	}
        undef @onlinedata1;
        if ($method eq "both") {
            $memberoutput ="";
            $memberoutput1 ="";

            foreach my $line (@onlinedata) {
                chomp $line;
		$line =~ s/＊＃！＆＊//;
                (my $savedusername, my $savedcometime, my $savedtime, my $savedwhere, my $postipaddresstemp, my $saveosinfo, my $savebrowseinfo, my $savedwhere2, my $fromwhere, my $memcod, my $hiddened) = split(/\t/, $line);
		       if ($memcod eq "ad")  {$mspic=$onlineadmin;}
		    elsif ($memcod eq "smo") {$mspic=$onlinesmod;}
		    elsif ($memcod eq "mo")  {$mspic=$onlinemod;}
		    elsif ($memcod eq "rz")  {$mspic=$onlinerz;}
		    else  {$mspic=$onlinemember;}

 		(my $lookfor, my $no) = split(/\(/,$savedusername);
    	    	next if ($lookfor =~ m/[\(\)\*]/);
    	    	next if ($lookfor eq "");
		($savedipaddress,$truepostipaddress) = split(/\=/,$postipaddresstemp);

		$fromwhere = "已設定保密" unless (($pvtip eq "on")||($membercode eq "ad")||(($membercode eq 'smo')&&($smocanseeip eq "no")));

		(my $ip1, my $ip2, my $ip3, my $ip4) = split(/\./,$savedipaddress);
            	$pmipaddress  = $savedipaddress;

		   if ($membercode eq "ad") {
		       $savedipaddress="$ip1.$ip2.$ip3.$ip4";
		   }
		   elsif ($membercode eq "smo") {
			if ($smocanseeip eq "no") { $savedipaddress="$ip1.$ip2.$ip3.$ip4"; }
			else {
			    if ($pvtip eq "on") { $savedipaddress="$ip1.$ip2.$ip3.$ip4"; }
			    else { $savedipaddress="已設定保密"; }
			}
		   }
		   elsif ($membercode eq "mo") {
			if ($pvtip eq "on") { $savedipaddress="$ip1.$ip2.$ip3.*"; }
       			else { $savedipaddress="已設定保密"; }
		   }
		   else {
		       if (($pvtip eq "on")&&($inmembername ne "訪客")) {
			 $savedipaddress="$ip1.$ip2.*.*";
		       }
       		       else { $savedipaddress="已設定保密"; }
		   }
		    $savedcometime = &dateformatshort($savedcometime + ($timezone*3600) + ($timedifferencevalue*3600));
		    $savedtime = &dateformatshort($savedtime + ($timezone*3600) + ($timedifferencevalue*3600));

		    $savedwhere2 =~s/\<a \s*(.*?)\s*\>\s*(.*)/「$2」/isg;
		    $savedwhere2 =~s/\<\/a\>//isg;
		    $savedwhere2 =~s/\<b\>//isg;
		    $savedwhere2 =~s/\<\/b\>//isg;
		    $savedwhere2 =~s/\"/\\\"/;

                if (((($hiddened eq 1)&&($membercode ne "ad"))||($savedusername =~ /^訪客/))&&(lc($savedusername) ne lc($inmembername))) {
		   $XA = $XB =  '';
		   if ((lc($savedusername) eq lc($inmembername))||($savedusername eq "訪客($trueipaddress)")) {
		    	$XA = "<font color=$onlineselfcolor>";
		    	$XB = '</font>';
		   }
		   if ($hiddened eq 1) {
		        $members++;
		        $memberoutput .= qq~<td width=12 align=center><img src=$imagesurl/images/$onlineguest align=absmiddle alt=請勿打擾！></td><td width=108><a href=# nowarp TITLE=\"來訪時間：$savedcometime\n活動時間：$savedtime\nＩＰ位址：$savedipaddress\n來源鑒定：$fromwhere\">$XA隱身會員$XB</a></td>~;
                        $memberoutput .= qq~</tr><tr>~ if ($members == int($members/$screenmode)*$screenmode);
		    }
		    else {
		        $guests++;
		        $memberoutput1 .= qq~<td width=12 align=center><img src=$imagesurl/images/$onlineguest align=absmiddle alt=快註冊呀！></td><td width=108><a href=# nowarp TITLE=\"目前位置：$savedwhere\n目前動$hk0155：$savedwhere2\n來訪時間：$savedcometime\n活動時間：$savedtime\n$hk0155$hk2814系統：$saveosinfo\n瀏 覽 器：$savebrowseinfo\nＩＰ位址：$savedipaddress\n來源鑒定：$fromwhere\">$XA訪客$XB</a></td>~;
                        $memberoutput1 .= qq~</tr><tr>~ if ($guests == int($guests/$screenmode)*$screenmode);
		    }
                }
                else {
                    $members++;
                    my $cleanmember = $savedusername;
#                    $cleanmember =~ s/ /\_/g;
#		    $cleanmember =~ tr/A-Z/a-z/;
	     	    $XA = $XB =  '';
		    if (lc($savedusername) eq lc($inmembername)) {
		    	$XA = "<font color=$onlineselfcolor>";
		    	$XB = '</font>';
		    }
		    if ($hiddened eq 1) { $hiddeninfo = "\n-=> 目前處於隱身狀態 <=-"; } else { $hiddeninfo = ""; }
                    $memberoutput .= qq~<td width=12 align=center><a href="javascript:openScript('messanger.cgi?action=new&touser=$cleanmember',420,320)"><img src=$imagesurl/images/$mspic border=0 align=absmiddle alt="發送$hk0001個私人訊息給 $savedusername"></a></td><td width=108><a href="javascript:O9('$cleanmember')" nowarp TITLE=\"目前位置：$savedwhere\n目前動$hk0155：$savedwhere2\n來訪時間：$savedcometime\n活動時間：$savedtime\n$hk0155$hk2814系統：$saveosinfo\n瀏 覽 器：$savebrowseinfo\nＩＰ位址：$savedipaddress\n來源鑒定：$fromwhere$hiddeninfo\">$XA$savedusername$XB</a></td>~;

		    if ($members == int($members/$screenmode)*$screenmode) {
                        $memberoutput .= qq~</tr><tr>~;
 		    }
                }
            }
	    if ($dispguest eq 3) { $memberoutput1 = ""; }
	    elsif (($dispguest eq 1)||($dispguest eq "")) {
    	        $memberoutput1 = "" if (($members > 50)&&($guests > 20));
    	    }

    	    $memberoutput = "$memberoutput</tr><tr>" if (($memberoutput ne "")&&($memberoutput1 ne ""));
            $memberoutput = "$memberoutput$memberoutput1";
        }
}

sub lbhz{
my($str,$maxlen) = @_;
if (length($str) <= $maxlen){    return $str;    }
if (substr($str,0,$maxlen-4) =~ /^([\000-\177]|[\200-\377][\200-\377])*([\000-\177]|[\200-\377][\200-\377])$/ ){
return substr($str,0,$maxlen-4)." ...";
}else{
return substr($str,0,$maxlen-5)." ...";
}
}

sub cleaninput {
    my $text = shift;
    $text =~ s/\&nbsp;/ /g;
    $text =~ s/\@ARGV/\&\#64\;ARGV/isg;
#    $text =~ s/\;/\&\#59\;/isg;
#    $text =~ s/\&/\&amp;/g;
    $text =~ s/\&amp;\#/\&\#/isg;
    $text =~ s/"/\&quot;/g;
    $text =~ s/  / \&nbsp;/g;
    $text =~ s/</\&lt;/g;
    $text =~ s/>/\&gt;/g;
    $text =~ s/[\a\f\e\0\r\t]//isg;
    $text =~ s/  / /g;
    $text =~ s/\n\n/<p>/g;
    $text =~ s/\n/<br>/g;
    return $text;
}
sub unclean {
    my $text = shift;
    $text =~ s/\&amp;/\&/g;
    $text =~ s/\&quot;/"/g;
    $text =~ s/ \&nbsp;/　/g;
    return $text;
}
sub unHTML {
    my $text = shift;
    $text =~ s/<!--(.|\n)*-->//g;
#    $text =~ s/\&/\&amp;/g;
    $text =~ s/<script>/\&lt;script\&gt;/ig;
    $text =~ s/"/\&quot;/g;
    $text =~ s/  / \&nbsp;/g;
    $text =~ s/</\&lt;/g;
    $text =~ s/>/\&gt;/g;
    return $text;
}
sub HTML {
    my $text = shift;
    $text =~ s/\&amp;/\&/g;
    $text =~ s/\&quot;/"/g;
    $text =~ s/ \&nbsp;/　/g;
    $text =~ s/\&lt;/</g;
    $text =~ s/\&gt;/>/g;
    return $text;
}
sub cleanarea {
    my $text = shift;
    $text =~ s/<!--(.|\n)*-->//g;
#    $text =~ s/\&/\&amp;/g;
    $text =~ s/"/\&quot;/g;
    $text =~ s/  / \&nbsp;/g;
    $text =~ s/</\&lt;/g;
    $text =~ s/>/\&gt;/g;
    $text =~ s/[\a\f\e\0\r\t]//g;
    $text =~ s/  / /g;
    $text =~ s/\n\n/<p>/g;
    $text =~ s/\n/<br>/g;
    return $text;
}
sub stripMETA {
    my $file = shift;
    $file =~ s/[<>\^\(\)\{\}\a\f\n\e\0\r\"\`\&\;\|\*\?]//g;
    return $file;
}
sub dateformat {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    my @months = ('01','02','03','04','05','06','07','08','09','10','11','12');
    $mon = $months[$mon];
    my $ampm = "am";
    if ($hour > 11) { $ampm = "pm"; }
    if ($hour > 12) { $hour = $hour - 12; }
    if ($hour < 10) { $hour = "0$hour"; }
    if ($min  < 10) { $min  = "0$min"; }
    if ($sec  < 10) { $sec  = "0$sec"; }
    if ($mday < 10) { $mday = "0$mday"; }
    $year = $year + 1900;
    return "$year/$mon/$mday $hour:$min$ampm";
}
sub dateformatshort {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    my @months = ('01','02','03','04','05','06','07','08','09','10','11','12');
    $mon = $months[$mon];
    if ($hour < 10) { $hour = "0$hour"; }
    if ($mday < 10) { $mday = "0$mday"; }
    if ($min  < 10) { $min  = "0$min"; }
    if ($sec  < 10) { $sec  = "0$sec"; }
    $year = $year + 1900;
    return "$year/$mon/$mday $hour:$min";
}
sub fulldatetime {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    my @months = ('01','02','03','04','05','06','07','08','09','10','11','12');
    $year = $year + 1900;
    if ($mday < 10) { $mday = "0$mday"; }
    my $ampm = "am";
    if ($hour > 11) { $ampm = "pm"; }
    if ($hour > 12) { $hour = $hour - 12; }
    if ($hour < 10) { $hour = "0$hour"; }
    if ($min  < 10) { $min  = "0$min"; }
    if ($sec  < 10) { $sec  = "0$sec"; }
    return "$year$hk1628$months[$mon]月$mday日 $hour:$min$ampm";
}
sub longdate {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    my @months = ('01','02','03','04','05','06','07','08','09','10','11','12');
    $year = $year + 1900;
    if ($mday < 10) { $mday = "0$mday"; }
    return "$year$hk1628$months[$mon]月$mday日";
}
sub shortdate {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    $mon++;
    if ($mon  < 10) { $mon  = "0$mon"; }
    if ($mday < 10) { $mday = "0$mday"; }
    $year = $year + 1900;
    return "$year/$mon/$mday";
}
sub shorttime {
    my $time = shift;
    (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime($time);
    my $ampm = "am";
    if ($hour > 11) { $ampm = "pm"; }
    if ($hour > 12) { $hour = $hour - 12; }
    if ($hour < 10) { $hour = "0$hour"; }
    if ($min  < 10) { $min  = "0$min"; }
    if ($sec  < 10) { $sec  = "0$sec"; }
    return "$hour:$min$ampm";
}
sub output {
        my %args = ( -Title => "", -ToPrint => "", -Version => "", @_, );
        my $title         = $args{-Title};
        my $output        = $args{-ToPrint};
        my $versionnumber = $args{-Version};
        my $filetoopen = "$lbdir" . "data/template.cgi";
        open(FILE,"$filetoopen");
        my $templatedata=join('',<FILE>);
        close(FILE);
    	my $boardcopyright;
	my $copyright;
	if ($versionnumber ne "msg") {
 	    $boardcopyright = qq(&copy\; $copyrightinfo) if $copyrightinfo;
            $boardcopyright =~ s/&lt;/</g; $boardcopyright =~ s/&gt;/>/g; $boardcopyright =~ s/&quot;/\"/g;
            $copyright = qq~<center>~;
            if (($thisprog eq "topic.cgi")||($thisprog eq "forums.cgi")) {
		if ($useadfoot ne 0) {
		    $adfoot   = &HTML("$adfoot");
		    $adfoot   =~ s/\$imagesurl/$imagesurl/isg;
		}
		else { $adfoot =""; }
	    	$copyright .= $adfoot;
	    }
	    $copyright .= qq~<hr width=380 size=1><table width=80% align=center cellpadding=0 cellspacing=0><tr><td align=center>~;
	    $boardlastinfo =qq~<BR>本論壇言論純屬發表者個人意見，與<font color=$fonthighlight><b> $boardname </b></font>立場無關<br>~ if ($dispboardsm ne "no");
       	    $copyright .= qq~<font color=$fontcolormisc>$boardcopyright　繁體翻譯：<a href="http://www.bbs-hk.com/" title="按此可以下載最新繁體版本的雷傲超級論壇">紫荊論壇</a>　紫荊版本：<a href="http://www.cgier.com/" title="按此可以下載最新簡體版本的雷傲超級論壇">$versionnumber</a><BR><font color=$postfontcolorone>版權所有：<a href="http://www.cgier.com" target=_blank>CGI 編程者之家</a>　翻譯製$hk0155：<a href="http://www.bbs-hk.com/cgi-bin/leoboard.cgi" target=_blank>tinha</a>　程式編寫：<a href="mailto:htc\@263.net">山鷹(糊)</a>、<a href="mailto:info\@cgier.net">花無缺</a></font><BR><img src=$imagesurl/images/none.gif width=0 height=3>$boardlastinfo</font></td></tr></table></center>\n$footmark~;
	}
	else{
	    undef $copyright;
	}

if ($coolclickdisp ne "0") {
    $coolclick = qq~<script language="javaScript" type="text/javascript" SRC="$imagesurl/images/adv.js"></SCRIPT>
<script language="javascript">Adv("","","","<img src=$imagesurl/images/banner.gif alt=雷傲超級論壇 border=0>","雷傲超級論壇 -- 提示資訊");</script>
<script language="javascript">Adv("","");</script>
~;
} else { $coolclick = ""; }

if ($coolwin eq "1") {
$coolwindow = qq~<script language="javaScript" type="text/javascript" SRC="$imagesurl/images/pz_chromeless_2.1.js"></SCRIPT>
<script>
function openScript(theURL, W, H) {
var bIsIE5 = navigator.userAgent.indexOf('IE 5.5')  > -1;
var bIsIE6 = navigator.userAgent.indexOf('IE 6.0')  > -1;
if (bIsIE5 || bIsIE6) {
wname ="Leoboard5000" 
windowCERRARa = "$imagesurl/close_a.gif"  
windowCERRARd = "$imagesurl/close_d.gif"
windowCERRARo = "$imagesurl/close_o.gif"
windowNONEgrf = "$imagesurl/none.gif" 
windowCLOCK = "$imagesurl/clock.gif" 
windowREALtit = "------| Leoboard Windows V2.1 |" 
windowTIT = "<font style=font-size:12px;font-family:Verdana>------| 雷傲論壇 http://www.LeoBoard.com/ |</font>" 
windowBORDERCOLOR = "#000000" 
windowBORDERCOLORsel = "#111111" 
windowTITBGCOLOR = "#D7DCD9" 
windowTITBGCOLORsel = "#FFFFFF" 
winBGCOLOR = "#D7DCD9"
openchromeless(theURL, wname, W, H, windowCERRARa, windowCERRARd, windowCERRARo, windowNONEgrf, windowCLOCK, windowTIT, windowREALtit , windowBORDERCOLOR, windowBORDERCOLORsel, windowTITBGCOLOR, windowTITBGCOLORsel)
}}
</script>
~;
}
else {$coolwindow = "";}
$coolmeta = qq~<META http-equiv="Page-Enter" content="revealTrans(Transition=$cinoption,Duration=$timetoshow)">
<META http-equiv="Page-Exit" content="revealTrans(Transition=$cinoption,Duration=$timetoshow)">~ if ($pagechange eq "yes");

$templatedata=~ s/\$lbbody/$lbbody/;
$templatedata=~ s/\$page_title/$title/;
$templatedata=~ s/\$lbboard_main/$output\n\n$copyright\n/;
$templatedata=~ s/\$coolwin/$coolwindow/;
$templatedata=~ s/\$coolmeta/$coolmeta/;
$templatedata=~ s/\$coolclick/$coolclick/;
$templatedata=~ s/\$imagesurl/$imagesurl\/images/isg;
print $templatedata;
exit;
}

sub helpfiles {
    my $helptype = shift;
    my $helpurl = qq~<a href="javascript:openScript('help.cgi?helpon=$helptype',500,400)">~;
    return $helpurl;
}

sub doemoticons {
    my $post = shift;
    unless ($post =~ /\:.{1,20}\:/) {return ($post);}
    if ($#emoticondata < 1) {
	open (FILE, "${lbdir}data/lbemot.cgi");
        @emoticondata = <FILE>;
	close (FILE);
    }
    chomp @emoticondata;
    $maxsmail = 9 if ($maxsmail > 9);
    foreach (@emoticondata) {
        $_ =~ s/\.gif$//ig;
        next if ($post !~ /\:$_\:/i);
        for (my $i=1;$i<=$maxsmail;$i++) {
            $post =~ s/\:$_\:/\<img src=$imagesurl\/emot\/$_.gif>/is;
            last if ($post !~ /\:$_\:/i);
        }
        last if ($post !~ /\:.{1,20}\:/i);
        $post =~ s/\:$_\://isg;
    }
    return $post;
}

sub lockfilename{
    my ($lockfilename) = shift;
    $lockfilename =~ s/\\/\//isg;
    $lockfilename =~ s/\://isg;
    $lockfilename =~ s/\//\_/isg;
    $lockfilename = "$lbdir" . "lock/$lockfilename";
}

sub winlock{
    my ($lockfile) = shift;
    my $i = 0;
    $lockfile =~ s/\\/\//isg;
    $lockfile =~ s/\://isg;
    $lockfile =~ s/\//\_/isg;
    $lockfile = "$lbdir" . "lock/$lockfile";
    while (-e "$lockfile.lck") {
	last if ($i >= 120);
	select(undef,undef,undef,0.1);
	$i++;
    }
    open (LOCKFILE, ">$lockfile.lck");
    close (LOCKFILE);
}
sub winunlock{
    my ($lockfile) = shift;
    $lockfile =~ s/\\/\//isg;
    $lockfile =~ s/\://isg;
    $lockfile =~ s/\//\_/isg;
    $lockfile = "$lbdir" . "lock/$lockfile";
    unlink("$lockfile.lck");
}

sub InMaintenance {
    $title = "論壇暫時關閉！";
    $line1 = &HTML($line1);
    $line1 =~ s/\n/<BR>/isg;
    $output .= qq~<table cellpadding=0 cellspacing=0 border=0 width=$tablewidth align=center>
<tr><td width=30% rowspan=2><img src="$imagesurl/myimages/$boardlogo" border=0></td><td valign=middle align=left><font face="$font" color=$fontcolormisc size=2>
 <img src="$imagesurl/images/closedfold.gif" border=0>$boardname -- 論壇維護中</td><div align="center"><center><br>
<table border="0" cellpadding="0" cellspacing="0" width="80%" bgcolor="#fdfdfd"><tr><td width="100%">
<p align="center"><b><font  color="#FF0000" size="4"><br>論壇暫時關閉<br><br>現在正在維護，請稍後瀏覽！<br><br><br>
</font><font face="新細明體" color="#FF0000">$line1<br></tr></table></center></div><tr><td valign=bottom align=right>&nbsp; $helpurl</td></tr></table><br>
~;
    print header(-charset=>big5);
    &output( -Title => "$boardname", -ToPrint => $output, -Version => $versionnumber );
    exit;
}

sub lbagent {
    my $out="";
    my $url=shift;
    $url =~ m@http://(.*?)/(.*)@;
    my ($host,$path) = ($1,$2);
    my $port = 80;
    if ($host =~ /(.*):(\d+)/) { $host = $1; $port = $2; }
    my $file;
    if ($path =~ m@.*/(.*)@) { $file = $1; } else { $file = $path; }
    my ($name,$aliases,$addrtype,$len,@addrs) = gethostbyname($host);
    my ($a,$b,$c,$d) = unpack("C4",$addrs[0]);
    my $that = pack('S n C4 x8',2,$port,$a,$b,$c,$d);
    select (sock);
    $|=1;
    select (STDOUT);
    socket(sock,2,1,0);
    my $result = connect(sock,$that);
    if ($result != 1) { $out="error!"; }
    else {
	print sock "GET /$path HTTP/1.1\r\n";
	print sock "Host: $host\r\n";
	print sock "Accept: */*\r\n";
	print sock "User-Agent: LeoBoard Agent 1.1\r\n";
	print sock "Pragma: no-cache\r\n";
	print sock "Cache-Control: no-cache\r\n";
	print sock "Connection: close\r\n";
	print sock "\r\n";
	my @out = <sock>;
	foreach (@out){
	    $out=$out.$_;
	}
	close(sock);
    }
    return $out;
}

sub getoicq {
    my $oicq=shift;
    if ($oicqshow == 0) { return "$imagesurl/images/oicq.gif"; }
      else {
	my $geturl = "http://search.tencent.com/cgi-bin/friend/oicq_find?oicq_no=$oicq";
	my $out    = &lbagent($geturl);
	if ($out eq "error!") { return "$imagesurl/images/oicq.gif"; }
	  else {
	    @str_ary = split(/ShowResult/,$out);
	    @str_ary = split(/<\/script>/,$str_ary[2]);
	    @str_ary = split(/\"\,\"/,$str_ary[0]);
	    if ($str_ary[1] !~ /\.gif$/isg){ return "$imagesurl/images/oicq.gif"; } else { return "$str_ary[1]"; }
	}
    }
}

sub myip {
    my $ipaddress      = $ENV{'REMOTE_ADDR'};
    my $trueipaddress  = $ENV{'HTTP_X_FORWARDED_FOR'};
    $trueipaddress     = $ipaddress if (($trueipaddress eq "")||($trueipaddress eq "unknown"));
    my $trueipaddress1 = $ENV{'HTTP_CLIENT_IP'};
    $trueipaddress     = $trueipaddress1 if (($trueipaddress1 ne "")&&($trueipaddress1 ne "unknown"));
    return "$ipaddress=$trueipaddress";

}
sub makedir {
        my	$mydir=shift;
        unless (-e $mydir) {
			mkdir($mydir,0777);
        }
	    unless (-w $mydir){
		chmod (0777,$mydir);
		}
        undef $mydir;
}

$hk0001 = "一";
$hk0155 = "作";
$hk0756 = "品";
$hk1120 = "外";
$hk1628 = "年";
$hk2088 = "才";
$hk2814 = "業";
$hk3352 = "漢";
$hk3911 = "瓶";
$hk4949 = "繼";
$hk5031 = "羯";
$hk6137 = "誤";
$hk6634 = "途";

1;

#發言處理(有出錯資訊)
#	if (($dofilter eq "yes")||($dofilter eq "all")) {
#	    my $temp = &dofilter("$inpost\t$message");
#	    ($inpost,$message) = split(/\t/,$temp);
#	}

#發言處理(無出錯資訊,直接過濾寫入)
#	if (($dofilter eq "yes")||($dofilter eq "all")) {
#	    my $temp = &postwordfilter("$inpost\t$message");
#	    ($inpost,$message) = split(/\t/,$temp);
#	}

#顯示處理
#	if (($dofilter eq "no")||($dofilter eq "all")) {
#	    my $temp = &postwordfilter("$title\t$msg");
#	    ($title,$msg) = split(/\t/,$temp);
#	}
