<?php
/*
	Discuz 7.2  gbk 帖子发布接口
	
*/

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

include('config.inc.php');//加载数据库配置
include('forumdata/cache/cache_forums.php');       //导入版块设置,$_DCACHE['forums']
$forums=$_DCACHE['forums'];                        //获取版块缓存信息
$dbcharset = 'gbk';			                       // MySQL 字符集, 可选 'gbk', 'big5', 'utf8', 'latin1', 留空为按照论坛字符集设定
$charset = 'gbk';			                       // 论坛页面默认字符集, 可选 'gbk', 'big5', 'utf-8'


$reguser=false;                                    //是否注册用户。当您提交的数据中有用户名时，程序可以自动注册用户。
$replyers="";   //随机回复的用户名,为空的话则不使用,多个用户名之间用 , 分开,如 $replyers="'admin2','admin3'";  

/****以下代码非专业人员不建议修改***************/

error_reporting(0);
@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);
}

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

if($_POST){
	//extract($_POST,EXTR_OVERWRITE);//获取POST过来的参数
	if(!$title){
		exit('标题不能为空');
	}
	if(!$content){
		exit('内容不能为空');
	}
	if(!$cid){
		exit('栏目不能为空');
	}
	if(!$username){
		exit('用户名不能为空');
	}
	foreach ($forums as $f=>$v)
	{
		if($v['fid']==$cid) $forum=$v;
		if($v['fid']==$cid&&$v['type']=='group') exit("版块分区不能发布内容"); 
	}
	if(!$forum) exit("不存在的版块id:$cid");
	if(strpos($content,'|||')>0)
	{
		$replys=explode('|||',$content);
		$content=$replys[0];
		unset($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;
	$htmlon=0;
	
	if(strpos($content,'<')!==false) 
	{
		$bbcodeoff=1;
		$htmlon=1;
	}
	

	/***以上为数据检测及赋值**/
	
	$db=new db($dbhost,$dbuser,$dbpw,$dbname,$charset,$dbcharset);
	$userinfo=$db->fetch_first("Select * from {$tablepre}members where username='$username'");
	if(!$userinfo) exit("不存在用户$username");
	$uid=$userinfo['uid'];

	$hits=mt_rand(0,199);
	$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, sortid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, special, attachment, moderated, status,views)
		VALUES ('$cid', '$readperm', '$price', '$iconid', '$typeid', '$sortid', '$username', '$uid', '$title', '$timestamp', '$timestamp', '$username', '$displayorder', '0', '$special', '0', '$moderated', '$status',$hits)");
	$tid = $db->insert_id();
	
	$content = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $content);
	$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
		VALUES ('$cid', '$tid', '1', '$username', '$uid', '$title', '$timestamp', '$content', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '0')");
	$pid = $db->insert_id();
	$db->query("UPDATE {$tablepre}members SET threads=threads+1 WHERE uid='$uid'");
	
	//现在开始添加tag
	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));
		}
		$tagcount = 0;
		foreach($tagarray as $tagname) {
			$tagname = trim($tagname);
			if(preg_match('/^([\x7f-\xff_-]|\w|\s){3,20}$/', $tagname)) {
				$query = $db->query("SELECT closed FROM {$tablepre}tags WHERE tagname='$tagname'");
				if($db->num_rows($query)) {
					if(!$tagstatus = $db->result($query, 0)) {
						$db->query("UPDATE {$tablepre}tags SET total=total+1 WHERE tagname='$tagname'", 'UNBUFFERED');
					}
				} else {
					$db->query("INSERT INTO {$tablepre}tags (tagname, closed, total)
						VALUES ('$tagname', 0, 1)", 'UNBUFFERED');
					$tagstatus = 0;
				}

				$db->query("INSERT {$tablepre}threadtags (tagname, tid) VALUES ('$tagname', $tid)", 'UNBUFFERED');

				$tagcount++;
				if($tagcount > 4) {
					unset($tagarray);
					break;
				}
			}
		}
	}
	
	//这里是统计数字
	$threads=1;
	
	
	//现在开始回复主题
	if(!$interval) $interval=500;
	if($replys&&$replyers)
	{
		//首先获取回复用户名及ID然后再循环
		$sql="Select `uid`, `username` from {$tablepre}members where username in ($replyers)";
		$result=$db->get_array($sql);
		if(count($result)>0)
		{
			$replies=0;
			foreach($replys as $content)
			{
				$timestamp+=rand(60,$interval);
				if($spidertimes) $timestamp=strtotime($spidertimes[$replies+1]);
				$rnd=array_rand($result);
				$rid=$result[$rnd]['uid'];
				$username=$result[$rnd]['username'];
				$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
					VALUES ('$cid', '$tid', '0', '$username', '$rid', '', '$timestamp', '$content', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '0')");
				$pid = $db->insert_id();
				$replies++;
				$db->query("UPDATE {$tablepre}members SET posts=posts+1 WHERE uid='$rid'");
			}
			$db->query("UPDATE {$tablepre}threads SET lastposter='$username', lastpost='$timestamp', replies=replies+$replies WHERE tid='$tid'", 'UNBUFFERED');
			$threads+=$replies;
		}
	}
	
	//更新统计
	$db->query("UPDATE {$tablepre}favoriteforums SET newthreads=newthreads+1 WHERE fid='$cid' AND uid<>'$uid'", 'UNBUFFERED');
	$lastpost = "$tid\t$title\t$timestamp\t$username";
	$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+$threads, todayposts=todayposts+$threads WHERE fid='$cid'", 'UNBUFFERED');
	if($forum['type'] == 'sub') {
		$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
	}
	exit("发布成功");
}else
{
	echo "<select name='list'>";
	echo maketree($forums,0,'');
	echo '</select>';
}

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

/****************************以下为公共类库及函数库******************************/
function daddslashes($string)
{
	if(!GET_MAGIC_QUOTES_GPC()) {
		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();
	}
}
?>