<?php

//引入核心文件
require_once 'common.php';

//连接到MYSQL并打开系统数据库
$DataBase->open_db();
//读取导航条信息
$DataBase->sel('nav', "ORDER BY `order` ASC");
//关闭数据库连接
$DataBase->close_dblink();
//将导航条信息赋值给模板
$smarty->assign('HeaderNavList', $DataBase->Result);

//留言板关闭
if(CLOSE == 1){
	if($AdminLogin->CheckLogin() == false){
		if(C_REASON !== ''){
			$C_REASON = '关闭原因：'.C_REASON;
		}
		else{
			$C_REASON = '';
		}
		ShowMessage("留言板已关闭！", 2, $C_REASON, "", WEB_URL.'/index.php', 1);
		exit();
	}
}

//首页
if($Action == ''){
	//连接到MYSQL并打开系统数据库
	$DataBase->open_db();
	//读取全部留言信息
	$DataBase->sel("message", "ORDER by `id` ".ORDER);
	//关闭数据库连接
	$DataBase->close_dblink();
	
	//留言统计 和 前台显示的留言处理
	//统计数值初始化
	$MessageNum = 0;	//留言总数
	$CheckNum = 0;		//已审核留言数
	$TodayNum = 0;		//今天留言数
	$YesterDayNum = 0;		//昨天留言数
	$TopMessage = '';		//置顶留言
	$MessageId = 1;		//留言编号

	//如果没有留言，则定义为空数组
	if(is_array($DataBase->Result) == false){
		$DataBase->Result = array();
	}
	
	foreach($DataBase->Result as $k => $v){		
		if($v['check'] == 0 || $v['check'] == 1){	//总数值=已审核+未审核的留言
			$MessageNum++;
		}
		if($v['check'] == 1){	//前台页面显示的留言=已审核的留言
			$CheckNum++;
		}
		if(date("Y-m-d", strtotime($v['time'])) == date("Y-m-d")){	//今天留言数
			$TodayNum++;
		}
		if(date("Y-m-d", strtotime($v['time'])) == date("Y-m-d", strtotime("-1 day"))){	//今天留言数
			$YesterDayNum++;
		}		
		if($v['check'] == 0 || $v['check'] == 2){	//删除未审核的留言和回收站中的留言
			unset($DataBase->Result[$k]);
		}
		if($v['id'] == TOP_MESSAGE && $v['check'] == 1 && $page == 1){		//置顶留言处理
			$TopMessage = $DataBase->Result[$k];
			$TopMessage['content'] = stripslashes_d($TopMessage['content']);
			$TopMessage['qqnum'] = $TopMessage['qq'];
			//处理隐私保护内容
			if($TopMessage['privacy'] == 2){
				if($AdminLogin->CheckLogin() == false){
					$TopMessage['qq'] = qqEncrypt($TopMessage['qq']);
					$TopMessage['mobile'] = phoneEncrypt($TopMessage['mobile']);
					$TopMessage['email'] = emailEncrypt($TopMessage['email']);
				}
			}						
		}
		if($v['id'] == TOP_MESSAGE && $v['check'] == 1){
			unset($DataBase->Result[$k]);	//如果留言置顶则不在列表中显示，所以删除
		}
	}
	//重新排序
	$DataBase->Result = array_values($DataBase->Result);
	
	//分页处理
	$PageC = new PageC();	//实例化分页类
	$PageC->Page = $page;		//当前页码
	$PageC->Total = count($DataBase->Result);	//查询总数
	$PageC->PageSize = 10;	//每页显示条数
	//链接样式
	if(REWRITE == 0){
		$PageC->Url = WEB_URL.'/index.php?page={#Page}';	//动态链接样式
	}
	elseif(REWRITE == 1){
		$PageC->Url = WEB_URL.'/page-{#Page}.html';	//模拟静态链接样式
	}
	$PageUrlList = $PageC->CreatePageCodeList(1);	//分页连接
	
	//当前页列表
	$MessageList = array();
	for($i=($PageC->Pg()); $i<($PageC->Pg())+$PageC->PageSize; $i++){
		if(isset($DataBase->Result[$i])){
			$MessageList[$i] = $DataBase->Result[$i];
			$MessageList[$i]['MessageId'] = $MessageId++;
			$MessageList[$i]['content'] = stripslashes_d($MessageList[$i]['content']);	//留言内容去除转义
			$MessageList[$i]['qqnum'] = $MessageList[$i]['qq'];
			//处理隐私保护内容
			if($MessageList[$i]['privacy'] == 2){
				if($AdminLogin->CheckLogin() == false){
					$MessageList[$i]['qq'] = qqEncrypt($MessageList[$i]['qq']);
					$MessageList[$i]['mobile'] = phoneEncrypt($MessageList[$i]['mobile']);
					$MessageList[$i]['email'] = emailEncrypt($MessageList[$i]['email']);
				}	
			}
		}
	}	
	
	//赋值给模板
	$smarty->assign('MessageNum', $MessageNum);		//留言总数
	$smarty->assign('TodayNum', $TodayNum);		//今日留言
	$smarty->assign('YesterDayNum', $YesterDayNum);		//昨日留言
	$smarty->assign('NoCheckNum', $MessageNum - $CheckNum);		//未审核留言
	$smarty->assign('TopMessage', $TopMessage);		//置顶留言
	
	$smarty->assign('MessageList', $MessageList);	//留言列表
	$smarty->assign('PageUrlList', $PageUrlList);	//分页链接
	
	//显示首页模板
	$smarty->display("index.html");
	exit();
}

//搜索留言页
if($Action == 'search'){
	if(isset($_GET['keywords'])){
		$KeyWords = $_GET['keywords'];	//搜索关键词，安全过滤待完善
		$KeyWords = ToUtf8($KeyWords);
		if($KeyWords !== ''){
			//处理关键字
			$KeyWordsArr = explode(' ', $KeyWords);		//以一个空格为分割符拆分成数组
			foreach($KeyWordsArr as $k => $v){
				$v = trimall($v);	//删除所有空格
				if($v == ''){
					unset($KeyWordsArr[$k]);	//删除多余的空格
				}
			}
			$KeyWordsArr = array_values($KeyWordsArr);	//将数组重新排序
			//将关键词连接并传递给模板
			$ShowKeyWords = '';
			foreach($KeyWordsArr as $KeyW){
				$ShowKeyWords .= ' '.$KeyW;
			}
			$smarty->assign('showkeywords', $ShowKeyWords.' ');
			//连接到MYSQL并打开系统数据库
			$DataBase->open_db();
			//读取全部已审核留言信息
			$DataBase->sel("message", "WHERE `check` = '1' ORDER by `id` ".ORDER);
			//创建变量用于存放搜索结果集
			$search_details_arr = array();
			//将关键字与每一条留言进行匹配
			foreach($DataBase->Result as $k => $v){
				foreach($KeyWordsArr as $kw){
					if(strstr(DeleteHtml($v['content']), $kw) !== false){
						//处理留言内容
						if($v['secret'] == 1){
							if($AdminLogin->CheckLogin() == false){
								$v['content'] = "<div class='admin_reply_box'>此留言内容仅管理员可见</div>";
							}
						}
						else{
							$v['content'] = cutout_str(DeleteHtml($v['content']), 70);
						}
						array_push($search_details_arr, $v);					
					}
				}
			}
			//去除重复结果
			$search_details_arr = assoc_unique($search_details_arr, 'id');
			//分页代码开始----------------
			//分页处理
			$PageC = new PageC();	//实例化分页类
			$PageC->Page = $page;		//当前页码
			$PageC->Total = count($search_details_arr);	//查询总数
			$PageC->PageSize = 10;	//每页显示条数
			//链接样式
			$PageC->Url = WEB_URL.'/index.php?action=search&keywords='.$KeyWords.'&page={#Page}';	//动态链接样式
			$PageUrlList = $PageC->CreatePageCodeList(1);	//分页连接
			
			//当前页列表
			$thispage_search_details_arr = array();
			for($i=($PageC->Pg()); $i<($PageC->Pg())+$PageC->PageSize; $i++){
				if(isset($search_details_arr[$i])){
					$thispage_search_details_arr[$i] = $search_details_arr[$i];
				}
			}			
			//分页代码结束----------------
			//将分页链接赋值给模板
			$smarty->assign('PageUrlList', $PageUrlList);			
			//将搜索结果集赋值给模板
			$smarty->assign('thispage_search_details_arr', $thispage_search_details_arr);
			$smarty->assign('search_details_arr', $thispage_search_details_arr);
			//关闭数据库连接
			$DataBase->close_dblink();
			//显示搜索结果页模板
			$smarty->display('search.html');				
		}
		else{
			if(isset($_SERVER['HTTP_REFERER'])){
				HgoToUrlExit($_SERVER['HTTP_REFERER']);
			}
			else{
				HgoToUrlExit(WEB_URL);
			}
			exit();		//关键词为空
		}
	}
}

//搜索结果查看详细页
if($Action == 'search_details'){
	if(isset($_GET['id'])){
		$search_id = ToUtf8(trimall(DeleteHtml($_GET['id'])));
		if(check_zzs($search_id)){
			//连接到MYSQL并打开系统数据库
			$DataBase->open_db();
			//查询留言信息
			$DataBase->sel("message", "WHERE `id` = '$search_id'");
			if(count($DataBase->Result) !== 1){
				ShowMessage("此留言不存在！", 2, "", "", WEB_URL.'/index.php', 1);
			}
			else{
				//留言内容去除转义
				$DataBase->Result[0]['content'] = stripslashes_d($DataBase->Result[0]['content']);
				//处理QQ头像
				$DataBase->Result[0]['qqnum'] = $DataBase->Result[0]['qq'];
				//处理隐私保护内容
				if($DataBase->Result[0]['privacy'] == 2){
					if($AdminLogin->CheckLogin() == false){
						$DataBase->Result[0]['qq'] = qqEncrypt($DataBase->Result[0]['qq']);
						$DataBase->Result[0]['mobile'] = phoneEncrypt($DataBase->Result[0]['mobile']);
						$DataBase->Result[0]['email'] = emailEncrypt($DataBase->Result[0]['email']);
					}
				}			
				//将留言信息传递给模板
				$smarty->assign('SearchMessage', $DataBase->Result[0]);
			}
			//关闭数据库连接
			$DataBase->close_dblink();
			//显示留言详情模板
			$smarty->display("search_details.html");
		}
	}
}

//签写留言页
if($Action == 'post'){
	//是否开启留言功能
	if(NEW_POST == 1){
		//生成input_key
		$_SESSION['PostInputKey'] = generate_rand_string(50);
		//将input_key赋值给模板
		$smarty->assign('PostInputKey', $_SESSION['PostInputKey']);
		//显示签写留言页面模板
		$smarty->display("post.html");
		exit();
	}
	elseif(NEW_POST == 0){
		ShowMessage("留言功能已关闭！", 2, "", "", WEB_URL.'/index.php', 1);
		exit();		
	}
}

//回复留言页
if($Action == 'reply'){
	if(isset($_GET['id'])){
		//生成input_key
		$_SESSION['ReplyInputKey'] = generate_rand_string(50);
		//将input_key赋值给模板		
		$smarty->assign('ReplyInputKey', $_SESSION['ReplyInputKey']);		
		if($_GET['id'] == 'sel'){
			$smarty->assign('GetId', $_GET['id']);
			$smarty->display("reply.html");
			exit();
		}
		elseif(check_zzs($_GET['id'])){
			$ReplyId = $_GET['id'];	//留言ID，过滤方法待写
			//连接到MYSQL并打开系统数据库
			$DataBase->open_db();
			//查询留言信息
			$DataBase->sel('message', "WHERE `id` = '$ReplyId'");
			//关闭数据库连接
			$DataBase->close_dblink();
			$smarty->assign('GetId', $ReplyId);	//留言ID
			$smarty->assign('Content', cutout_str(DeleteHtml($DataBase->Result[0]['content']), 70));	//留言内容摘要
			$smarty->assign('ReplyMessage', $DataBase->Result[0]);
			$smarty->display("reply.html");
			exit();			
		}
		else{
			exit();
		}
	}
}

//编辑留言页
if($Action == 'edit'){
	if(isset($_GET['id'])){
		//编码转换
		$EditId = ToUtf8($_GET['id']);
		//数据过滤
		$EditId = addslashes(trimall($EditId));
		//判断ID是否正整数
		if(check_zzs($EditId)){
			//生成input_key
			$_SESSION['EditInputKey'] = generate_rand_string(50);
			//将input_key赋值给模板
			$smarty->assign('EditInputKey', $_SESSION['EditInputKey']);
			//将留言ID赋值给模板
			$smarty->assign('GetId', $_GET['id']);
			//连接到MYSQL并打开系统数据库
			$DataBase->open_db();
			//查询留言信息
			$DataBase->sel('message', "WHERE `id` = '$EditId'");
			if(count($DataBase->Result) == 1){
				//留言内容去除转义处理
				$DataBase->Result['0']['content'] = stripslashes_d($DataBase->Result['0']['content']);
				//留言内容传递给模板
				$smarty->assign('EditMsg', $DataBase->Result['0']);
			}
			//关闭数据库连接
			$DataBase->close_dblink();
			//显示编辑页面模板
			$smarty->display("edit.html");
			exit();
		}
		else{	//不是正整数
			echo 'Error!';
			exit();
		}				
	}
}

//显示验证码
if($Action == 'checkcode'){
	$ValidateCode = new ValidateCode();      //实例化一个对象
	$ValidateCode -> doimg();
	$_SESSION['PostValidateCode'] = $ValidateCode -> getCode();
	exit();
}

if($Action == 'checkinput'){
	if(isset($_POST['inputname']) && isset($_POST['value'])){
		echo AjaxCheckInput($_POST['inputname'], $_POST['value']);
	}
}

//提交留言
if($Action == "submit"){
	if(NEW_POST == 0){
		ShowMessage("留言功能已关闭！", 2, "", "", WEB_URL.'/index.php', 1);
		exit();
	}	
	if(!isset($_POST['MessageContentText'])){
		$_POST['MessageContentText'] = '';
	}
	//是否提交表单
	if($UserRequest->IsPost(array('RadioGroup1', 'NickName', 'QQ', 'Phone', 'Mail', 'SecretOptions', 'MessageContentText', 'ValidateCode', 'PostInputKey'), 'SubmitButton')){
		//来路判断
		if($UserRequest->CheckHttpReferer(array(WEB_URL.'/index.php?action=post', WEB_URL.'/post.html')) == true){
			//定义过滤方法
			$UserRequest->CheckPostFun = array(
					'RadioGroup1' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), array('check_zzs', 'strlen_only_one', 'CheckNull')),
					'NickName' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), array('strlen_nickname', 'CheckNull')),
					'QQ' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), 'check_qqnum'),
					'Phone' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), 'CheckPhone'),
					'Mail' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), 'CheckMail'),
					'SecretOptions' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), array('CheckSecretOptions', 'CheckNull')),
					'MessageContentText' => array(array('ToUtf8', 'ContentHtmlToStr', 'addslashes_d'), 'CheckNull'),
					'ValidateCode' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), array('CheckValidateCode', 'CheckNull')),
					'PostInputKey' => array(array('ToUtf8', 'trimall', 'DeleteHtml', 'strip_tags'), array('CheckPostInputKey', 'CheckNull'))
			);
			//验证提交的信息
			if($UserRequest->CheckPostValue()){
				//经过验证的数据
				$UserPostData = $UserRequest->Post;
				//比对inputkey
				if($UserRequest->CheckValue($UserPostData['PostInputKey'], $_SESSION['PostInputKey'])){
					if(CheckVCset('post') == true){
						//比对验证码
						if($UserRequest->CheckValue(strtolower($UserPostData['ValidateCode']), $_SESSION['PostValidateCode']) == false){
							ShowMessage("验证码错误！", 2, "", "", WEB_URL.'/index.php', 1);
							exit();
						}
					}
					//判断QQ号码是否必填
					if($UserPostData['RadioGroup1'] == 7){
						if($UserPostData['QQ'] == ''){
							ShowMessage("您填写的内容不符合要求！", 2, "", "", WEB_URL.'/index.php', 1);
							exit();
						}
					}
					//连接到MYSQL并打开系统数据库
					$DataBase->open_db();
					//将留言内容添加到数据库
					$AddMessageRI = $DataBase->Add('message', array('time' => GetNowTime(), 'writer' => $AdminLogin->GetUserName(), 'content' => $UserPostData['MessageContentText'], 'reply' => '', 'avatar' => $UserPostData['RadioGroup1'], 'nickname' => $UserPostData['NickName'], 'qq' => $UserPostData['QQ'], 'mobile' => $UserPostData['Phone'], 'email' => $UserPostData['Mail'], 'ip' => GetClientIp(), 'secret' => SecretOptions($UserPostData['SecretOptions'], 'secret'), 'privacy' => SecretOptions($UserPostData['SecretOptions'], 'privacy'), 'check' => NewMessageCheck()));
					//关闭数据库连接
					$DataBase->close_dblink();
					if($AddMessageRI == true && MESSAGE_CHECK == 0){
						ShowMessage("留言成功！", 1, "", "", WEB_URL.'/index.php', 1);
					}
					elseif($AddMessageRI == true && MESSAGE_CHECK == 1){
						ShowMessage("留言提交成功，请等待管理员审核！", 1, "", "", WEB_URL.'/index.php', 1);
					}
					else{
						ShowMessage("留言失败！（错误代码：9）", 2, "", "", WEB_URL.'/index.php', 1);
					}
				}
				else{
					ShowMessage("提交失败！（错误代码：8）", 2, "", "", WEB_URL.'/index.php', 1);
				}
			}
			else{
				ShowMessage("您填写的内容不符合要求！", 2, "", "", WEB_URL.'/index.php', 1);
			}
		}
		else{
			ShowMessage("来路不正确！", 2, "", "", WEB_URL.'/index.php', 1);
		}
		//销毁inputkey和验证码确保只能使用一次
		$_SESSION['PostInputKey'] = '';
		$_SESSION['PostValidateCode'] = '';		
	}
	else{
		ShowMessage("表单未提交！", 2, "", "", WEB_URL.'/index.php', 1);
	}
}

?>