<?php
require_once(dirname(__FILE__)."/inc/common.php");
/*******************************************************************************************
' Software name: DJCMS Content Management System
' Version:3.0
' Web: http://www.djcms.net
' Author: 心情(qq:1130731)
' Copyright (C) 2009-2010 DJCMS官方 版权所有
' 法律申明：DJCMS程序所有代码100%原创、未引入任何网上代码,对一切抄袭行为、坚决严肃追究法律责任
'*******************************************************************************************/
if (gbookStart == 0) die("留言功能已经关闭");
$timeSpan = gbookTime;
$action = getForm("action", "get");
$page = getForm("page","get");
switch ($action) {
	case "add" : leaveWord();break;
	case "list" : leaveWordList();break;
	case "login" : loginLeaveWord();break;
	case "logout" :  logOut();break;
	case "state" : viewLoginState();break;
	case "del" : delLeaveWord();break;
	case "reply" : replyLeaveWord();break;
	default : viewmain();break;
}

function main() {
	return "<div class='leaveNavInfo'><h3><span id='adminleaveword'></span>".siteName."留言板</h3></div>";
}

function transferSpecialStr($str){
	if (isExistStr($str, "{URL}")) {
		$str = preg_replace(buildregx("{URL}(\S+?){/URL}","is"),"<a target=\"_blank\" href=\"$1\">$1</a>",$str);
	}else{
		$str = preg_replace(buildregx("(http://\S+)[\s|\n]*","is"),"<a target=\"_blank\"  href=\"$1\">$1</a>",$str);
	}
	return $str;
}

function viewmain() {
	global $t1;
	$templatePath = DJCMS_TEMPLATE."gbook.html";
	$cacheName="parse_book_";
	if (cacheStart==1){
		if (!djcms::$content = memory('get', $cacheName)){
            parseBook($templatePath);
            memory('set', $cacheName, djcms::$content);
        }
    }else{
		parseBook($templatePath);
    }
	echo replaceStr(replaceStr(djcms::$content,"{gbook:viewLeaveWord}",viewLeaveWord()),"{djcms:runinfo}",getRunTime($t1));
}

function parseBook($x) {
	djcms::$content=loadFile($x);
	djcms::parseTopAndFoot();
	djcms::parseSelf();
	djcms::parseGlobal();
	djcms::$content = replaceCurrentTypeId(djcms::$content);
	djcms::$content = replaceStr(djcms::$content,"{gbook:main}",main());
	djcms::parseMenuList("");
	djcms::parseAreaList();
	djcms::parseTopicList();
	djcms::parseVideoList();
	djcms::parseNewsList();
	djcms::parseLinkList();
	djcms::parseIf();
}

function replyLeaveWord() {
	if (!isLogin()) die("err");
	$id=getForm("id","get");
	$m_content = transferSpecialStr(filterDirty(unescape(getForm("m_replycontent","post"))));
	$m_ip=getIp();
	if (empty($id)){
		die("err");
	}else{
		if (!is_numeric($id)) { echoSaveStr("safe");exit(); } else { $id = intval($id);}
	}
	$wordarr = array(
	'm_replyid' => $id,
	'm_content' => $m_content,
	'm_ip' => $m_ip,
	);
	DB::insert('leaveword', $wordarr);
	echo "ok";
}

function delLeaveWord() {
	if (!isLogin()) die("err");
	$id = getForm("id","get");
	$ptype = intval(getForm("type","get"));
	if ($ptype == 1) DB::delete('leaveword', array('m_id' => $id));
	DB::delete('leaveword', array('m_replyid' => $id));
	echo "ok";
}

function ChleaveWord($x){
	return preg_match("/[\x80-\xff]./", $x);
}

function leaveWord() {
	global $timeSpan;
	$m_content = getForm("m_content","post");
	$m_content = encodeHtml(filterDirty(unescape($m_content)));
	if (!ChleaveWord($m_content)) die("cn");
	$m_ip = getIp();
	if (computeStrLen($m_ip)>15) $m_ip=getStrByLen($m_ip,15);
	CheckBanIP($m_ip);
	$m_content = encodeHtml(filterDirty($m_content));
	if (computeStrLen($m_content)>500) $m_content = getStrByLen($m_content,500);
	CheckBanWords($m_content);
	$m_author = encodeHtml(filterDirty(unescape(getForm("m_author","post"))));
	if (computeStrLen($m_author)>20) $m_author = getStrByLen($m_author,20);
	$m_qq = encodeHtml(filterDirty(getForm("m_qq","post")));
	if (computeStrLen($m_qq)>15) $m_qq = getStrByLen($m_qq,15);
	$m_mail = encodeHtml(filterDirty(getForm("m_mail","post")));
	if (computeStrLen($m_mail)>30) $m_mail = getStrByLen($m_mail,30);
	$m_addtime = time();
	//检查留言间隔时间；
	if (!empty($timeSpan)) {
		$row = DB::fetch_first("SELECT m_addtime FROM ".DB::table('leaveword')." WHERE m_replyid=0 AND m_ip='$m_ip' ORDER BY m_id DESC");
		if (is_array($row)) {
		    if ($m_addtime - $row['m_addtime'] < $timeSpan) {
		        die("haveleave");
		    }
		}
	}
	$feedarr = array(
	'm_author' => $m_author,
	'm_qq' => $m_qq,
	'm_mail' => $m_mail,
	'm_content' => replacedirtyWords($m_content),
	'm_ip' => $m_ip,
	'm_addtime' => $m_addtime,
	);
	DB::insert('leaveword', $feedarr);echo "ok";
}

function logOut() {
	dsetcookie("loginflag");
}


function loginLeaveWord() {
	$m_username = unescape(getForm("m_username","post"));
	$m_pwd = unescape(getForm("m_pwd","post"));
	$m_login = unescape(getForm("m_login","post"));
	if ($m_username == gbookUser && $m_pwd == gbookPwd && $m_login == 'ok') {
		dsetcookie("loginflag", gbookUser.gbookPwd, 3600 * 24); echo "ok";
	} else {
		echo "no";
	}
}

function viewLoginState() {
	if (isLogin()) {
?>
已登陆:  <a style="color:red" onClick="logOut();return false;" href="javascript:" >退出</a>
<?php
	}else{
?>
<span onClick="viewLoginState();">留言管理</span>
<?php
	}
}

function viewLeaveWord() {
	$key = htmlspecialchars(getForm("key","get"));
    $mystr = "<div id=\"leaveword\">\n
<form id=\"f_leaveword\"   action=\"/".sitePath."gbook.php?action=add\" method=\"post\">\n
<table align=\"center\" width=\"600px\" style=\"margin:0 auto\">\n
<tr>\n
<td height=\"25\" colspan=\"2\">昵称：<input type=\"input\"  value=\"匿名\" name=\"m_author\" id=\"m_author\" size='20' /> <input type=\"hidden\" name=\"m_qq\" id=\"m_qq\"  size=10 /><input type=\"hidden\"  name=\"m_mail\"  id=\"m_mail\" size=10  />\n
<span class=\"red\">*</span></td>\n
</tr>\n
<tr>\n
<td height=\"25\" colspan=\"2\"><div id=\"facepic\" > 表情：\n
<img src=\"/".sitePath."pic/faces/18.gif\" width=\"22\" height=\"22\" onclick='addFace(\"18\")' alt=\"微笑\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/19.gif\" width=\"22\" height=\"22\" onclick='addFace(\"19\")' alt=\"憨笑\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/20.gif\" width=\"22\" height=\"22\" onclick='addFace(\"20\")' alt=\"色迷迷\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/21.gif\" width=\"22\" height=\"22\" onclick='addFace(\"21\")' alt=\"悠闲\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/22.gif\" width=\"22\" height=\"22\" onclick='addFace(\"22\")' alt=\"调皮\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/23.gif\" width=\"22\" height=\"22\" onclick='addFace(\"23\")' alt=\"大哭\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/24.gif\" width=\"22\" height=\"22\" onclick='addFace(\"24\")' alt=\"惊讶\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/25.gif\" width=\"22\" height=\"22\" onclick='addFace(\"25\")' alt=\"扁你\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/26.gif\" width=\"22\" height=\"22\" onclick='addFace(\"26\")' alt=\"很囧\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/27.gif\" width=\"22\" height=\"22\" onclick='addFace(\"27\")' alt=\"愤怒\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/28.gif\" width=\"22\" height=\"22\" onclick='addFace(\"28\")' alt=\"偷笑\" style=\"cursor:pointer\"/>\n
<img src=\"/".sitePath."pic/faces/29.gif\" width=\"22\" height=\"22\" onclick='addFace(\"29\")' alt=\"痛苦啊\" style=\"cursor:pointer\"/>\n
</div></td>\n
  </tr>\n

     <tr>\n
     	<td width=550 colspan=\"2\" valign=\"top\">内容：<textarea cols=\"40\" name=\"m_content\" id=\"m_content\" rows=\"5\"  >";
		if (!empty($key)) $mystr.="您好，我想看".$key.",多谢了" ;
		$mystr .= "</textarea>　<span class=\"red\">*</span></td>\n
  </tr>\n

  <tr>\n
    <td height=\"30\" colspan=\"2\">　　　<input type=\"button\" value=\"提交留言\"  onclick=\"leaveWord()\" class=\"btn\"/>　<input type=\"reset\" value=\"重新留言\" class=\"btn\" /></td> </tr>\n
</table></form>\n
</div>\n
<div id=\"leavewordlist\"  align=\"center\"></div>\n
<script>setLoginState();viewLeaveWordList(1);</script>\n
<br /><br />" ;
return $mystr;
}

function leaveWordList() {
	$page = getForm("page","get");
	$number = 10;
	$sqlStr="SELECT m_id,m_author,m_qq,m_mail,m_content,m_ip,m_addtime FROM ".DB::table('leaveword')." WHERE m_replyid=0 ORDER BY m_id DESC";
	$allRecordset = db::getCount($sqlStr);
	$tpagecount = ceil($allRecordset / $number);
	if ($page > $tpagecount) $page = $tpagecount;
	if ($allRecordset > 0) {
	    $i=1;
		$page = max(intval($page), 1);
        $offset = $number*($page-1);
		$query = DB::query("$sqlStr LIMIT $offset, $number");
	    while ($row = DB::fetch($query)) {
		    $rowl = DB::fetch_first("SELECT m_content FROM ".DB::table('leaveword')." WHERE m_replyid=".$row['m_id']);

?>
	<ul>
        <li class="topwords"><span><strong><?=$row['m_author']?></strong> 发表于 <?=MyDate("Y-m-d H:i:s",$row['m_addtime'])?>
        </span>
		<?php if (isLogin()) {
				echo " <a href=\"javascript:void(0)\" class='red'  onclick=\"if(confirm('确定删除该留言及回复吗')){delLeaveWord(".$row['m_id'].",".$page.",1);return false;}\">删除</a> | ";

				if (!is_array($rowl)) {
					echo "<a href=\"javascript:void(0)\" class='red' onclick=\"replyLeaveWord(".$row['m_id'].",".$page.");return false;\">回复</a> | ";
				} else {

					echo "<a href=\"javascript:void(0)\"  class='red' onclick=\"if(confirm('确定删除该回复吗')){delLeaveWord(".$row['m_id'].",".$page.",2);return false;}\">删除回复</a> | ";

				}

		}

		?>  第<?=($allRecordset - $i - ($page - 1) * $number + 1)?> 楼 </li>
        <li class="words"><?=showFace($row['m_content'])?></li>
		 <?php
			if(is_array($rowl)) echo "<li class=\"rewords\"><em>回复内容:</em>".$rowl['m_content']."</li>";
		?>
    </ul>
    <?php
	$i = $i + 1;
   }
 }else{
	echo "<ul><li class=\"words\">当前没有留言</li></ul>";
}
?><div class="page"><span>
共<?=$tpagecount?>页</span>
<?php if ($page==1){?>
<em class='nolink'>首页</em><em class='nolink'>上一页</em>
<?php }else{?>
<a title="首页" href='javascript:' onClick="viewLeaveWordList(1);return false;" >首页</a><a title="前一页" href='javascript:' onClick="viewLeaveWordList(<?php echo ($page-1);?>);return false;">上一页</a>
<?php }?>
		<?php
		$x = $page-5;$y = $page+5;
		if ($x < 1) $x = 1;
		if ($y > $tpagecount) $y = $tpagecount;
		for ($m = $x;$m <= $y;$m++) {
			if($page == $m) {
				echo "<em>".$m."</em> ";
			} else {
				echo " <a onclick=\"viewLeaveWordList(".$m.");return false;\" href='javascript:'>".$m."</a>";
			}
		}
		?>
        <?php if ($page==  $tpagecount){?>
        <em class='nolink'>下一页</em><em class='nolink'>尾页</em>
        <?php } else {?>
		<a title="下一页" onClick="viewLeaveWordList(<?=($page+1)?>);"  href='javascript:'>下一页</a> <a title="最后一页" onClick="viewLeaveWordList(<?=$tpagecount?>)"  href='javascript:'>尾页</a>
        <?php }?>
    </div>

<?php
}

function isLogin(){
	if (getcookie("loginflag") == gbookUser.gbookPwd){ return true; } else { return false;}
}

function CheckBanWords($m_content)
{
	$BanWords = BanWords;
	if (empty($BanWords) || empty($m_content)) return "";
	$Ban = explode(",",$BanWords);$l = count($Ban);
	for ($i = 0;$i < $l;$i++) {
		if (strpos(" ".$m_content,$Ban[$i])>0) die("haveleave");
	}
}

function CheckBanIP($m_ip)
{
	$BanIPS=banIPS;
	if (empty($BanIPS) || empty($m_ip)) return "";
	$Ban = explode(",",ReplaceStr($BanIPS," ",""));$l=count($Ban);
	if (strpos(" ,".$BanIPS.",",",".$m_ip.",")>0) die("havecomment");
	for ($i = 0;$i < $l;$i++) {
		if(strpos(" ".$Ban[$i], "*") > 0) {
			$x = explode(".",$Ban[$i]);
			$y = explode(".",$m_ip);
			if (count($x) >= 3) {
				if (($x[0]==$y[0] || $x[0]=="*") && ($x[1]==$y[1] || $x[1]=="*") && ($x[2]==$y[2] || $x[2]=="*") && ($x[3]==$y[3] || $x[3]=="*")) {
					die("haveleave");
		        }
		    }
		} else if ($Ban[$i] == $m_ip) {
			die("haveleave");
		}
	}
}
?>
