<?php
/********密码验证***********/
$password='123456';				                   //这个密码是登陆验证用的.您需要在模块里设置和这里一样的密码....注意一定需要修改.
if($password!=$_GET['pw']) exit('验证密码错误');   //安全检测,密码不符则退出


/******随机回复用户名设置,用户可自行修改******/
$replyers="";            //随机回复的用户名,为空的话则不使用,多个用户名之间用 , 分开,如 $replyers="'admin2','admin3'";  


/******以下代码加载并设置数据库配置,非专业人员不建议修改********/
include('config/config_global.php');					//加载数据库配置
$dbhost=$_config['db']['1']['dbhost'];
$dbuser=$_config['db']['1']['dbuser'];
$dbpw=$_config['db']['1']['dbpw'];
$dbname=$_config['db']['1']['dbname'] ;
$tablepre=$_config['db']['1']['tablepre'];
$dbcharset = 'utf8';			                       // MySQL 字符集, 可选 'gbk', 'big5', 'utf8', 'latin1', 留空为按照论坛字符集设定
$charset = 'utf8';			                       // 论坛页面默认字符集, 可选 'gbk', 'big5', 'utf-8'


/****以下代码对数据进行安全过滤,非专业人员不建议修改***************/
@set_magic_quotes_runtime(0);
$timestamp=time();

if(PHP_VERSION < '4.1.0') {
	$_GET = &$HTTP_GET_VARS;
	$_POST = &$HTTP_POST_VARS;
	$_COOKIE = &$HTTP_COOKIE_VARS;
	$_SERVER = &$HTTP_SERVER_VARS;
	$_ENV = &$HTTP_ENV_VARS;
	$_FILES = &$HTTP_POST_FILES;
}

if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) {
	exit('Request tainting attempted.');
}

foreach(array('_COOKIE', '_POST', '_GET') as $_request) {
	foreach($$_request as $_key => $_value) {
	  $$_key = daddslashes($_value);
	}
}

if (!get_magic_quotes_gpc() && $_FILES) {
	$_FILES = daddslashes($_FILES);
}

/*****************以下是核心的处理代码******************/

$db=new db($dbhost,$dbuser,$dbpw,$dbname,$charset,$dbcharset);//创建数据库链接

$cates=$db->get_array("Select fid as cid,fup as pid,name as cname,type from {$tablepre}forum_forum where  status=1 order by displayorder");//先获取分类信息

if($_POST){
	extract($_POST,EXTR_OVERWRITE);//获取POST过来的参数
	if(!$title){
		exit('标题不能为空');
	}
	if(!$content){
		exit('内容不能为空');
	}
	if(!$cid){
		exit('栏目不能为空');
	}
	if(!$username){
		exit('用户名不能为空');
	}
	foreach ($cates as $f=>$v)
	{
		if($v['cid']==$cid)
		{		
			$eid=$v;
			$cname=$v['cname'];
			if($v['type']=='group') exit("该栏目不能发布内容"); 
		}
	}
	if(!$eid) exit("不存在的版块id:$cid");
	
	$replys=array($content);
	if(strpos($content,'|||')>0)
	{
		$replys=explode('|||',$content);
		$content=$replys[0];
	}
	
	if(count($replys)>1&&$replyers)
	{
		$timestamp=$timestamp-count($replys)*500;
	}
	$spidertimes=array();

	if($spidertime)
	{
		if($spidertime!='[标签:时间]')
		{
			$spidertimes=explode('|||',$spidertime);
			if(count($spidertimes)!=count($replys)+1) $spidertimes=array();
			else $timestamp=strtotime($spidertimes[0]);
		}
	}
	
	$smileyoff=0;
	$status=0;
	$price=0;
	$iconid='';
	$bbcodeoff=0;

	/***以上为数据检测及赋值**/	
	$userinfo=$db->fetch_first("Select uid as uid from {$tablepre}common_member where username='$username'");
	if(!$userinfo) exit("不存在用户$username");
	$uid=$userinfo['uid'];

	//处理tag
	$tagarray=array();
	if($tags) 
	{
		$tags = str_replace(array(chr(0xa3).chr(0xac), chr(0xa1).chr(0x41), chr(0xef).chr(0xbc).chr(0x8c)), ',', $tags);
		if(strpos($tags, ',')) {
			$tagarray = array_unique(explode(',', $tags));
		} else {
			$tags = str_replace(array(chr(0xa1).chr(0xa1), chr(0xa1).chr(0x40), chr(0xe3).chr(0x80).chr(0x80)), ' ', $tags);
			$tagarray = array_unique(explode(' ', $tags));
		}
	}
	

	$tag=implode(' ',$tagarray);
	$hits=mt_rand(0,199);
	//先处理主题
	$sql="INSERT INTO {$tablepre}forum_thread (fid, posttableid, readperm, price, typeid, sortid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, special, attachment, moderated, status, isgroup)VALUES ('$cid', '', '0', '0', '0', '0', '$username', '$uid', '$title', '$timestamp', '$timestamp', '$username', '0', '0', '0', '0', '0', '0', '0')";
	$db->query($sql);
	$tid=$db->insert_id();
	$db->query("UPDATE  {$tablepre}common_member_field_home SET `recentnote`='$title' WHERE `uid`='$uid'");
	
	//主题回复这块是一样的
	if($replyers)
	{
		$sql="Select `uid`, `username` from {$tablepre}common_member where username in ($replyers)";
		$result=$db->get_array($sql);
	
	}

	$replycount=-1;
	$first=1;
	if(!$interval) $interval=500;
	foreach($replys as $content)
	{
		$htmlon=0;
		if(strpos($content,'<')!==false) 
		{
			$bbcodeoff=1;
			$htmlon=1;
		}
		$timestamp+=rand(60,$interval);
		if($spidertimes) $timestamp=strtotime($spidertimes[$replies+1]);
		$db->query("INSERT INTO {$tablepre}forum_post_tableid SET `pid`=''");
		$pid=$db->insert_id();
		$db->query("INSERT INTO {$tablepre}forum_post SET `fid`='$cid',`tid`='$tid',`first`='$first',`author`='$username',`authorid`='$uid',`subject`='$title',`dateline`='$timestamp',`message`='$content',`useip`='',`invisible`='0',`anonymous`='0',`usesig`='1',`htmlon`='$htmlon',`bbcodeoff`='$bbcodeoff',`smileyoff`='$smileyoff',`parseurloff`='$parseurloff',`attachment`='0',`tags`='$tag',`pid`='$pid'");
		$db->query("REPLACE INTO {$tablepre}common_syscache (cname, ctype, dateline, data) VALUES ('max_post_id', '0', '$timestamp', '$pid')");
		$db->query("UPDATE {$tablepre}common_member_count SET extcredits1=extcredits1+'0',extcredits2=extcredits2+'2',extcredits3=extcredits3+'0',threads=threads+'1',posts=posts+'1' WHERE uid IN ('$uid')");
		$db->query("UPDATE {$tablepre}common_credit_rule_log SET cyclenum=cyclenum+1,total=total+1,dateline='$timestamp',extcredits1='0',extcredits2='2',extcredits3='0' WHERE clid='2'");
		$db->query("UPDATE  {$tablepre}common_member SET `credits`=`credits`+1 WHERE `uid`='$uid'");
		$db->query("UPDATE {$tablepre}common_member_status SET lastpost='$timestamp' WHERE uid IN ('$uid')");
		
		$first=0;
		$replycount++;
		
		if(count($replys)>1)
		{		
			if($result)
			{
				$rnd=array_rand($result);
				$uid=$result[$rnd]['uid'];
				$username=$result[$rnd]['username'];
			}
			$title='';
		}else
		{
			if(!$replyers) break;//如果没有设置那个随机用户的话就不发布回复
		}
	}

	$db->query("UPDATE {$tablepre}forum_forum SET lastpost='$tid	$title	$timestamp	$username', threads=threads+1, posts=posts+$replycount+1, todayposts=todayposts+$replycount+1 WHERE fid='$cid'");
	$dt=date("yymd");
	$db->query("UPDATE {$tablepre}common_stat SET `thread`=`thread`+$replycount WHERE daytime='$dt'");
	$db->query("UPDATE {$tablepre}forum_thread SET lastposter='$username', lastpost='$timestamp', replies=replies+$replycount WHERE tid='$tid'");
	$db->query("UPDATE LOW_PRIORITY {$tablepre}forum_thread SET views=views+$hits WHERE tid='$tid'");
	exit("发布成功");
}else
{
	echo "<select name='list'>";
	echo maketree($cates,0,'');
	echo '</select>';
}

/***生成目录的一个遍历算法***/
function maketree($ar,$id,$pre)
{
	$ids='';
	foreach($ar as $k=>$v){
		$pid=$v['pid'];
		$cname=$v['cname'];
		$cid=$v['cid'];
		if($pid==$id)
		{
			$ids.="<option value='$cid'>{$pre}{$cname}</option>";
			foreach($ar as $kk=>$vv)
			{
				$pp=$vv['pid'];
				if($pp==$cid)
				{ 
					$ids.=maketree($ar,$cid,$pre."&nbsp;&nbsp;");
					break;
				}
			}
		}
	}
	return $ids;
}

/****************************以下为公共类库及函数库******************************/
function daddslashes($string)
{
	if(is_array($string)) 
	{
		foreach($string as $key => $val) 
		{
			$string[$key] = daddslashes($val);
		}
	}
	else
	{
		$string = addslashes($string);
	}
	return $string;
}


/*当前为数据库操作类库*/
class db {

	var $mlink;

	function db($dbhost, $dbuser, $dbpw, $dbname = '',$charset='gbk',$dbcharset='gbk', $pconnect=0){
		if($pconnect){
			if(!$this->mlink = @mysql_pconnect($dbhost, $dbuser, $dbpw)){
				$this->halt('Can not connect to MySQL');
			}
		} else {
			if(!$this->mlink = @mysql_connect($dbhost, $dbuser, $dbpw)){
				$this->halt('Can not connect to MySQL');
			}
		}
		if($this->version()>'4.1'){
			if('utf-8'==strtolower($dbcharset)){
				$dbcharset='utf8';
			}
			if($dbcharset){
				mysql_query("SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary", $this->mlink);
			}
			if($charset){
				mysql_query("SET $charset", $this->mlink);
			}
			
			if($this->version() > '5.0.1'){
				mysql_query("SET sql_mode=''", $this->mlink);
			}
		}
		if($dbname){
			mysql_select_db($dbname, $this->mlink);
		}
	}

	function select_db($dbname){
		return mysql_select_db($dbname, $this->mlink);
	}
	
	function get_array($sql){
		$list = array();
		$query=$this->query($sql);
		while($row=$this->fetch_array($query)){
			$list[]=$row;
		}
		return $list;
	}
	
	function fetch_array($query, $result_type = MYSQL_ASSOC){
		return (is_resource($query))? mysql_fetch_array($query, $result_type) :false;
	}

	function result_first($sql){
		$query = $this->query($sql);
		return $this->result($query, 0);
	}

	function fetch_first($sql){
		$query = $this->query($sql);
		return $this->fetch_array($query);
	}
	
	
	function fetch_total($table,$where='1'){
		return $this->result_first("SELECT COUNT(*) num FROM ".DB_TABLEPRE."$table WHERE $where");
	}
	
	function query($sql, $type = ''){
		global $mquerynum;
		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
		if(!($query = $func($sql, $this->mlink)) && $type != 'SILENT'){
			$this->halt("MySQL Query Error",'TRUE',$sql);
		}
		$mquerynum++;
		return $query;
	}

	function affected_rows(){
		return mysql_affected_rows($this->mlink);
	}

	function error(){
		return (($this->mlink) ? mysql_error($this->mlink) : mysql_error());
	}

	function errno(){
		return intval(($this->mlink) ? mysql_errno($this->mlink) : mysql_errno());
	}

	function result($query, $row){
		$query = @mysql_result($query, $row);
		return $query;
	}

	function num_rows($query){
		$query = mysql_num_rows($query);
		return $query;
	}

	function num_fields($query){
		return mysql_num_fields($query);
	}

	function free_result($query){
		return mysql_free_result($query);
	}

	function insert_id(){
		return ($id = mysql_insert_id($this->mlink)) >= 0 ? $id : $this->result($this->query('SELECT last_insert_id()'), 0);
	}

	function fetch_row($query){
		$query = mysql_fetch_row($query);
		return $query;
	}

	function fetch_fields($query){
		return mysql_fetch_field($query);
	}

	function version(){
		return mysql_get_server_info($this->mlink);
	}

	function close(){
		return mysql_close($this->mlink);
	}

	function halt($msg, $debug=true, $sql=''){
		@ini_set("date.timezone","Asia/Shanghai");
		$output .="<html>\n<head>\n";
		$output .="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$charset."\">\n";
		$output .="<title>$msg</title>\n";
		$output .="</head>\n<body><table>";
		$output .="<b>MySql Error Info</b><table><tr><td width='100px'><b>Message</b></td><td>$msg</td></tr>\n";
		$output .="<tr><td><b>Time</b></td><td>".date("Y-m-d H:i:s")."<br /></td></tr>\n";
		$output .="<tr><td><b>Script</b></td><td> ".$_SERVER['PHP_SELF']."<br /></td></tr>\n\n";
		$output .="<tr><td><b>SQL</b></td><td> ".htmlspecialchars($sql)."<br />\n</td></tr><tr><td><b>Error</b></td><td>  ".$this->error()."</td></tr><br />\n";
		$output .="<tr><td><b>Errno.</b></td><td>  ".$this->errno()."</td></tr></table>";
		$output .="\n</body></html>";
		echo $output;
		exit();
	}
}
?>