#############################################################
#  LeoBoard ver.5000 / LB5000 / 雷傲超级论坛 ver.5000
#
#  版权所有: 雷傲工作室(原蓝宝石软件工作室)
#
#  制作人  : 山鹰糊 (Shining Hu)
#            花无缺 (Ifairy Han)
#           
#  主页地址: http://www.CGIer.com/      CGI 编程者之家
#	     http://www.LeoBoard.com/   雷傲论坛支持主页
#	     http://www.leoBBS.com/     本论坛直通车
#            http://maildo.com/      大家一起邮
#            
#############################################################
$versionnumber = "LB5000II v0818a";

$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")); 

sub ipbanned {
	my $term_postipaddress = $ENV{'REMOTE_ADDR'};
	my $term_postipaddress1 = $ENV{'HTTP_X_FORWARDED_FOR'};
	$term_postipaddress = $term_postipaddress1 if (($term_postipaddress1 ne "")&&($term_postipaddress1 ne "unknown"));
	my $trueipaddress1 = $ENV{'HTTP_CLIENT_IP'};
	$term_postipaddress = $trueipaddress1 if (($trueipaddress1 ne "")&&($trueipaddress1 ne "unknown"));
	my $term_filetoopen ="$lbdir" . "data/ipbans.cgi";
	open(FILE,"$term_filetoopen");
	my @term_bannedmembers = <FILE>;  
	close(FILE);
	foreach $term_bannedip (@term_bannedmembers) {
            $term_bannedip =~ s/\r//ig;
	    chomp $term_bannedip;
	    next if ($term_bannedip eq "");
	    if ($term_postipaddress =~ /^$term_bannedip/) { print header(-charset=>gb2312); &error(" IP 被禁止&由于你没遵守本站规定！你的 IP ($term_postipaddress)被禁止！如有疑问，请联系管理员。"); }
	}
}
sub mischeader {
	local($misctype) = @_;
	my $filetoopen = "$lbdir" . "data/allforums.cgi";
	&winlock($filetoopen);
	open(FILE, "$filetoopen") or die "无法定位所需文件！";
	flock (FILE, 1) if ($OS_USED eq "Unix");
	my @forums = <FILE>;
	close(FILE);
	&winunlock($filetoopen);
	foreach my $forumline (@forums) {
	    chomp $forumline;
	    next if ($forumline eq "");
	    (my $tempno, my $trash) = split(/\t/,$forumline);
	    if ($inforum eq $tempno) {
		(my $forumid, my $category, my $categoryplace, $forumname, my $forumdescription, my $forummoderator, my $htmlstate, my $idmbcodestate, my $privateforum, my $startnewthreads, my $lastposter, my $lastposttime, my $threads, my $posts, $forumgraphic, my $ratings, my $misc, my $forumpass, my $hiddenforum, my $indexforum) = split(/\t/,$forumline);
	    }
	}
	$filetoopen = "$lbdir" . "forum$inforum/list.cgi";
	&winlock($filetoopen);
	open(FILE, "$filetoopen");
	flock (FILE, 1) if ($OS_USED eq "Unix");
	my @allthreads = <FILE>;
	close(FILE);
	&winunlock($filetoopen);
	
	foreach my $line (@allthreads) {
	    ($tempno, $trash) = split(/\t/, $line);
	    if ($intopic eq $tempno) {
		($trash, my $topictitle, my $topicdescription, my $threadstate, $trash) = split(/\t/,$line);
	    }
	}
        
	if ($forumgraphic) {
	    $forumgraphic = qq~<a href=$forumsprog?forum=$inforum><img src=$imagesurl/images/$forumgraphic border=0></a>~;
        }
	else {
	    $forumgraphic = qq~<a href=$boardurl/$forumsummaryprog><img src=$imagesurl/images/$boardlogo border=0></a>~;
	}
	&title;
	$inmembername =~ s/\_/ /g;
        $output .= qq~
            <table cellpadding=0 cellspacing=0 border=0 width=$tablewidth align=center>
              <tr>
                <td width=30% rowspan=2 valign=top>
                  $forumgraphic
                </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=$forumsummaryprog>$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=$forumsprog?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=$forumsprog?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>
                $usermenu
              </tr>
            </table>
            <p>
	~;
}
sub title {
	my $newmail = "<p>";  
        if ($mainonoff == 1) { &InMaintenance; } 
	if ($inmembername eq "" || $inmembername eq "客人") {
	    $inmembername = "客人";
	    $loggedinas = qq~<b>客人</b>： <a href="$loginprog?forum=$inforum">登陆</a> | <a href="$registerprog" >注册</a> | <a href="$lostpasswordprog" >忘记密码</a> | <a href="$onlineprog" >在线</a> | <a href="$searchprog" >搜索</a> | <a href="javascript:openScript('$helpprog',500,400)">帮助</a>~;
	    if (($regaccess eq "on")&&($thisprog ne "loginout.cgi")&&($thisprog ne $registerprog)&&($thisprog ne $profileprog)) {
	    	print header(-cookie=>[$namecookie, $passcookie], -charset=>gb2312);
	    	print "<script language='javascript'>document.location = 'loginout.cgi?forum=$inforum'</script>";
	    	exit;
	    }
	}
	else {
	    my $memberfilename = $inmembername;
	    $memberfilename =~ s/ /\_/g;
	    $memberfilename =~ tr/A-Z/a-z/;
            if ((!(-e "$lbdir" . "members/$memberfilename.cgi"))&&($thisprog ne $registerprog)&&($startnewthreads ne "all")){

        	$namecookie = cookie(-name    =>   "amembernamecookie",
			     -path    =>   "$cookiepath/",       
                             -value   =>   "",
                             -expires =>   "");
		$passcookie = cookie(-name    =>   "apasswordcookie",
                             -value   =>   "",
			     -path    =>   "$cookiepath/",
                             -expires =>   "");
        	$namecookie1 = cookie(-name    =>   "amembernamecookie",
			     -path    =>   "/",       
                             -value   =>   "",
                             -expires =>   "");
		$passcookie1 = cookie(-name    =>   "apasswordcookie",
                             -value   =>   "",
			     -path    =>   "/",
                             -expires =>   "");
        	print header(-cookie=>[$namecookie, $passcookie, $namecookie1, $passcookie1], -charset=>gb2312);
            	
            	print "非法登录，你还没有注册呢！<br>刷新此页以客人身份继续浏览！";
            	exit;
            }
	    
	    my $filetoopen = "$lbdir". "messages/$memberfilename" . "_msg.cgi";
	    open (FILE, "$filetoopen");
	    @allmessages = <FILE>;
	    close (FILE);
        
	    $unread = 0;
	    foreach (@allmessages) {
		(my $trash, my $readstate) = split(/\t/,$_);
		$unread++ if ($readstate eq "no");
	    }
	    my $popnew = '<script language="JavaScript">JavaScript:PopWindow()</script>' if (($newmsgpop eq "on")&&($thisprog ne $threadprog));
	    $newmail = qq(<table width=$tablewidth cellpadding=2 cellspacing=0 align=center>
                        <tr>
                          <td align=right>
                            <bgsound src=$imagesurl/images/mail.wav border=0>$popnew
                            <a href="javascript:openScript('$messangerprog?action=inbox',420,320)"><img src=$imagesurl/images/newmail.gif border=0>有新短消息</a>
                          </td>
                      </tr>
                      </table>) if $unread;
	    $loggedinas = qq~$inmembername：<a href=$loginprog?forum=$inforum>重登陆</a> | <a href="javascript:openScript('$messangerprog?action=inbox',420,320)">短消息</a> | <a href="javascript:openScript('friendlist.cgi',420,320)">好友</a> | <a href=$profileprog?action=modify&user=memberfilename>更改信息</a> | <a href="javascript:openScript('$boardurl/$newpostsprog',500,400)">新贴</a> | <a href=$searchprog>搜索</a> | <a href=$onlineprog>在线</a> | <a href="javascript:openScript('$helpprog',500,400)">帮助</a> | <a href=$loginprog?action=logout>退出</a>&nbsp;~;
        }
	&getmember("$inmembername");
	$loggedinas .= qq~| <a href=$adminprog>管理中心</a>~ if (($membercode eq "ad")||($membercode eq "smo"));
	
	if (($thisprog eq $threadprog)||($thisprog eq $forumsprog)) {
	    $loggedinas .= qq~
		<script>
		var tc_user="cnleo";
		var tc_class="2";
		var tc_union="";
		var tc_type="1";
		_dw('<a href=http://www.textclick.com/viewmain.asp?name='+tc_user+' target=_blank><img WIDTH=0 EIGHT=0 src=http://ad.t2t2.com/scripts/stat.dll?default&user='+tc_user+'&refer='+escape(document.referrer)+'&cur=type2 border=0></a>');
		function _dw(string) {document.write(string);}
		</script>
	    ~;
	}
	
	$output = qq~
	    <table width=$tablewidth align=center cellspacing=0 cellpadding=1  border=0 bgcolor=$titleborder>
		<tr><td>
		<table width=100% cellspacing=0 cellpadding=4 border=0>
        	<tr><td bgcolor=$menubackground>
		  <font color=$menufontcolor>
		  >> 欢迎您，$loggedinas 
            	  </font>
        	 </td>
        	 <td bgcolor=$menubackground align=right>
            	  <font color=$titlefont><a href=$homeurl target=_blank><b>返回主页</B></a></font>
        	</td></tr>
		</table>
		</td></tr>
	    </table>
	    $newmail
	~;
	if ($forumlastvisit) {
	    my $flv= $forumlastvisit + ($timedifferencevalue*3600) + ($timezone*3600);
	    my $flongdate = &longdate("$flv");
	    my $fshorttime = &shorttime("$flv");
	    $lastvisitdata = qq~ 最近访问论坛时间： $flongdate $fshorttime~;
	}
	else {
	    $lastvisitdata = qq~>> $forumname欢迎您的到来 <<~;
	}
	$uservisitdata = qq~
	    <tr>
	    <td valign=bottom align=right>
	    <font color=$menufontcolor>
	    <a href=$forumsprog?forum=$inforum&action=resetposts>标记论坛所有内容为已读</a>　 <a href="javascript:openScript('$helpprog?helpon=阅读标记',500,400)"><img src=$imagesurl/images/help_b.gif border=0></a>&nbsp;<br>$lastvisitdata&nbsp;
	    </font>
	    </td></tr>
	~;
}           
sub moderator {
	my $filetoopen = "$lbdir" . "data/allforums.cgi";
	&winlock($filetoopen);
	open(FILE, "$filetoopen") or die "无法定位所需文件！";
	flock (FILE, 1) if ($OS_USED eq "Unix");
	my @forums = <FILE>;
	close(FILE);
	&winunlock($filetoopen);
	foreach my $forumline (@forums) {
	    chomp $forumline;
	    next if ($forumline eq "");
	    (my $tempno, my $trash) = split(/\t/,$forumline);
	    if ($inforum eq $tempno) {
		($trash, $trash, $trash, $trash, $trash, $forummoderator ,$trash, $trash, $trash, $trash) = split(/\t/,$forumline);
	    }
	}
	$forummoderator =~ s/\, /\,/gi;
	$forummoderator =~ s/\, /\,/gi;
	my @forummodnames = split(/\,/, $forummoderator);
	my $totalmods = @forummodnames;
	my $modcount = 1;
	$inmembmod = "no";
	foreach my $name (@forummodnames) {
	    chomp $name;
	    my $cleanedmodname = $name;
	    $cleanedmodname =~ s/ /\_/g;
	    $cleanedmodname =~ tr/A-Z/a-z/;
	    unless ($modcount eq $totalmods) {
		$modoutput .= qq~<a href=$profileprog?action=show&member=$cleanedmodname>$name</a>, ~;
            }
            else {
                $modoutput .= qq~<a href=$profileprog?action=show&member=$cleanedmodname>$name</a>~;
            }
	    $inmembmod = "yes" if (lc($inmembername) eq lc($name));
	    $modcount++
	}
	unless ($inmembmod eq "yes") { $inmembmod = "no"; }
}
sub error {
	my $errorinfo = shift;
	(my $where, my $errormsg) = split(/\&/, $errorinfo);
	$inmembername = cookie("amembernamecookie");
	$inpassword = cookie("apasswordcookie");
	&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/images/$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="$forumsummaryprog">$boardname</a><br>
		　<img src="$imagesurl/images/bar.gif" width=15 height=15><img src=$imagesurl/images/openfold.gif width=15 height=11>　错误： $where
 	    ~;
	}else{
	    $output .= qq~        
		<font color=$fontcolormisc>
		<img src=$imagesurl/images/openfold.gif width=15 height=11>　错误： $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%>
		<tr><td bgcolor=$miscbacktwo align=center><font color=$fontcolormisc><b>错误： $where</b></font></td></tr>
		<tr><td bgcolor=$miscbackone><font color=$fontcolormisc>
                  <b>关于$where错误的详细原因：</b>
                  <ul>
                  <li><b>$errormsg</b>
                  <li>您是否需要查看<a href="javascript:openScript('$helpprog',500,400)">帮助文件</a>? 
                  </ul>
                  <b>产生$where错误的可能原因：</b>
                  <ul>
                  <li>密码错误<li>用户名错误<li>您不是<a href="$registerprog" >注册</a>用户 
                  </ul>
                  <br><br>
                  <center><font color=$fontcolormisc> << <a href="javascript:history.go(-1)">返回上一页</a></center>
                </tr></td>
                </table>
                </td></tr></table>
	~;
        &output(
          -Title   => $boardname, 
          -ToPrint => $output, 
          -Version => $versionnumber 
        );
}
sub getmember {
	$nametocheck = shift;
	$nametocheck =~ s/ /\_/g;
	$nametocheck =~ tr/A-Z/a-z/;
	$userregistered = "";
	undef $filedata;
	$filetoopen = "$lbdir" . "members/$nametocheck.cgi";
	$filetoopen = &stripMETA($filetoopen);
	if (-e $filetoopen) {
	    &winlock($filetoopen);
            open(FILE,"$filetoopen");
            flock(FILE, 1) if ($OS_USED eq "Unix");
            $filedata = <FILE>;
            close(FILE);
	    &winunlock($filetoopen);
	    chomp($filedata);
	    ($membername, $password, $membertitle, $membercode, $numberofposts, $emailaddress, $showemail, $ipaddress, $homepage, $aolname, $icqnumber ,$location ,$interests, $joineddate, $lastpostdate, $signature, $timedifference, $privateforums, $useravatar, $misc1, $misc2, $misc3, $personalavatar, $personalwidth, $personalheight, $rating, $lastgone, $visitno, $addjy, $meili, $mymoney, $postdel, $sex, $education, $marry, $work, $born, $useradd1, $useradd2, $jhmp) = split(/\t/,$filedata);
	    $timedifferencevalue=$timedifference;
	    ($numberofposts, $numberofreplys) = split(/\|/,$numberofposts);
            chomp $privateforums;
            if($privateforums) {
		@private = split(/&/,$privateforums);
		foreach $accessallowed (@private) {
		    chomp $accessallowed;
		    ($access, $value) = split(/=/,$accessallowed);
		    $allowedentry{$access} = $value;
		}
	    }
	}
	else { $userregistered = "no"; }
}

sub uplogintime {
        my($nametocheck,$visit) = @_;
	my $nametochecktemp = $nametocheck;
	$nametocheck =~ s/ /\_/g;
	$nametocheck =~ tr/A-Z/a-z/;
	$userregistered = "";
	my $filetoopen = "$lbdir" . "members/$nametocheck.cgi";
	$filetoopen = &stripMETA($filetoopen);
	if (-e $filetoopen) {
	    &winlock($filetoopen);
	    open(FILE,"$filetoopen");
	    flock (FILE, 1) if ($OS_USED eq "Unix");
            my $filedata = <FILE>;
            close(FILE);
	    chomp($filedata);
	    (my $membername, my $password, my $membertitle, my $membercode, my $numberofposts, my $emailaddress, my $showemail, my $ipaddress, my $homepage, my $aolname, my $icqnumber ,my $location ,my $interests, my $joineddate, my $lastpostdate, my $signature, my $timedifference, my $privateforums, my $useravatar, my $misc1,my  $misc2, my $misc3, 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 $useradd1,my  $useradd2, my $jhmp) = split(/\t/,$filedata);

	    if ($visit eq "T") {
	    	$visitno++; 
           	if ($usertype eq "0") {
     		    if (($membercode eq "rz")||($membercode eq "ad")||($membercode eq "smo")||($membercode eq "mo")) { 
     			$mymoney=$mymoney+$loginmoney; 
     			$meili=$meili+$loginml; 
     		    } 
   		} 
	    } 
	    else { 
		$mymoney=$mymoney+$loginmoney; 
		$meili=$meili+$loginml;
	    }

	    if (($membername ne "")&&($password ne "")) {
	      open(FILE,">$filetoopen");
	      flock (FILE, 2) if ($OS_USED eq "Unix");
	      $lastgone=time;
	      print FILE "$nametochecktemp\t$password\t$membertitle\t$membercode\t$numberofposts\t$emailaddress\t$showemail\t$ipaddress\t$homepage\t$aolname\t$icqnumber\t$location\t$interests\t$joineddate\t$lastpostdate\t$signature\t$timedifference\t$privateforums\t$useravatar\t$misc1\t$misc2\t$misc3\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$useradd1\t$useradd2\t$jhmp\t\n";
	      close(FILE);
	    }
	    &winunlock($filetoopen);
	}
}

sub getmemberstime {
	local($nametocheck) = @_;
	$nametocheck =~ s/ /\_/g;
	$nametocheck =~ tr/A-Z/a-z/;
	my $filetoopen = "$lbdir" . "members/$nametocheck.cgi";
	$filetoopen = &stripMETA($filetoopen);
	if (-e $filetoopen) {
	    &winlock($filetoopen);
	    open(FILE,"$filetoopen");
            flock(FILE, 1) if ($OS_USED eq "Unix");
	    my $filedata = <FILE>;
	    close(FILE);
	    &winunlock($filetoopen);
	    (my $trash, $trash, $trash, $trash, $trash, $trash, $trash, $trash, $trash, $trash, $trash ,$trash ,$trash, $trash, $trash, $trash, $timedifferencevalue, $trash) = split(/\t/,$filedata);
	}
	else { $userregistered = "no"; $timedifferencevalue = 0; }
}
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);
	if ($badwords) {
 	    @pairs = split(/\&/,$badwords);
	    foreach (@pairs) {
		($bad, $good) = split(/=/,$_);
		chop $good;
		$where2 =~ s/$bad/$good/isg;
	    }
	}
	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;
		
	$filetoopen = "$lbdir" . "data/hidden.cgi";
        open (FILE, "$filetoopen");
      	flock(FILE, 1) if ($OS_USED eq "Unix");
        @hiddenmember1 = <FILE>;
        close (FILE);
        unshift (@hiddenmember1,"客人");
	@hiddenmember = @hiddenmember1;
        @hiddenmember = "客人" if ($membercode eq "ad");
                
	undef @onlinedata;
	undef @onlinedata1;
	my $currenttime = time;
	my $userexpire = $currenttime - ($membergone * 60);
	my $memberprinted = "no";
	$osinfo=&osinfo();
	$browseinfo=&browseinfo();
	$screenmode=7 if ($screenmode eq "");

	my $filetoopen = "$lbdir" . "data/onlinedata.cgi";
	&winlock($filetoopen);
	open(FILE,"$filetoopen");
	flock (FILE, 1) if ($OS_USED eq "Unix");
	my @onlinedata1 = <FILE>;
	close(FILE);
        &winunlock($filetoopen);
        my $onlinedatafiles=1 if (-e "$filetoopen");
	my $onlinedatanumber=@onlinedata1;
        
        foreach my $line (@onlinedata1) {
                chomp $line;
                (my $savedusername, my $savedcometime, my $savedtime, my $savedwhere, my $savedipaddress, my $saveosinfo, my $savebrowseinfo, my $savedwhere2, my $fromwhere) = split(/\t/, $line);
 		(my $lookfor, my $no) = split(/\(/,$savedusername);
                next if (((length($savedusername)>12)&&($lookfor ne "客人"))||(length($fromwhere) > 30));
                next if ((length($saveosinfo) > 15)||(length($savebrowseinfo) > 30));

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

		if ($userexpire <= $savedtime) {
                    if (($savedusername eq $tempusername)||(($savedusername eq "客人($ipaddress)")&&($ipall eq $savedipaddress))) {
                         if ((($currenttime - $savedtime) <= $banfreshtime)&&($savedwhere eq $where)&&($savedwhere2 eq $where2)&&(($thisprog eq $postprog)||($thisprog eq $forumsummaryprog)||($thisprog eq $forumsprog)||($thisprog eq $threadprog))) {
                             print header(-charset=>gb2312);
                             print "<BR>服务器忙，请 $banfreshtime 秒后按刷新键继续。<BR><BR>出错原因：你刷新页面过快，或者你打开了过多窗口来浏览本网站。";
                             exit;
                         }
                         if ($memberprinted ne "yes") {
                             $tempdata = "$tempusername\t$savedcometime\t$currenttime\t$where\t$ipall\t$osinfo\t$browseinfo\t$where2\t$fromwhere\t$membercode\t" ;
                             $tempdata =~ s/\n//isg;
                             $fromwhere1 = $fromwhere;
                             push(@onlinedata,$tempdata);
                         }
                         $memberprinted = "yes";
                    }
                    else {
                         $line =~ s/\n//isg;
                         push(@onlinedata,$line);
                    }
                }
                else {
                	&uplogintime("$savedusername","") if (($savedusername !~ /^客人/)&&(($thisprog eq $forumsprog)||($thisprog eq $forumsummaryprog)));
                }
        }
        if ($memberprinted eq "no") {
           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" ;
	   if (($thisprog eq $forumsprog)||($thisprog eq $forumsummaryprog)) {
	     $filetomake = "$lbdir" . "data/stats.cgi";
  	     if (!(-e "$filetomake.lck")) {
	        &winlock($filetomake);
	        open(LOGFILE, ">>$filetomake");
                flock(LOGFILE, 2) if ($OS_USED eq "Unix");
	        print LOGFILE "$currenttime|$browseinfo|$osinfo|$fromwhere|\n";
	        close(LOGFILE);
	        &winunlock($filetomake);
             }
	     
	     $filetomake = "$lbdir" . "data/refers.cgi";
	     $laiyuan = $ENV{'HTTP_REFERER'};
	     if ($noself eq "on") {
	     	$recoder=1;
	     }
	     else {
	        if ($laiyuan =~ m/$homeurl/isg) {
	            $recoder=0;
	        }
	        else {
	            $recoder=1;
	        }
	     }
  	     if ((!(-e "$filetomake.lck"))&&($laiyuan ne "")&&($laiyuan !~ m/unknow /i)&&($laiyuan !~ m/$boardurl/isg)&&($recoder==1)) {
		if (-e "$filetomake") {
	          &winlock($filetomake);
	          open(LOGFILE, "$filetomake");
                  flock(LOGFILE, 1) if ($OS_USED eq "Unix");
	          @refersall= <LOGFILE>;
	          close(LOGFILE);
		  $refersall = @refersall;
      		  if ($refersall<$newrefers) {  $newrefers=$refersall; }  else {  $newrefers--; }
	          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);
	        }
	        else {
	           open(LOGFILE, ">>$filetomake");
	           print LOGFILE "$laiyuan|$ipall|$currenttime|\n";
	           close(LOGFILE);
	        }
             }
           }  
           $fromwhere1 = $fromwhere;
           &uplogintime("$tempusername","T") if ($tempusername !~ /^客人/);
           $tempdata =~ s/\n//isg;
           push(@onlinedata,$tempdata);
        }
        unless (($onlinedatanumber eq 0)&&($onlinedatafiles eq 1)) {
  	  if (!(-e "$filetoopen.lck")) {
	    $onlinedatanum = @onlinedata;
	    &winlock($filetoopen);
	    open(FILE,"$filetoopen");
	    flock (FILE, 1) if ($OS_USED eq "Unix");
	    my @ondatas = <FILE>;
	    close(FILE);
	    $onlinnownum = @ondatas;
	    
	    if ($onlinedatanum > $onlinnownum) { $delmaxuser=int($onlinedatanum/3); } else { $delmaxuser=int($onlinnownum/3); }
	    $delmaxuser = 30 if ($delmaxuser < 30);
	    
	    if (($onlinedatanum > 0)&&(($onlinnownum - $onlinedatanum) < $delmaxuser)) {
                open(FILE,">$filetoopen");
                flock(FILE, 2) if ($OS_USED eq "Unix");
                foreach $line (@onlinedata) {
                    chomp $line;
                    print FILE "$line\n" if ($line ne "");
	    	}
                close(FILE);
            }
            &winunlock($filetoopen);
          }
        }
	if (($thisprog eq $forumsummaryprog)||($thisprog eq $forumsprog)||($thisprog eq $threadprog)) {
	    my $addcountflag = 0;
	    $onlinemax = @onlinedata;
	    foreach $line (@onlinedata1) {
		chomp $line;
		($savedusername, $savedcometime, $savedtime, $savedwhere, $saveipaddress, $saveosinfo, $savebrowseinfo, $savedwhere2, $fromwhere) = split(/\t/, $line);
		if ($tempusername eq $savedusername) {
		    $addcountflag =1;
		    last;
		}
	    }

	    $filetomake = "$lbdir" . "data/counter.cgi";
	    my $countfiles=1 if (-e "$filetomake");
	    
	    &winlock($filetomake);
	    open(FILE,"$filetomake");
	    flock (FILE, 1) if ($OS_USED eq "Unix");
	    my $count = <FILE>;
	    close(FILE);
	    &winunlock($filetomake);

	    ($count1,$count2,$onlinemax1,$onlinemaxtime1) = split(/\t/, $count);
	    $onlinemaxtime = time;
	    $onlinemaxtime1 = time if ($onlinemaxtime1 eq "");
	    $count2++;
	    $count1++ if ($addcountflag == 0);
	    $count1=0 if ($count1 eq "");
	    if ($onlinemax < $onlinemax1) {
	        $onlinemax = $onlinemax1;
	        $onlinemaxtime = $onlinemaxtime1;
	    }
	    unless (($count2 eq 1)&&($countfiles eq 1)) {
	      if (!(-e "$filetomake.lck")) {
	      	if (($count1 ne 0)&&($count2 ne 0)&&($count1 ne "")&&($count2 ne "")&&($onlinemax ne 0)&&($onlinemax <= 2000)) {
	            &winlock($filetomake);
	            open(FILE, ">$filetomake");
	            flock (FILE, 2) if ($OS_USED eq "Unix");
	            print FILE "$count1\t$count2\t$onlinemax\t$onlinemaxtime\t";
	            close(FILE);
	            &winunlock($filetomake);
	        }
	      }
	    }
	}
        undef @onlinedata1;
        if ($method eq "both") {
            $memberoutput ="　";
            $memberoutput1 ="　";
            my $lengthmark= 0;

            foreach my $line (@onlinedata) {
                chomp $line;
                (my $savedusername, my $savedcometime, my $savedtime, my $savedwhere, my $postipaddresstemp, my $saveosinfo, my $savebrowseinfo, my $savedwhere2, my $fromwhere, my $memcod) = split(/\t/, $line);
		if ($memcod eq "ad") {$mspic=0;}
		    elsif ($memcod eq "smo") {$mspic=3;}
		    elsif ($memcod eq "mo")  {$mspic=4;}
		    else  {$mspic=1;}
		    
 		(my $lookfor, my $no) = split(/\(/,$savedusername);
		($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);

		   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 { $postipaddress="已设置保密"; }
		   }
		   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/\"/\\\"/;
  
                my $checkhidden=0;
                if ($lookfor !~/\(/ && $lookfor =~/\)/ ){$lookfor="客人";}  
                my $guestmode=$screenmode*2-1;
                foreach (@hiddenmember){
                if ($_=~/^$lookfor/) {	  
                   $guests++;
                   $checkhidden=1;
                   if ($_ ne "客人") {
		     $memberoutput1 .= qq~<img src=$imagesurl/images/messages2.gif width=12 height=11 alt=请勿打扰！><a href=# nowarp TITLE=\"来访时间：$savedcometime\n活动时间：$savedtime\nＩＰ地址：$savedipaddress\n来源鉴定：$fromwhere\">隐身</a>　~;
                     $memberoutput1 .= qq~<br>　~ if ($guests == int($guests/$guestmode)*$guestmode); 
		    }
		    else {
		     $memberoutput1 .= qq~<img src=$imagesurl/images/messages2.gif width=12 height=11 alt=快注册呀！><a href=# nowarp TITLE=\"目前位置：$savedwhere\n目前动作：$savedwhere2\n来访时间：$savedcometime\n活动时间：$savedtime\n操作系统：$saveosinfo\n浏 览 器：$savebrowseinfo\nＩＰ地址：$savedipaddress\n来源鉴定：$fromwhere\">客人</a>　~;
                     $memberoutput1 .= qq~<br>　~ if ($guests == int($guests/$guestmode)*$guestmode); 
		    }
                }
                }
        
                if ($checkhidden==0) {
                    $members++;
                    my $spaces = "";
                    my $cleanmember = $savedusername;
                    $cleanmember =~ s/ /\_/g;
		    $cleanmember =~ tr/A-Z/a-z/;
                    my $spacetemp= 12 - length($cleanmember);
		    my $spacetemp1 = int($spacetemp/2);
		    $spaces .= " " if ($spacetemp ne $spacetemp1*2);
		    for (my $i=1;$i<=$spacetemp1;$i++) { $spaces .= "　"; }
		    $lengthmark =$lengthmark+4+length($cleanmember);
                    $memberoutput .= qq~<a href="javascript:openScript('messanger.cgi?action=new&touser=$cleanmember',420,320)"><img src="$imagesurl/images/messages$mspic.gif" border=0 width=12 height=11 alt="给$savedusername发送一个短消息"></a><a href="$profileprog?action=show&member=$cleanmember" target=_blank nowarp TITLE=\"目前位置：$savedwhere\n目前动作：$savedwhere2\n来访时间：$savedcometime\n活动时间：$savedtime\n操作系统：$saveosinfo\n浏 览 器：$savebrowseinfo\nＩＰ地址：$savedipaddress\n来源鉴定：$fromwhere\">$savedusername</a>$spaces　~;
		   
		    if ($members == int($members/$screenmode)*$screenmode) {
                        $memberoutput .= qq~<br>　~;
 		    }
                }
            }
    	    $memberoutput1 = "" if (($members > 50)&&($guests > 20));
	    $memberoutput1 = "" if ($memberoutput1 eq "　");
	    $memberoutput = "" if ($memberoutput eq "　");
	
    	    $memberoutput = "$memberoutput<BR>" 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/\&/\&amp;/g;
    $text =~ s/<script>/\&lt;script\&gt;/g;
    $text =~ s/"/\&quot;/g;
    $text =~ s/  / \&nbsp;/g;
    $text =~ s/</\&lt;/g;
    $text =~ s/>/\&gt;/g;
    $text =~ s/\t//g;
    $text =~ s/\r//g;
    $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;/g;
    $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/<script>/\&lt;script\&gt;/g;
    $text =~ s/"/\&quot;/g;
    $text =~ s/  / \&nbsp;/g;
    $text =~ s/</\&lt;/g;
    $text =~ s/>/\&gt;/g;
    $text =~ s/\t//g;
    $text =~ s/\r//g;
    $text =~ s/  / /g;
    $text =~ s/\n\n/<p>/g;
    $text =~ s/\n/<br>/g;
    return $text;
}
sub stripMETA {
    my $file = shift;
    $file =~ s/\&//g;
    $file =~ s/\;//g;  
    $file =~ s/\`//g;
    $file =~ s/\'//g;
    $file =~ s/"//g;
    $file =~ s/\|//g;
    $file =~ s/\*//g;
    $file =~ s/\?//g;
    $file =~ s/<//g;
    $file =~ s/>//g;
    $file =~ s/\^//g;
    $file =~ s/\(//g;
    $file =~ s/\)//g;
    $file =~ s/\[//g;
    $file =~ s/\]//g;
    $file =~ s/\{//g;
    $file =~ s/\}//g;
    $file =~ s/\$//g;
    $file =~ s/\n//g;
    $file =~ s/\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 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年$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);
    $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"; }
    return "$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 joineddate {
    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/$months[$mon]/$mday";
}
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") or die "没有找到 template.cgi 文件！";
        my @templatedata = <FILE>;
        close(FILE);
        my $boardcopyright = qq(&copy\; $copyrightinfo) if $copyrightinfo;
        
        $boardcopyright =~ s/&lt;/</g; $boardcopyright =~ s/&gt;/>/g; $boardcopyright =~ s/&quot;/\"/g;
        my $copyright = qq~
            <center>
        ~;
        if ($thisprog eq $threadprog) {
	    $adscript = &HTML("$adscript");
	    $copyright .= $adscript;
	}
	$copyright .= qq~      
           <hr width=350 size=1>
           <table width=80% align=center cellpadding=0 cellspacing=0>
           <tr><td align=center>
	~;
	
	if ($thisprog eq $threadprog) {
	    $copyright .= qq~
	       <script>
		var tc_user="cnleo";
		var tc_class="2";
		var tc_union="";
		var tc_type="1";
		_dw('<a href=http://www.textclick.com/viewmain.asp?name='+tc_user+' target=_blank><img WIDTH=0 EIGHT=0 src=http://ad.t2t2.com/scripts/stat.dll?default&user='+tc_user+'&refer='+escape(document.referrer)+'&cur=type2 border=0></a>');
		function _dw(string) {document.write(string);}
	       </script>
	    ~;
	}
	
        $copyright .= qq~
           <font color=$fontcolormisc>
           $boardcopyright　 版本： <a href="http://www.leoboard.com/download.htm">$versionnumber</a>
           </font> 
 	   </td></tr></table>
           </center>
        ~;
        foreach my $line (@templatedata) {
            $line =~ s/\$lbbody/$lbbody/sg;
            $line =~ s/\$page_title/$title/sg;
            $line =~ s/\$imagesurl/$imagesurl\/images/sg;
            $line =~ s/\$lbboard_main/$output\n\n$copyright\n/sg;
            $coolwinn = $coolwin?"navigator.userAgent.indexOf('IE 5.5')  > -1":"0";
            $line =~ s/\$coolwin/$coolwinn/isg;
            print $line;
        }
        exit;
}
sub helpfiles {
    my $helptype = shift;
    my $helpurl = qq~<a href="javascript:openScript('help.cgi?helpon=$helptype',500,400)">~;
    return $helpurl;
}
sub getforum {
	my $inforum = shift;
	$filetoopen = "$lbdir" . "data/allforums.cgi";
	&winlock($filetoopen);
	open(FILE, "$filetoopen") or die "文件 allforums.cgi　不存在！";
        flock(FILE, 1) if ($OS_USED eq "Unix");
	@forums = <FILE>;
	close(FILE);
	&winunlock($filetoopen);
	foreach my $forumline (@forums) {
	    chomp $forumline;
	    next if ($forumline eq "");
	    (my $tempno, my $trash) = split(/\t/,$forumline);
	    if ($inforum eq $tempno) {
		($forumid, $category, $categoryplace, $forumname, $forumdescription, $forummoderator ,$htmlstate ,$idmbcodestate ,$privateforum, $startnewthreads ,$lastposter ,$lastposttime, $threads, $posts, $forumgraphic, $ratings, $misc,$forumpass,$hiddenforum,$indexforum) = split(/\t/,$forumline);
	    }
	}
}
sub rebuildLIST {
	my %IN = (
           -Forum  => "",
           @_, 
	); 
 
	$dirtoopen = "$lbdir" . "forum$IN{-Forum}";
	opendir (DIR, "$dirtoopen"); 
	my @dirdata = readdir(DIR);
	closedir (DIR);
	
	my @entry = grep(/\.thd\.cgi$/,@dirdata);
	foreach (@entry) {
	  (my $id, my $tr) = split(/\./,$_);
        
	  my $file = "$lbdir" . "forum$IN{-Forum}/$id.pl";
	  open (TMP, "$file");
	  (my $topicid, my $topictitle, my $topicdescription, my $threadstate, my $threadposts, my $threadviews, my $startedby, my $startedpostdate, my $lastposter, my $lastpostdate, my $posticon1,my $inposttemp) = split (/\t/,<TMP>);
	  close (TMP);

	    $posticon =~ s/\s//isg;
	    if ($posticon =~/<br>/i) {
      		$posticon=~s/<br>/\t/ig;
      		@temppoll = split(/\t/, $posticon);
      		$temppoll = @temppoll;
      		if ($temppoll >1) {
      		    $posticon = "<br>";
      		}
      		else {
      		    $posticon = "";
      		}
	    }
	          
	  my $file1 = "$lbdir" . "forum$IN{-Forum}/$id.thd.cgi";
	  if (($topictitle eq "")||($startedby eq "")||($startedpostdate eq "")||($threadposts eq "")){
	    open (TMP1, "$file1");
	    my @tmp = <TMP1>;
	    close (TMP);
            my $tmp = @tmp;
	    $tmp --;
	    my $tmp1 = $tmp[-1];
	    my $tmp2 = $tmp[0];
	    (my $membername, $topictitle, my $postipaddress, my $showemoticons, my $showsignature, my $postdate, my $post, my $posticon) = split(/\t/,$tmp2);
	    (my $membername1, my $topictitle1, my $postipaddress1, my $showemoticons1, my $showsignature1, my $postdate1, my $post1, $posticon1) = split(/\t/,$tmp1);
	    chomp $posticon;
	    chomp $posticon1;
	    $membername1 = "" if ($tmp eq 0);
	    $threadviews = ($tmp+1) * 8;
	    $postdate1 = $lastpostdate if ($lastpostdate ne "");
	    $inposttemp = $post1;
	    $inposttemp =~ s/\[这个贴子最后由(.+?)编辑\]\n//isg;
	    $inposttemp =~ s/\[quote\](.*)\[quote\](.*)\[\/quote](.*)\[\/quote\]//isg;
	    $inposttemp =~ s/\[quote\]\s*(.*?)\s*\[\/quote\]//isg;
	    $inposttemp =~ s/\[\s*(.*?)\s*\]\s*(.*?)\s*\[\s*(.*?)\s*\]/$2\n/isg;
	    $maxsmailtemp = $maxsmail;
	    $maxsmail     = 0;
	    $inposttemp   = &doemoticons("$inposttemp");
	    $maxsmail     = $maxsmailtemp;
	    $inposttemp =~ s/\<img\s*(.*?)\s*\>//isg;
	    $inposttemp =~ s/\n//isg;
	    $inposttemp =~ s/( )+$//isg;
	    $inposttemp =~ s/^( )+//isg;
	    $inposttemp =~ s/<(.|\n)+?>//g;
	    $inposttemp =~ s/\[.+?\]//g;

	    $posticon =~ s/\s//isg;
	    if ($posticon =~/<br>/i) {
      		$posticon=~s/<br>/\t/ig;
      		@temppoll = split(/\t/, $posticon);
      		$temppoll = @temppoll;
      		if ($temppoll >1) {
      		    $posticon1 = "<br>";
      		}
      		else {
      		    $posticon1 = "";
      		}
	    }
	    $inposttemp = &lbhz($inposttemp,$maxsavepost);
            $posticon = $posticon1 if ($sortposticonshow eq "yes");
	    $rr = ("$postdate1\t$id\t$topictitle\t$topicdescription\t$threadstate\t$tmp\t$threadviews\t$membername\t$postdate\t$membername1\t$posticon\t$inposttemp\t");
	  }else{
   	    $threadviews = ($tmp+1) * 8 if ($threadviews eq "");
   	    $threadviews = 8000 if ($threadviews > 10000);
	    $rr = ("$lastpostdate\t$id\t$topictitle\t$topicdescription\t$threadstate\t$threadposts\t$threadviews\t$startedby\t$startedpostdate\t$lastposter\t$posticon1\t$inposttemp\t");
	  }
	  if ($topictitle ne "") {push (@dat, $rr);}
        }
        @sortdat = sort(@dat); undef @dat;
        @sortdat = reverse(@sortdat);
        my $file = "$lbdir" . "forum$IN{-Forum}/list.cgi";
        &winlock($file) if ($OS_USED eq "Nt");
        open (LIST, ">$file");
        flock (LIST, 2) if ($OS_USED eq "Unix");
        foreach (@sortdat) {
            chomp $_;
            $_ =~ s/\n//isg;
            next if ($_ eq "");
            ($lastpostdate, $topicid, $topictitle, $topicdescription, $threadstate, $threadposts, $threadviews, $startedby, $startedpostdate, $lastposter, $posticon, $posttemp) = split (/\t/,$_);    
            next if ($topicid eq "");
            next if ($topicid !~ /^[0-9]+$/);
            $threadstate = "poll" if (($posticon =~ m/<br>/i)&&($threadstate ne "poll")&&($threadstate ne "pollclosed"));
            if ($threadstate eq "") {$threadstate="open";}
            $posticon = "<BR>" if (($threadstate eq "poll")||($threadstate eq "pollclosed"));
            print LIST "$topicid\t$topictitle\t$topicdescription\t$threadstate\t$threadposts\t$threadviews\t$startedby\t$startedpostdate\t$lastposter\t$lastpostdate\t$posticon\t$posttemp\t\n" unless (!$topictitle);
            undef $posticon; undef $threadstate;
        }
        close (LIST);
        &winunlock($file) if ($OS_USED eq "Nt");
}
sub ipwhere {
    my $fromwhere = shift;    
    my $datapath="$lbdir"."data";
    (my $ip1,my $ip2,my $ip3,my $ip4)=split(/\./,$fromwhere);
    my $ips=$ip1*1000000000+$ip2*1000000+$ip3*1000+$ip4;
    $ip1=int($ip1);
    if (-f "$datapath/$ip1.txt") {
        $datafile=$datapath."/".$ip1.".txt";
    }
    else {
        $datafile=$datapath."/other.txt"; 
    }
    my $from1='';
    my $from2='';
    open(IPF,"$datafile");
    my @ipdata=<IPF>;
    close(IPF);
    for ($i=0;$i<@ipdata;$i++){
        ($ip1,$ip2,$from1,$from2)=split(/__/,$ipdata[$i]);
        (my $ipa1,my $ipa2,my $ipa3,my $ipa4)=split(/\./,$ip1);
        (my $ipb1,my $ipb2,my $ipb3,my $ipb4)=split(/\./,$ip2);
        my $ipbegin =$ipa1*1000000000+$ipa2*1000000+$ipa3*1000+$ipa4;
        my $ipend =$ipb1*1000000000+$ipb2*1000000+$ipb3*1000+$ipb4;
        if (($ips<=$ipend)&&($ips>=$ipbegin)) {
            last;
        }
    }
    if ($from1 eq "") { $fromwhere="未知地区"; }
    else {$fromwhere="$from1$from2";}
    $fromwhere =~ s/\n//isg;
    $fromwhere =~ s/\)//isg;
    $fromwhere =~ s/\(//isg;
    return $fromwhere;
}
sub osinfo {
   local $os="",$Agent;
   $Agent = $ENV{'HTTP_USER_AGENT'};
   if (($Agent =~ /win/i)&&($Agent =~ /95/i)) {
      $os="Windows 95";
   }
   elsif (($Agent =~ /win 9x/i)&&($Agent =~ /4.90/i)) {
      $os="Windows ME";
   }
   elsif (($Agent =~ /win/i)&&($Agent =~ /98/i)) {
      $os="Windows 98";
   }
   elsif (($Agent =~ /win/i)&&($Agent =~ /nt 5\.0/i)) {
      $os="Windows 2000";
   }
   elsif (($Agent =~ /win/i)&&($Agent =~ /nt 5\.1/i)) {
      $os="Windows XP";
   }
   elsif (($Agent =~ /win/i)&&($Agent =~ /nt/i)) {
      $os="Windows NT";
   }
   elsif (($Agent =~ /win/i)&&($Agent =~ /32/i)) {
      $os="Windows 32";
   }
   elsif ($Agent =~ /linux/i) {
      $os="Linux";
   }
   elsif ($Agent =~ /unix/i) {
      $os="Unix";
   }
   elsif (($Agent =~ /sun/i)&&($Agent =~ /os/i)) {
      $os="SunOS";
   }
   elsif (($Agent =~ /ibm/isg)&&($Agent =~ /os/isg)) {
      $os="IBM OS/2";
   }
   elsif (($Agent =~ /Mac/i)&&($Agent =~ /PC/i)) {
      $os="Macintosh";
   }
   elsif ($Agent =~ /FreeBSD/i) {
      $os="FreeBSD";
   }
   elsif ($Agent =~ /PowerPC/i) {
      $os="PowerPC";
   }
   elsif ($Agent =~ /AIX/i) {
      $os="AIX";
   }
   elsif ($Agent =~ /HPUX/i) {
      $os="HPUX";
   }
   elsif ($Agent =~ /NetBSD/i) {
      $os="NetBSD";
   }
   elsif ($Agent =~ /BSD/i) {
      $os="BSD";
   }
   elsif ($Agent =~ /OSF1/i) {
      $os="OSF1";
   }
   elsif ($Agent =~ /IRIX/i) {
      $os="IRIX";
   }
  $os = "Unknown"  if ($os eq '');
  $os =~ s/\n//isg;
  $os =~ s/\)//isg;
  $os =~ s/\(//isg;
  return $os;
}
sub browseinfo {
   local $browser="",$browserver="",@Browsers = ("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb"),$Agent,$Part;
   $Agent = $ENV{'HTTP_USER_AGENT'};
   foreach (@Browsers) {
      if ($Agent =~/$_/i) {
         $browser = $_;
         $browserver ="";
      }
   }
   if (($Agent =~ "Mozilla")&&($Agent !~ "MSIE")) {
      $Part =(split(/\(/, $Agent))[0];
      $browserver = (split(/\//, $Part))[1];
      $browserver = (split(/ /,$browserver))[0];
      $browserver =~ s/([\d\.]+)/$1/isg;
      $browserver = " $browserver";
      $browser = "Netscape Navigator";
   }
   if (($Agent =~ "Mozilla")&&($Agent =~ "Opera")) {
      $Part =(split(/\(/, $Agent))[1];
      $browserver = (split(/\)/, $Part))[1];
      $browserver = (split(/ /,$browserver))[2];
      $browserver =~ s/([\d\.]+)/$1/isg;
      $browserver = " $browserver";
      $browser = "Opera";
   }
   if (($Agent =~ "Mozilla")&&($Agent =~ "MSIE")) {
      $Part = (split(/\(/, $Agent))[1];
      $Part = (split(/\;/,$Part))[1];
      $browserver = (split(/ /,$Part))[2];
      $browserver =~ s/([\d\.]+)/$1/isg;
      $browserver = " $browserver";
      $browser = "Internet Explorer";
   }
  if ($browser ne '') {
      $browserver = substr($browserver,0,4) if (length($browserver) > 10);
      $browseinfo = "$browser$browserver";
  }
  else {
      $browseinfo = "Unknown";
  }
  $browseinfo =~ s/\n//isg;
  $browseinfo =~ s/\)//isg;
  $browseinfo =~ s/\(//isg;
  return $browseinfo;
}

sub doemoticons {
	my $post = shift;       
        open (FILE, "${lbdir}data/lbemot.cgi");
        my @emoticondata = <FILE>;
	close (FILE);
	chomp @emoticondata;

        foreach $picture (@emoticondata) {
            $smileyname = $picture;
            $smileyname =~ s/\.gif$//g;
            for (my $i=1;$i<=$maxsmail;$i++) {
                $post =~ s/\:$smileyname\:/\<img src=$imagesurl\/emot\/$picture>/is;
            }
            $post =~ s/ \:$smileyname\://isg;
            $post =~ s/\:$smileyname\://isg;
            $post =~ s/\&nbsp;\:$smileyname\://isg;
      }
        return $post;
}

sub winlock{
    my ($lockfile) = shift;
    my $i = 0;
    while (-e "$lockfile.lck") {
	last if ($i >= 100);
	select(undef,undef,undef,0.1);
	$i++;
    }
    open (LOCKFILE, ">$lockfile.lck");
    close (LOCKFILE);
}
sub winunlock{
    my ($lockfile) = shift;
    chmod(0777,"$lockfile.lck");
    unlink("$lockfile.lck");
}

sub InMaintenance 
{
    if ($@) {
    print header(-charset=>gb2312); print start_html(-title=>"LB5000 出错！");
    print "不能够找到文件：$@\n如果您使用的是 Windows 类操作系统，请在每一个程序中更改 require 的设置，填入绝对路径！";
    print end_html; exit;
	}
$|++;  
                                   # Unbuffer the output
    $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/images/$boardlogo" border=0></td>
           <td valign=middle align=left><font face="$font" color=$fontcolormisc size=2>
           &nbsp;&nbsp;<img src="$imagesurl/images/closedfold.gif" border=0>$boardname&nbsp;&nbsp;-&nbsp;&nbsp;论坛维护中
           </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=>gb2312);
&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) || die "不能建立套接字,$!!\n";
    my $result = connect(sock,$that);
    if ($result != 1) {
	$out="连接远程服务器错误,请检查网络!";	
    } 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.0 By hanwei\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";
	recv(sock,$out,4096,0);
	recv(sock,$out1,4096,0);
	$out=$out.$out1;
	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 "连接远程服务器错误,请检查网络!"){
	    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]";
	    }
	}
    }
}

1;
