<?php
/*
* ===========================================
* 项目: CTB文本论坛
* 版本: 1.3
* 团队: 实易数码
* 小组: CTB文本论坛小组
* 作者: windnets，16hot，险情
* 功能: 常用函数库
* ===========================================
* Copyright (c) 2002
* 团队主页: http://www.11cn.org
* 团队信箱: -------------------
* 创建日期: 2002-4-16
* 修改日期: 2002-10-26
* 修改说明: 代码整理
* 版权声明: 免费软件.
* ===========================================
*/

class CommonClass extends CtbClass
{
	var $set;
	var $tplPath;
	var $siteTitle;
	var $input = array();            //获取全局变量的$_GET变量
    var $sess = array();        //获得全局变量的$_SESSION变量
	var $code = "<?die();?>";

    /*     以下为公共基础函数
	1、  获取模版文件函数：getTemplate($template,$EXT="htm") 
	2、  模版输出函数：outPut($template,$showFooter="y")
	3、  CTB代码 ：ctbCode($msg,$check_url=0,$check_fuhao=0) 
	4、  用户输入数据安全性检查：safeChars($msg) 
	5、  邮箱地址合法性检查：checkEmail($email) 
	6、  获取分页列表：getPage($url,$totalnum) 
	7、  删除文件夹与他下面的文件：delFileValue($path)
	8、  字符串限长函数：keepLen($str,$len)
	9、  获取文件类型：getFileType($type1)
    */

    /*
    * 函数说明： 获取模版文件函数
    * 创建时间： 2002-4-25
    */
	function getTemplate($template,$EXT="htm") 
    {
    	if (!isset($this->templateCache[$template])) {
    		$this->templateCache[$template] = str_replace("\"","\\\"",implode("",file($this->tplPath."/".$template.".".$EXT)));
			$this->openTemplateFile[] = $this->tplPath."/".$template.".".$EXT;
    	}
		return $this->templateCache[$template];
    }// end func

    /*
    * 函数说明： 模版文件替换函数
    * 创建时间： 2002-4-25
    */
	function outPut($template,$showFooter="y")
    {
    	if ($showFooter == "y") {
            $template .= $this->footer();
        }
    	echo $template;
		//ob_end_flush;  // added by cx
    }// end func

    /*
    * 函数说明： CTB代码
    * 创建时间： 2002-4-25
    */
	function ctbCode($msg,$checkUrl=0,$checkFuhao=0) 
    {
        $msg = str_replace("  ", "&nbsp;&nbsp;", $msg);             // 显示连续的空格
        $msg = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $msg); // \t 替换为四个空格
        $msg = str_replace("<br /> ", "<br />&nbsp;", $msg);        // 紧跟 <br /> 后面的空格不转换无法显示
        $msg = str_replace("<br> ", "<br />&nbsp;", $msg);          // 兼容旧版
        $msg = stripslashes($msg);          // 兼容旧版


		//判断是否自动判断url
    	if ($checkUrl == 1) {
			$url_search = array(
				"/(^|[ \n\r\t>])((https?|ftp|gopher|news|telnet|pnm|rtsp|mms):\/\/|www\.)([^ \n\r\t\(\)\^\$!`\"'\|\[\]\{\}<>]*)/i",
				"/(^|[ \n\r\t>])([\da-z][\.\w-]+@[\da-z][\.\w-]+\.[a-z]{2,3})/i",
			);

			$url_parse = array(
				"\\1[url]\\2\\4[/url]",
				"\\1[email]\\2[/email]",
			);
            $msg = preg_replace($url_search, $url_parse, $msg);
       }
        
        //判断是否自动表情转换--此代码可无限制增加
    	if ($checkFuhao == 1) {
			$msg = str_replace(":IBM", ": IBM", $msg);                // added by cx
			$msg = str_replace("&amp;)", "&amp; )", $msg);            // added by cx
			$msg = str_replace('&amp;quot;)', '&amp;quot; )', $msg);  // added by cx
			$msg = str_replace("&amp;nbsp;)", "&amp;nbsp; )", $msg);  // added by cx
			$msg = str_replace("&gt;)", "&gt; )", $msg);              // added by cx
			$msg = str_replace("&lt;)", "&lt; )", $msg);              // added by cx
			$msg = str_replace("&amp;gt;)", "&amp;gt; )", $msg);      // added by cx
			$msg = str_replace("&amp;lt;)", "&amp;lt; )", $msg);      // added by cx
            $msg=str_replace(":)","<img src='$this->tplPath/images/fuhao/ctb.gif'>",$msg);
            $msg=str_replace("：）","<img src='$this->tplPath/images/fuhao/ctb.gif'>",$msg);        
            $msg=str_replace(":(","<img src='$this->tplPath/images/fuhao/ctb_sad.gif'>",$msg);        
            $msg=str_replace("：（","<img src='$this->tplPath/images/fuhao/ctb_sad.gif'>",$msg);
            $msg=str_replace(":D","<img src='$this->tplPath/images/fuhao/ctb_big.gif'>",$msg);
            $msg=str_replace("8D","<img src='$this->tplPath/images/fuhao/ctb_cool.gif'>",$msg);
            $msg=str_replace(":I","<img src='$this->tplPath/images/fuhao/ctb_blush.gif'>",$msg);
            $msg=str_replace(":P","<img src='$this->tplPath/images/fuhao/ctb_tongue.gif'>",$msg);
            $msg=str_replace(":})","<img src='$this->tplPath/images/fuhao/ctb_evil.gif'>",$msg);
            $msg=str_replace(";)","<img src='$this->tplPath/images/fuhao/ctb_wink.gif'>",$msg);
            $msg=str_replace(":o)","<img src='$this->tplPath/images/fuhao/ctb_clown.gif'>",$msg);
            $msg=str_replace("B)","<img src='$this->tplPath/images/fuhao/ctb_blackeye.gif'>",$msg);
            $msg=str_replace(":8)","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":O)","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":!(","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace("xx(","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace("|)","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":X","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":^)","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":~)","<img src='$this->tplPath/images/fuhao/ctb_shy.gif'>",$msg);
            $msg=str_replace(":?)","<img src='$this->tplPath/images/fuhao/ctb_question.gif'>",$msg);
        }

		$search_array = array(
			"/\[code](.*)\[\/code]/isU",
			"/\[quote](.*)\[\/quote]/isU",
			"/\[img]([^'\"\s\?\&\+]*(\.gif|jpg|jpeg|png|bmp))\[\/img]/iU",
			"/\[img=([^'\"\s\?\&\+]*(\.gif|jpg|jpeg|png|bmp))]([^'\"]*)\[\/img]/iU",
			"/\[url]www.([^'\"\s]*)\[\/url]/iU",
			"/\[url]([^'\"\s]*)\[\/url]/iU",
			"/\[url=www.([^'\"\s]*)](.*)\[\/url]/iU",
			"/\[url=([^'\"\s]*)](.*)\[\/url]/iU",
			"/\[email]([^'\"\s]*)\[\/email]/iU",
			"/\[email=([^'\"\s]*)](.*)\[\/email]/iU",
			"/\[b](.*)\[\/b]/isU",
			"/\[i](.*)\[\/i]/isU",
			"/\[u](.*)\[\/u]/isU",
			"/\[size=([1-7])](.*)\[\/size]/isU",
			"/\[color=(#?[\da-fA-F]{6})](.*)\[\/color]/isU",
			"/\[color=([a-zA-Z]{3,20})](.*)\[\/color]/isU",
			"/\[font=([^'\"]*)](.*)\[\/font]/isU",
			"/\[center](.*)\[\/center]/isU",
			"/\[right](.*)\[\/right]/isU",
			"/\[list](.*)\[\/list]/isU",
			"/\[list=1](.*)\[\/list=1]/isU",
			"/\[list=a](.*)\[\/list=a]/isU",
			"/\[\*](.*)\[\/\*]/U",
			"/\[shadow](.*)\[\/shadow]/isU",
			"/\[glow](.*)\[\/glow]/isU",
			"/\[fly](.*)\[\/fly]/isU",
			"/\[move](.*)\[\/move]/isU",
			"/\[swf]www.([^'\"\s]*)\[\/swf]/iU",
			"/\[swf]([^'\"\s]*)\[\/swf]/iU",
			"/\[swf width=([1-6]\d\d) height=([1-9]\d\d)]www.([^'\"\s]*)\[\/swf]/iU",
			"/\[swf width=([1-6]\d\d) height=([1-9]\d\d)]([^'\"\s]*)\[\/swf]/iU",
		);

		$replace_array = array(
			"<table cellpadding=\"4\" cellspacing=\"1\" bgcolor=\"#6394bd\" width=\"98%\" align=\"center\"><tr bgcolor=\"#f5f5f5\"><td style=\"WORD-BREAK: break-all\"><span style=\"color:#6394bd\">代码：<br />\\1</span></td></tr></table>",
			"<center>引用：<table cellspacing=\"$table_border\" cellpadding=\"4\" bgcolor=\"$table_border_color\" width=\"90%\"><tr bgcolor=\"$this_background_color\"><td>\\1</td></tr></table></center>",
			"<img src=\"\\1\" border=\"0\" />",
			"<img src=\"\\1\" alt=\"\\3\" border=\"0\" />",
			"<a href=\"http://www.\\1\" target=\"_blank\">www.\\1</a>",
			"<a href=\"\\1\" target=\"_blank\">\\1</a>",
			"<a href=\"http://www.\\1\" target=\"_blank\">\\2</a>",
			"<a href=\"\\1\" target=\"_blank\">\\2</a>",
			"<a href=\"mailto:\\1\">\\1</a>",
			"<a href=\"mailto:\\1\">\\2</a>",
			"<b>\\1</b>",
			"<i>\\1</i>",
			"<u>\\1</u>",
			"<font size=\"\\1\">\\2</font>",
			"<font color=\"\\1\">\\2</font>",
			"<font color=\"\\1\">\\2</font>",
			"<font face=\"\\1\">\\2</font>",
			"<center>\\1</center>",
			"<div align=\"right\">\\1</div>",
			"<ul>\\1</ul>",
			"<ol type=\"1\">\\1</ol>",
			"<ol type=\"a\">\\1</ol>",
			"<li>\\1</li>",
			"<table style=\"filter: shadow(color='#ff5555', direction='135')\"><nobr><font color=\"ffffff\">\\1</font></nobr></table>",
			"<table style=\"filter: glow(color='#5555ff', strength='4')\"><nobr><font color=\"ffffff\">\\1</font></nobr></table>",
			"<marquee behavior=\"alternate\">\\1</marquee>",
			"<marquee>\\1</marquee>",
			"<embed src=\"http://www.\\1\" width=\"400\" height=\"300\"></embed><br />",
			"<embed src=\"\\1\" width=\"400\" height=\"300\"></embed><br />",
			"<embed src=\"http://www.\\3\" width=\"\\1\" height=\"\\2\"></embed><br />",
			"<embed src=\"\\3\" width=\"\\1\" height=\"\\2\"></embed><br />",
		);

		$msg = preg_replace($search_array, $replace_array, $msg);

    	return $msg;
    }// end func

    /*
    * 函数说明： 用户输入数据安全性检查
    * 创建时间： 2002-4-25
    */
	function safeChars($msg) 
    {
        $msg = trim($msg);
        $msg = str_replace("\x0E", "*", $msg);
        $msg = str_replace("", "*", $msg);
        //$msg = str_replace("|", "&#124;", $msg); 
        $msg = str_replace("&", "&amp;", $msg);    // 正常显示符号 &
        $msg = str_replace(">", "&gt;", $msg);
        $msg = str_replace("<", "&lt;", $msg);
        $msg = str_replace("\n", "<br />", $msg);  // 兼容 XHTML，改用 <br />
        $msg = str_replace("\r","",$msg);

    	return $msg;
    }// end func

	/*
    * 函数说明： 脏话过滤 added by cx
    * 创建时间： 2003-4-17
    */
	function replaceBadWord($msg) 
    {
		if (!$msg or $this->unset_bad_word) {
			return $msg;
		}
		if (!is_array($this->bad_word) or !is_array($this->replace_word)) {
			$bad_word_file = $this->set[dataPath]."/badword.php";
			if (!file_exists($bad_word_file) or !filesize($bad_word_file)) {
				$this->unset_bad_word = 1;
				return $msg;
			} else {
				$bad_word_lines = file($bad_word_file);
				if (!count($bad_word_lines)) {
					$this->unset_bad_word = 1;
					return $msg;
				}
			}
			foreach ($bad_word_lines as $bad_word_line) {
				$bad_word_code = $this->make_array($bad_word_line);
				$this->bad_word[] = $bad_word_code[2];
				$this->replace_word[] = $bad_word_code[3];
			}
		}
		$msg = str_replace($this->bad_word, $this->replace_word, $msg);

		return $msg;
    }// end func
    /*
    * 函数说明： 邮箱地址合法性检查
    * 创建时间： 2002-4-25
    */
	function checkEmail($email) 
    {
    	if (ereg("^.+@.+\\..+$",$email)) {
            return 1;
        } else {
            return 0;
        }
    }// end func
    
    /*
    * 函数说明： 分页显示函数
    * 创建时间： 2002-4-25
    */
	function getPage($url,$totalnum) 
    {
    	global $p,$mods,$forumid,$recnum,$listnum,$postid; 

        $p = $this->input['p'];
        $mods = $this->input['mods'];
        $forumid = $this->input['forumid'];
        //$recnum = $this->set['topicList'];
        //$listnum = $this->set['topicPage'];
        if(!$listnum) $listnum = 10;
        $postid = $this->input['postid']; 
        $pagenum = $p; 
    	if(!$p){$pagenum = 1; $p = 1;} 
    	if($p > $this->set['pageLimit']) { 
        	if ($p == 1) { 
                $htmlpage .= "\n"; 
            } else { 
                $PrevPage = $p-1; 
                $htmlpage .= "<a href=$url&p=1 title=首页>[1]</a>\n"; 
            }
        }
        $term = $this->set['pageLimit'];$f = 1;$l = $term;
    	while ($f <= $totalnum) { 
        	if (($f <= $p) && ($p <= $l)) { 
                $prevp = $f - 1; 
            	if ($prevp > 0) { 
                    $htmlpage .= "<a href=$url&p=$prevp title=\"前 $set[listnum]页\">[Prev]</a>-"; 
                } else { 
                    $page = "\n"; 
                }
            	if ($l <= $totalnum) { 
                	for ($page = $f; $page <= $l; $page++) { 
                    	if ($page == $p) { 
                            $htmlpage .= "[<font color=red title=当前页>$page</font>]"; 
                        } else { 
                            $htmlpage .= "<a href=$url&p=$page title=$page页>[$page]</a>"; 
                        }
                    }
                } else { 
                	for ($page = $f; $page <= $totalnum; $page++) { 
                    	if ($page == $p) { 
                            $htmlpage .= "[<font color=red title=当前页>$page</font>]"; 
                        } else { 
                            $htmlpage .= "<a href=$url&p=$page title=$page页>[$page]</a>"; 
                        }
                    }
                }
                $nextp = $l + 1; 
            	if ($nextp <= $totalnum) { 
                    $htmlpage .= "-<a href=$url&p=$nextp title=\"后 $set[listnum]页\">[Next]</a>"; 
                } else { 
                    $htmlpage .= ""; 
                }
            }
            $f = $f + $term; 
            $l = $l + $term; 
        }
    	if($nextp <= $totalnum) {
            $htmlpage .= "<a href=$url&p=$totalnum title=尾页>[$totalnum]</a>\n"; 
        }

    	return $htmlpage;
    }// end func

    /*
    * 函数说明： 删除文件夹与下面的文件
    * 创建时间： 2002-4-25
    */
    function delFileValue($path) {
        $dh = opendir($path);
        $delNum = array();
        while($entry = readdir($dh)){
            if ($entry != "." && $entry != ".."){
                if (@unlink($path."/".$entry)) 
                $delNum[0]++;
            else 
                $delNum[1]++;
            }
        }
        closedir($dh);
		if (@rmdir($path)); 
		    $delNum[2] = "ok";
        return $delNum;
    }

    /*
    * 函数说明： 字符串限长函数
    * 创建时间： 2002-9-3
    */
	function keepLen($str,$len)
    {
		for($i=0;$i<$len;$i++) { 
			if(ord(substr($str,$i,1))>0xa0) { 
				$tmpstr.=substr($str,$i,2); 
				$i++; 
			} else 
				$tmpstr.=substr($str,$i,1); 
		} 
		return $tmpstr."...";; 

    }// end func

    /*
    * 函数说明： 获取文件类型函数
    * 创建时间： 2002-12-30
    */
   function getFileType($type1)
   {
        if ( !$type1 ) { $ftype = "unknown.gif "; return $ftype; }
            if( eregi($type1, "html")) { $ftype = "html.gif"; }
        elseif( eregi($type1, "exe")) { $ftype = "exe.gif"; }
        elseif( eregi($type1, "zip|gz|tar")) { $ftype = "zip.gif"; }
        elseif( eregi($type1, "rar")) { $ftype = "rar.gif"; }
        elseif( eregi($type1, "gif")) { $ftype = "gif.gif"; }
        elseif( eregi($type1, "php|php3|phtml|inc")) { $ftype = "php3.gif"; }
        elseif( eregi($type1, "jpeg|jpg")) { $ftype = "jpg.gif"; }
        elseif( eregi($type1, "bmp")) { $ftype = "bmp.gif"; }
        elseif( eregi($type1, "mid")) { $ftype = "mid.gif"; }
        elseif( eregi($type1, "wav")) { $ftype = "wav.gif"; }
        elseif( eregi($type1, "mp3")) { $ftype = "mp3.gif"; }
        elseif( eregi($type1, "ra")) { $ftype = "ra.gif"; }
        elseif( eregi($type1, "mpeg|asf|mpg|avi|asx|mov")) { $ftype = "mpeg.gif"; }
        elseif( eregi($type1, "doc")) { $ftype = "doc.gif"; }
        elseif( eregi($type1, "hwp")) { $ftype = "hwp.gif"; }
        elseif( eregi($type1, "xls")) { $ftype = "xls.gif"; }
        elseif( eregi($type1, "ppt")) { $ftype = "ppt.gif"; }
        elseif( eregi($type1, "cgi|pl|pm")) { $ftype = "cgi.gif"; }
        elseif( eregi($type1, "js|css|class")) { $ftype = "js.gif"; }
        elseif( eregi($type1, "swf")) { $ftype = "swf.gif"; }
        elseif( eregi($type1, "txt")) { $ftype = "text.gif"; }
        else { $ftype = "unknown.gif"; }
        return "<img src=\"{$this->tplPath}/images/file/$ftype\" align=\"absbottom\">";
     }//end func

//=============================================================================
//得到一个目录下的所有文件名和目录名列表,不带绝对路径,不展开子目录: Array1

	function getFileNameList($dirPath)
	{
		$filenameSet=array();
		$dirHandle=opendir($dirPath);
		while ($file = readdir($dirHandle)) {
		   if($file!=".." and $file!="." and $file!="") 
			   $filenameSet[]=trim($file);
		}
		closedir($dirHandle); 
		return $filenameSet;
	}


//-----------------------------------------------------------------------------
//1----前台用户登陆日志
//2---前台管理员管理日志
//3---后台管理员登陆日志
//-----------------------------------------------------------------------------




//=============================================================================
//前台用户登陆日志
	function userLoginLog($check="ok")
    { 
		if($this->set[logRecord] == "N"){
            return false;
		}
        $msgArray[phpCode] = $this->code;
        //判断文件大小是否需要清空
		$logUserLoginMaxSize = 2000;
		if(filesize($this->set[dataPath]."/log_userlogin.php")>$logUserLoginMaxSize){
            $this->file = $this->set[dataPath]."/log_userlogin.php";
			$this->null_write("");
		}
		//登陆错误日志
		if($check == "ok"){
            $msgArray[loginMode] = 1;
            $msgArray[loginId] = $this->input['ulogon'];
		    $msgArray[wrongMsg] = $_SESSION['sess_uname']."：登陆成功";
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = "";  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = $this->set[dataPath]."/log_userlogin.php";
			$this->add_line($msgArray);
		}
		//登陆失败
		else{
            $msgArray[loginMode] = 0;
            $msgArray[loginId] = $this->input['ulogon'];
		    $msgArray[wrongMsg] = $check;
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = "";  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = $this->set[dataPath]."/log_userlogin.php";
			$this->add_line($msgArray);
		}


	}
//=============================================================================
//后台管理员登陆日志
	function manageLog($check="no")
    { 
		if($this->set[logRecord] == "N"){
            return false;
		}
		$msgArray[phpCode] = $this->code;
        //判断文件大小是否需要清空
		$logUserLoginMaxSize = 2000;
		if(filesize($this->set[dataPath]."/log_manage.php")>$logUserLoginMaxSize){
            $this->file = $this->set[dataPath]."/log_manage.php";
			$this->null_write("");
		}
		//登陆错误日志
		if($check == "no"){
            $msgArray[loginMode] = 0;
            $msgArray[loginId] = $this->sess['sess_uname'];
		    $msgArray[wrongMsg] = $this->sess['sess_uname']."：没有权限执行此项操作";
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = "0";  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = $this->set[dataPath]."/log_manage.php";
			$this->add_line($msgArray);
		}
		//登陆失败
		else{
            $msgArray[loginMode] = 1;
            $msgArray[loginId] = $this->sess['sess_uname'];
		    $msgArray[wrongMsg] = $check;
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = $this->input['forumid'];  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = $this->set[dataPath]."/log_manage.php";
			$this->add_line($msgArray);
		}


	}
//=============================================================================
//后台管理员登陆日志
	function adminLoginLog($check="ok")
    { 
		if($this->set[logRecord] == "N"){
            return false;
		}
        $msgArray[phpCode] = $this->code;
        //判断文件大小是否需要清空
		$logUserLoginMaxSize = 2000;
		if(filesize("../".$this->set[dataPath]."/log_adminlogin.php")>$logUserLoginMaxSize){
            $this->file = "../".$this->set[dataPath]."/log_adminlogin.php";
			$this->null_write("");
		}
		//登陆错误日志
		if($check == "ok"){
            $msgArray[loginMode] = 1;
            $msgArray[loginId] = $this->input['userName'];
		    $msgArray[wrongMsg] = $this->input['userName']."：登陆成功";
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = "";  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = "../".$this->set[dataPath]."/log_adminlogin.php";
			$this->add_line($msgArray);
		}
		//登陆失败
		else{
            $msgArray[loginMode] = 0;
            $msgArray[loginId] = $this->input['userName'];
		    $msgArray[wrongMsg] = $check;
		    $msgArray[userIp] = getenv("REMOTE_ADDR");
			$msgArray[loginTime] = time();
            $msgArray[temp1] = "";  //备用
			$msgArray[temp2] = "";  //备用
            $this->file = "../".$this->set[dataPath]."/log_adminlogin.php";
			$this->add_line($msgArray);
		}


	}
//-----------------------------------------------------------------------------
//---前台管理模块
//1---ctb前台执行提示函数：showMsg($msg,$url='')
//2---ctb前台页头信息：header($modName)
//3---ctb前台页脚信息：footer()
//4---主题列表或显示文件行数写入处理函数：insertTop($file,$array) 
//5---版块权限判断：checkForum($forumId) 
//6---邮件函数：sendSmallEmail($to, $subject, $msg, $emailMode="text",$emailFrom)
//7---添加在线显示函数（包括访客和用户）：addOnline()
//8---排序一：orderTopic1
//9---排序二：orderTopic2
//10---排序三：orderTopic3
//11---验证用户权限：userCheck($per)
//12---使用限制，只有登陆才可以使用：openLimit()
//---
//---
//-----------------------------------------------------------------------------

//1============================================================================
//ctb前台执行提示函数
	function showMsg($msg,$url='')
    { 
    	if ($url == "") {
			// start hack by cx
			if ($this->input['jump_back']) {
				$url = $this->input['jump_back'];
			} else {
				$url = "javascript:history.go(-1);";
			}
        }
        if("ask" == $url) {
            $action2 = $this->input['action']."2";
            eval("\$this->outPut(\"".$this->getTemplate("moderateMsg")."\",\"n\");");
        }else {
            eval("\$this->outPut(\"".$this->getTemplate("msg")."\",\"n\");");
        }
    	exit;
    } // end func

//+2----------------------------------------------------------------------------
//ctb前台页头信息
	function header($modName)
    {

    	if (isset($this->sess[sess_uid])) {
            $headerMenu = "| <a href=\"./index.php?mods=member&action=logout\">退出论坛</a> | <a href=\"./index.php?mods=member&action=profile\">个人设置</a> ";
        } else {
            $headerMenu = "| <a href=\"./index.php?mods=member&action=register\">注册会员</a> | <a href=\"./index.php?mods=member&action=login\">会员登陆</a> ";
        }
    	eval ("\$output = \"".$this->getTemplate("header")."\";");

    	return $output;
    } // end func

//+3----------------------------------------------------------------------------
//ctb前台页脚信息
	function footer()
    {
        global $startTime;
        $mtime2 = explode(" ", microtime());
        $endtime = $mtime2[1] + $mtime2[0];
        $totalTime = number_format(($endtime - $startTime), 7);
        //
		if (is_array($this->openTemplateFile)) {
			$openTemplateFileCnt = count($this->openTemplateFile)+1;
			$this->OpenTpl =  "Open template : $openTemplateFileCnt<br />";
		}
    	eval ("\$output = \"".$this->getTemplate("footer")."\";");
        
    	return $output;
    } // end func

//+4----------------------------------------------------------------------------
//函数说明： 主题列表或显示文件行数写入处理函数
	function insertTop($file,$array) 
    {
        $newfile = @implode("\x0E",$array);
        if (file_exists($file)) {
            $line = @file($file);
            $line_num = @count($line)-1;
        } else {
            $line_num = 0;
        }
        $f = @fopen($file,"w");
        @flock($f,LOCK_EX);
    	for ($i=0;$i<=$line_num;$i++) {
            $tmpLine = @explode("\x0E",$line[$i]);
        	if ($tmpLine[5]=="1") {
                @fputs($f,$line[$i]);
            }
        }
        @fputs($f,$newfile);
        for ($i=0;$i<=$line_num;$i++) {
            $tmpLine = @explode("\x0E",$line[$i]);
        	if ($tmpLine[5]!="1") {
                @fputs($f,$line[$i]);
            }
        }
        @fclose($f);

    }// end func

//+5----------------------------------------------------------------------------
//函数说明： 版块权限判断
	function checkForum($forumId) 
    {
        //global $forum;

        $check = array();
		$this->file = $this->set[dataPath]."/forums.php";
		if($this->input['forumid']){
            $forum = $this->select_line("2",$forumId);
		}else{
            $forum = $this->forum;
		}


        // 1.以下为加密板块判断
        $forumGrade = $forum[6]; //此为加密版块判断字段
        //检查是否为允许访问加密版块的用户
    	if ($forumGrade == "1") {
            $check[0] = "0";
            $memberFile = $this->set[dataPath]."/".$forumId."/member.php";
        	if (file_exists($memberFile) and $this->sess['sess_uid']) {
                $line = @file($memberFile);    
                $userCode = explode("\x0E",$line[0]);
                $totalCode = count($userCode);
            	for ($i=0;$i<=$totalCode-1;$i++) {
                	if($userCode[$i] == $this->sess['sess_uid'] && isset($this->sess['sess_ugrade'])) {
                        $check[0] = "1";
                    	break;
                    }
                }
            }
            //检查用户是否为该版版主
        	if ($forum[8] != "" and $this->sess['sess_uid']) {
                $moderators = explode("|",$forum[8]);
            	foreach ($moderators as $moderator) {
                    $modInfo1 = explode(",",$moderator);
                    //$modUserId = $modUserId;
                	if ($modInfo1[0] == $this->sess['sess_uid'] && isset($this->sess['sess_ugrade'])) {
                        $check[0] = "1";
                    }
                }
            }
            //检查是否为管理员
        	if ( $this->sess['sess_ugrade'] == '1' && isset($this->sess['sess_ugrade'])) {
                $check[0] = "1";
            }

        }

        // 2.以下为会员板块判断(是否允许访客浏览)
        $forumGuest = $forum[7];
    	if($forumGuest == "1") {
            $check[1] = "0";
        	if (isset($this->sess['sess_uid']) && $this->sess['sess_uid'] != "") {
                $check[1] = "1";
            }
        }

        // 3.以下为只读板块判断
        $forumRead = $this->forum[5];
    	if ($forumRead == "1") {
            $check[2] = "0";
            //检查用户是否为该版版主
        	if ($forum[8] != "") {
                $moderators = explode("|",$forum[8]);
            	foreach ($moderators as $moderator) {
                    $modInfo2 = explode(",",$moderator);
                    //$modUserId = $modUserId;
                	if ($modInfo2[0] == $this->sess['sess_uid'] && isset($this->sess['sess_ugrade'])) {
                        $check[2] = "1";
                    }
                }
            }
            //检查是否为管理员
        	if ( $this->sess['sess_ugrade'] == '1' && isset($this->sess['sess_ugrade'])) {
                $check[2] = "1";
            }
        }

    	return $check;
    
    }// end func

//+6----------------------------------------------------------------------------
//函数说明：邮件函数
	function sendSmallEmail($to, $subject, $msg, $emailMode="text",$emailFrom)
    {
        //发送htm邮件
		if ($emailMode=="html"){
			$headers  = "MIME-Version: 1.0\r\n";
			$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
			$headers .= "From: ".$emailFrom."\r\n";
			$headers .= "Cc: birthday2@example.com\r\n";
			$headers .= "Bcc: birthday3@example.com\r\n";
		}
		//发送普通文本
        if ($emailMode=="text"){
            $headers .= "From: ".$emailFrom."\r\n";
			$msg .="\n______________________________________________
    欢迎访问 {$this->set['ctbTitle']}
    {$this->set['webPath']}
-----------------------------------------------
    实易数码：CTB文本论坛
    技术支持：http://ctb.11cn.org
            ";
		}
		//执行发送操作，并返回结果
    	if(@mail($to, $subject, $msg, $headers)) {
            return 1;
        }else {
            Return 0;
        }     
    } //end func 

//+7----------------------------------------------------------------------------
//添加在线显示函数（包括访客和用户）
    function addOnline(){
        $nowTime = time();
        $ip = getenv("REMOTE_ADDR");
        //获取用户位置
    	if (!$this->input['forumid']) {
            $userWhere = "all";
        } else {
            $userWhere = $this->input['forumid'];
        }
        
        $this->file = $this->set['dataPath']."/online.php";
        $newOnline = "";
        //如果是会员...
    	if(isset($this->sess['sess_uid'])) {
            $fp = @fopen($this->file,'r');
        	while ($line = fgets($fp,1024)) {
                $arrayCode = $this->make_array($line);
                if ($arrayCode[1] != $this->sess['sess_uid'] && ($nowTime - $arrayCode[4]) < $this->set['showOnlineTime']) {
                	if ($arrayCode[1] != ""){
                        $newOnline .= $line;
                    }
                }
            }
        	fclose($fp);
            $newOnlineArray = $this->code."\x0E".$this->sess['sess_uid']."\x0E".$this->sess['sess_ulogin']."\x0E".$this->sess['sess_uname']."\x0E".$nowTime."\x0E".$userWhere."\x0E".""."\x0E".$this->sess['sess_ugrade']."\x0E".$this->sess['sess_login_mode']."\x0E";
            $newOnline.=$newOnlineArray."\n";    
        }else {
            //如果是游客...
            $fp = fopen($this->file,'r');
        	while ($line = fgets($fp,1024)) {
                $arrayCode = $this->make_array($line);
                if ($arrayCode[1] != $ip && ($nowTime - $arrayCode[4]) < $this->set['showOnlineTime']) {
                	if ($arrayCode[1] != ""){
                        $newOnline .= $line;
                    }
                }
            }
        	fclose($fp);
            $newOnlineArray = $this->code."\x0E".$ip."\x0E".'0'."\x0E".'guest'."\x0E".$nowTime."\x0E".$userWhere."\x0E".''."\x0E".'0'."\x0E".''."\x0E";    
            $newOnline .= $newOnlineArray."\n";    
        }
        //从新写整个在线文件...
        $fp = fopen($this->file,'w');
    	flock($fp,LOCK_EX);
        fputs($fp,$newOnline);
    	fclose($fp);
        $newCount = $this->getlines();
        //写入在线峰值文件
        $this->file = $this->set[dataPath]."/toponline.php";
        $topOnlineCode = $this->get();
    	if ($newCount > $topOnlineCode[1]){
            $newDate = date("Y.m.d H:i");
            $newTop = array($this->code,$newCount,$newDate,'');
            $this->insert_line($newTop);
        } else {
            $topOnline = $topOnlineCode[1];
            $topOnlineTime = $topOnlineCode[2];
        }

        //判断是否有新消息
    	if (file_exists($this->set[dataPath]."/users/".$this->sess['sess_uid']."new.php")) {
        	echo "<script type=\"text/javascript\"> window.open(\"index.php?mods=usermgs\");</script>";
        }
    } //end func

//+8----------------------------------------------------------------------------
//帖子排序

    function orderTopic($columnSort,$orderColumnSort,$orderColumnValue,$mode='0') {
        $tlines = file($this->file);
    	for ($i=0;$i<=count($tlines);$i++) {
            $line = explode("\x0E",$tlines[$i]);
            if ($mode == "0") {
                $getNowTime = time();
                if (($getNowTime - $line[$orderColumnSort]) <= $orderColumnValue) {
                    $linesOrder[$tlines[$i]] = $line[$columnSort];
                }
            }else {
                if (($getNowTime - $line[$orderColumnSort]) == $orderColumnValue) {
                    $linesOrder[$tlines[$i]] = $line[$columnSort];
                }
            }
        }
        @asort($linesOrder);
        @reset($linesOrder);

    	for ($j=0; $j<count($linesOrder); $j++) {
             $lines[] = key($linesOrder);
             next($linesOrder);
        }
    	return $lines;
    } //end func


//+9----------------------------------------------------------------------------
//按照帖子某个字段等于多少进行排序
    function orderTopic2($columnSort,$orderColumnSort,$orderColumnValue) {
        $tlines = file($this->file);
    	for ($i=0;$i<=count($tlines);$i++) {
            $line = explode("\x0E",$tlines[$i]);
        	if ($line[$orderColumnSort] == $orderColumnValue)
                $linesOrder[$tlines[$i]] = $line[$columnSort];
        }
        @asort($linesOrder);
        @reset($linesOrder);

    	for ($j=0; $j<count($linesOrder); $j++) {
             $lines[] = key($linesOrder);
             next($linesOrder);
        }
    	return $lines;
    } //end func

//+10----------------------------------------------------------------------------
//按照帖子某个字段进行排序
function orderTopic3($order_data,$column_sort,$topic_num="20") {
		for ($i=0;$i<=count($order_data);$i++) {
			$line=explode("\x0E",$order_data[$i]);
			    $lines_order[$order_data[$i]]=$line[$column_sort];
		}
		@arsort($lines_order);
		@reset($lines_order);

		for ($j=0; $j<=$topic_num; $j++) {
             $lines[]=key($lines_order);
             next($lines_order);
			   }
		return $lines;
	} //end func


//+11----------------------------------------------------------------------------
//验证用户权限
	function userCheck($per)
    {

        //检查用户是否为该版版主
        $this->file = $this->set[dataPath]."/forums.php";
        $forum = $this->select_line("2",$this->input['forumid']);
    	if ($forum[8] != "") {
            $moderators = explode("|",$forum[8]);
        	foreach ($moderators as $modId) {
                $modInfo = explode(",",$modId);
                $mod = $modInfo[0];
            	if ($mod == $this->sess['sess_uid'] && isset($this->sess['sess_ugrade'])) {
                    $check = "1";
                }
            }
        }
        
        //检查是否为管理员
    	if ( $this->sess['sess_ugrade'] == '1' && isset($this->sess['sess_ugrade'])) {
            $check = "1";
        }
        
        //检查是否为文章作者
        $this->file = $this->set[dataPath]."/".$this->input['forumid']."/".$this->input['postid'].".php";
        $line = $this->select_line("1", $this->input['topicid']);
    	if ($line[5] == $this->sess['sess_uid']) {
            $check = 1;
        }
        //输出 1 或 0
        if ($check == "1") {
            return 1;
        } else {
        	return 0;
        }

    }// end func

//+12----------------------------------------------------------------------------
//使用限制，只有登陆才可以使用
	function openLimit()
    {
	    if ($this->set[openLimit] == "Y" and !$this->sess['sess_uid'] ) {
		    $this->showmsg("CTB论坛开启使用限制；要想使用此功能，请您登陆。","./index.php");
	    }
    }// end func

//=============================================================================

//-----------------------------------------------------------------------------
//----后台管理模块
//1---后台管理提示信息：doAdminOrder($msg)
//2---后台管理执行操作提示一:adminShowMsg($url,$msg)
//3---后台管理执行操作二:adminShowWrong($url,$msg)
//4---信息提示函数：wrongPage($err,$url="index.php",$turn=1)
//5---后台管理密码验证函数：md5AdminCheck()
//6---显示论坛基本情况函数 ：showBbsInfo()
//7---后台管理基本数据输入验证:adminSafeChars($msg) 
//8---后台单选按钮函数，险情制作：getChecked();
//9---后台管理基本数据输入判断是否有效，并将之过滤：inputCheck($newUrl) 
//10---由论坛id获取起名字：getForumName($forumId) 
//---
//---
//---
//-----------------------------------------------------------------------------
//1============================================================================
//后台管理提示信息
function doAdminOrder($msg){
	$action2 = $action."2";
	eval("\$this->outPut(\"".$this->gettemplate("doAdminOrder")."\",\"n\");");
}

//+2---------------------------------------------------------------------------
//后台管理正确提示
	function adminShowMsg($url,$msg)
    {
    	eval("\$this->output(\"".$this->getTemplate("msg")."\",\"n\");");
    	exit;
    } // end func

//+3---------------------------------------------------------------------------
//后台管理错误提示
	function adminShowWrong($url,$msg)
    {
    	eval("\$this->output(\"".$this->getTemplate("wrong")."\",\"n\");");
    	exit;
    } // end func

//+4---------------------------------------------------------------------------
function wrongPage($err,$url="index.php",$turn=1) {
//信息提示函数
  echo "
    <html>
    <head>
    <style type=\"text/css\">
    <!--
	a {color:#333333;font-size: 9pt;text-decoration:none; }
	a:hover {color:#000066;text-decoration:underline overline;}
	td{FONT-SIZE: 9pt; color:#333333; font-family:宋体}
    -->
    </style>
    <title>CTB论坛操作提示</title>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">";
	if ($turn==1) {
        echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\">";   
    }
  echo "
    </head>
	<body bgcolor=\"#f5f5f5\" text=\"#000000\" topmargin=\"5\">
	<p>&nbsp;</p>
	<p>&nbsp;</p>
	<p>&nbsp;</p>
	<table width=\"60%\" border=\"0\" cellspacing=\"1\" cellpadding=\"5\" bgcolor=\"#6394bd\" align=\"center\">
	<tr bgcolor=\"#6394bd\">
	  <td>&nbsp;<font color=white><b>CTB文本论坛 - 提示信息</b></font></td>
	  </tr>
	  <tr> 
		<td align=\"center\" bgcolor=\"#FFFFFF\" height=\"100\">
		  <br><b>
		  $err</b><br>
		  <br><br><div align=right>
		   若您不能解决，请联系:<A 
      href=\"http://www.11cn.org\">实易数码</a>=>>CTB开发组&nbsp;&nbsp;</div>
		</td>
	  </tr>
	</table>
    </body>
    </html>";
  exit;
} //end func


//+5---------------------------------------------------------------------------
//管理员密码验证
function md5AdminCheck(){ 
    if(!$this->sess['sess_adminlogin'] || !$this->sess['sess_adminpass']) {
       $this->wrongPage("管理员同志，请您重新登陆1",$url="main.php?mod=login");
       exit;
    }
    $fileOpen = file("../".$this->set[dataPath]."/adminuser.php");
    $ok="no";
	for($i=0;$i<count($fileOpen);$i++){
        $fileCode = explode("\x0E",$fileOpen[$i]);
    	if ($fileCode[2]==$this->sess['sess_adminlogin']) {
            $ok="yes";
            break;
        }
    }
    if ($ok=="yes")
       return true;
    else {
        $this->wrongPage("管理员同志，请您重新登陆2",$url="main.php?mod=login");
        exit;
    }
}// end func


//+6---------------------------------------------------------------------------
//后台基本资料显示
function showBbsInfo()
{   
    $cates = file("../".$this->set[dataPath]."/forums.php");
    $cate_num="0";
    $forum_num="0";
	foreach ($cates as $tmpCate) {
        $cate  = explode("\x0E",$tmpCate);;    
    	if ($cate[1] == "cat") {
            $cate_num++;
        } else {
            $forum_num++;
            $forumid = $cate[2];
            @$f=file("../".$this->set[dataPath]."/".$forumid."/status.php");    
            $new_status=explode("\x0E",$f[0]);
            $topicnum += $new_status[1];
            $postnum += $new_status[2];
        }
    }
            $f=file("../".$this->set[dataPath]."/member.php");    
            $new_mem=explode("\x0E",$f[0]);
            $all_mem=$new_mem[2];
    //环境测试
    $show_phpv=$phpos;
    $phpverion=PHP_VERSION;
    $phpos=PHP_OS;
	global $HTTP_COOKIE_VARS;
	if (isset($HTTP_COOKIE_VARS)){ 
    $ctb_cookie="<font color=#6394bd>通 过</font>";
    }
	else {
    $ctb_cookie="<font color=red>失 败</font>";
    }
	if (@session_register('test')){ 
    $ctb_session="<font color=#6394bd>通 过</font>";
    }
	else {
    $ctb_session="<font color=red>失 败</font>";
    }
    $ctb_time = date("F j, Y, g:i:s a");
    //结束
    eval("\$this->outPut(\"".$this->gettemplate("indexMain")."\",\"n\");");

} // end func

//+7---------------------------------------------------------------------------
//后台管理基本数据输入验证
	function adminSafeChars($msgs) 
    {
        if (!is_array($msgs)){
			$msgs = trim($msgs);
			$msgs = str_replace("\x0E", "*", $msgs);
			$msgs = str_replace("", "*", $msgs);
			$msgs = str_replace("\n", "<br>", $msgs);
			$msgs = str_replace("\t","",$msgs);
			$msgs = str_replace("\r","",$msgs);
		}else {
            foreach($msgs as $msg){
                $msgsKey = key($msgs);//=>$msgsKey
                $msgs[$msgsKey] = $this->adminSafeChars($msg);
				next($msgs);
			}
		}
    	return $msgs;
    }// end func

//+8---------------------------------------------------------------------------
//后台单选按钮函数，险情制作
	function getChecked($msg) 
    {
        if ($msg == "Y"){
            $getChecked[Y] = "checked";
            $getChecked[N] = "";
		}
		if ($msg == "N"){
            $getChecked[Y] = "";
            $getChecked[N] = "checked";
		}

    	return $getChecked;
    }// end func

//+9---------------------------------------------------------------------------
//后台管理基本数据输入判断是否有效，并将之过滤
	function inputCheck($newUrl) 
    {
	    if (in_array("",$this->input)){
           $this->adminShowWrong($newUrl,"所有资料为必填选项，请不要留空。");
	    }
	    $this->input = $this->adminSafeChars($this->input);
	}//end func

//+10---------------------------------------------------------------------------
//由论坛id获取起名字
	function getForumName($forumId) 
    {
		$this->file = "../".$this->set[dataPath]."/forums.php";
	    $forums = $this->read_file();
	     foreach ($forums as $line) {
		    $lineCode = $this->make_array($line);
			if ($lineCode[2]==$forumId) {
				$forumName=$lineCode[3];
			}
		 }
		 return $forumName;
	}//end func
//+11--------------------------------------------------------------------------
//获取所有论坛版块列表
	function getForumLine($forumId=false) 
    {
        $this->file =  "../".$this->set[dataPath]."/forums.php";
		$forums = $this->read_file();
		$optionLine="\n";
		if ($forumId){
			foreach ($forums as $line) {
			  $lineCode = $this->make_array($line);
			  if ($lineCode[1] == "forum" and $lineCode[2] == $forumId) {
				$optionLine.="<option value=".$lineCode[2]." selected>　|-".$lineCode[3]."</option>\n";
			  }
			  elseif ($lineCode[1] == "forum") {
				$optionLine.="<option value=".$lineCode[2].">　|-".$lineCode[3]."</option>\n";
			  }
			  elseif ($lineCode[1] == "cat" and $lineCode[2] == $forumId) {
				$optionLine.="<option value=\"$lineCode[2]\" selected>╋".$lineCode[3]."</option>\n";
			  }
			  elseif ($lineCode[1] == "cat") {
				$optionLine.="<option value=\"$lineCode[2]\">╋".$lineCode[3]."</option>\n";
			  }
			}	
		}
		else{
			foreach ($forums as $line) {
			  $lineCode = $this->make_array($line);	
			  if ($lineCode[1] == "forum") {
				$optionLine.="<option value=".$lineCode[2].">　|-".$lineCode[3]."</option>\n";
			  }
			  elseif ($lineCode[1] == "cat") {
				$optionLine.="<option value=\"$lineCode[2]\">╋".$lineCode[3]."</option>\n";
			  }
			}	

		}
		return $optionLine;
		}
//+11--------------------------------------------------------------------------
//获取所有论坛版块列表
	function getForumList() 
    {
        $optionLine = $this->getForumLine();
		$forumList="<select name='forumListId'  class='input5'>".$optionLine."</select>";
	    
		return $forumList;
		}

//+12----------------------------------------------------------------------------
//通过用户名获取id
    function getIdFromName($userName){
        $this->file = "../". $this->set[dataPath]."/users/list.php";
	    $userInfo = $this->select_line("4",$userName);
		if ($userInfo[1]!="")
		    return $userInfo[1];
		else 
			return false;
	}
//+12----------------------------------------------------------------------------
//通过用户id获取名字
    function getNameFromId($userId){
        $this->file = "../". $this->set[dataPath]."/users/list.php";
	    $userInfo = $this->select_line("1",$userId);
		if ($userInfo[4]!="")
		    return $userInfo[4];
		else 
			return false;
	} 

//<<
//=============================================================================
}// end class
?>