<?php

/*
EditorTools自动采集助手-DZ7.0(简体GBK、繁体big5、简繁UTF-8)文章发布接口
----------------------------------
文件名
etpost.php
discuz7.0文章主题发布文件，请复制在DZ7.0论坛根目录使用，为保密，请自行修改文件名


主要参数
username 	会员名参数名
password 	密码参数名
subject		主题标题参数名
message 	内容参数名
ETattachs	文件列表参数名

附加参数
fid		论坛版块编号(取值为您要发布的版面FID号) 
vercode		安全校验码，请自行设定，本项用以防止接口被他人利用，如果需要进行更多校验，请自行填加相关代码。

*/

@$vercode='';	//此处取值请自行修改

/*



可选参数
typeid 		主题分类（如论坛未设必选主题分类，可以不用）
parseurloff	禁用 URL 识别（取值1）
smileyoff	禁用表情（取值1）
tagoff		禁用标签解析（取值1）
tags		标签(TAG)，用空格隔开
isanonymous	使用匿名发帖（取值1）
usesig		使用个人签名（取值1）
emailnotify	 接收新回复邮件通知（取值1）
readperm	文章所需阅读权限
price		文章售价
iconid		图标编号


ET发布配置-文章检查网址处，填写参考如下：
http://您的网址/etpost.php

*/
if ($_REQUEST['vercode']!=$vercode){
	echo("[err]invalid vercode[/err]");
	exit();
}


define('CURSCRIPT', 'post');
define('NOROBOT', TRUE);

//require_once './include/common.inc.php';
//common.inc.php代码开始


error_reporting(0);
set_magic_quotes_runtime(0);
$mtime = explode(' ', microtime());
$discuz_starttime = $mtime[1] + $mtime[0];

define('SYS_DEBUG', FALSE);
define('IN_DISCUZ', TRUE);
//define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -7));
$DISCUZROOT=ereg_replace("[/\\]{1,}",'/',dirname(__FILE__) ) ;
if (substr($DISCUZROOT,-1,1)!='/')$DISCUZROOT.='/';
define('DISCUZ_ROOT', $DISCUZROOT);

define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
!defined('CURSCRIPT') && define('CURSCRIPT', '');

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.');
}

require_once DISCUZ_ROOT.'./include/global.func.php';

getrobot();
if(defined('NOROBOT') && IS_ROBOT) {
	exit(header("HTTP/1.1 403 Forbidden"));
}

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

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

$charset = $dbs = $dbcharset = $forumfounders = $metakeywords = $extrahead = $seodescription = $mnid = '';
$plugins = $hooks = $admincp = $jsmenu = $forum = $thread = $language = $actioncode = $modactioncode = $lang = array();
$_DCOOKIE = $_DSESSION = $_DCACHE = $_DPLUGIN = $advlist = array();

require_once DISCUZ_ROOT.'./config.inc.php';

if($urlxssdefend && !empty($_SERVER['REQUEST_URI'])) {
	$temp = urldecode($_SERVER['REQUEST_URI']);
	if(strpos($temp, '<') !== false || strpos($temp, '"') !== false)
		exit('Request Bad url');
}

$prelength = strlen($cookiepre);
foreach($_COOKIE as $key => $val) {
	if(substr($key, 0, $prelength) == $cookiepre) {
		$_DCOOKIE[(substr($key, $prelength))] = MAGIC_QUOTES_GPC ? $val : daddslashes($val);
	}
}
unset($prelength, $_request, $_key, $_value);

$inajax = !empty($inajax);
$handlekey = !empty($handlekey) ? htmlspecialchars($handlekey) : '';
$timestamp = time();

if($attackevasive && CURSCRIPT != 'seccode') {
	require_once DISCUZ_ROOT.'./include/security.inc.php';
}

require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';


$PHP_SELF = dhtmlspecialchars($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
$BASESCRIPT = basename($PHP_SELF);
list($BASEFILENAME) = explode('.', $BASESCRIPT);
$boardurl = htmlspecialchars('http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api|archiver|wap)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/');

if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
	$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
	$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
	$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
	$onlineip = $_SERVER['REMOTE_ADDR'];
}

preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
unset($onlineipmatches);

$cachelost = (@include DISCUZ_ROOT.'./forumdata/cache/cache_settings.php') ? '' : 'settings';
@extract($_DCACHE['settings']);

if($gzipcompress && function_exists('ob_gzhandler') && !in_array(CURSCRIPT, array('attachment', 'wap')) && !$inajax) {
	ob_start('ob_gzhandler');
} else {
	$gzipcompress = 0;
	ob_start();
}

if(!empty($loadctrl) && substr(PHP_OS, 0, 3) != 'WIN') {
	if($fp = @fopen('/proc/loadavg', 'r')) {
		list($loadaverage) = explode(' ', fread($fp, 6));
		fclose($fp);
		if($loadaverage > $loadctrl) {
			header("HTTP/1.0 503 Service Unavailable");
			include DISCUZ_ROOT.'./include/serverbusy.htm';
			exit();
		}
	}
}

if(in_array(CURSCRIPT, array('index', 'forumdisplay', 'viewthread', 'post', 'topicadmin', 'register', 'archiver'))) {
	$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/cache_'.CURSCRIPT.'.php') ? '' : ' '.CURSCRIPT;
}

$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
$dbuser = $dbpw = $pconnect = $sdb = NULL;

$sid = daddslashes(($transsidstatus || CURSCRIPT == 'wap') && (isset($_GET['sid']) || isset($_POST['sid'])) ?
	(isset($_GET['sid']) ? $_GET['sid'] : $_POST['sid']) :
	(isset($_DCOOKIE['sid']) ? $_DCOOKIE['sid'] : ''));

CURSCRIPT == 'attachment' && isset($_GET['sid']) && $sid = addslashes(authcode($_GET['sid'], 'DECODE', $_DCACHE['settings']['authkey']));

$discuz_auth_key = md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']);
list($discuz_pw, $discuz_secques, $discuz_uid) = empty($_DCOOKIE['auth']) ? array('', '', 0) : daddslashes(explode("\t", authcode($_DCOOKIE['auth'], 'DECODE')), 1);






$prompt = $sessionexists = $seccode = 0;
$membertablefields = 'm.uid AS discuz_uid, m.username AS discuz_user, m.password AS discuz_pw, m.secques AS discuz_secques,
	m.adminid, m.groupid, m.groupexpiry, m.extgroupids, m.email, m.timeoffset, m.tpp, m.ppp, m.posts, m.digestposts,
	m.oltime, m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5,
	m.extcredits6, m.extcredits7, m.extcredits8, m.timeformat, m.dateformat, m.pmsound, m.sigstatus, m.invisible,
	m.lastvisit, m.lastactivity, m.lastpost, m.prompt, m.accessmasks, m.editormode, m.customshow, m.customaddfeed';
/*if($sid) {
	if($discuz_uid) {
		$query = $db->query("SELECT s.sid, s.styleid, s.groupid='6' AS ipbanned, s.pageviews AS spageviews, s.lastolupdate, s.seccode, $membertablefields
			FROM {$tablepre}sessions s, {$tablepre}members m
			WHERE m.uid=s.uid AND s.sid='$sid' AND CONCAT_WS('.',s.ip1,s.ip2,s.ip3,s.ip4)='$onlineip' AND m.uid='$discuz_uid'
			AND m.password='$discuz_pw' AND m.secques='$discuz_secques'");
	} else {
		$query = $db->query("SELECT sid, uid AS sessionuid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
			FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'");
	}
	if($_DSESSION = $db->fetch_array($query)) {
		$sessionexists = 1;
		if(!empty($_DSESSION['sessionuid'])) {
			$_DSESSION = array_merge($_DSESSION, $db->fetch_first("SELECT $membertablefields
				FROM {$tablepre}members m WHERE uid='$_DSESSION[sessionuid]'"));
		}
	} else {
		if($_DSESSION = $db->fetch_first("SELECT sid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
			FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'")) {
			clearcookies();
			$sessionexists = 1;
		}
	}
}
*/

if(!$sessionexists) {

	if (empty($username) || empty($password)) {
		echo("[err]username or password is empty[/err]");
		exit();	
		}
	else{

			if(!($_DSESSION = $db->fetch_first("SELECT $membertablefields, m.styleid
			FROM {$tablepre}members m WHERE m.username='".addslashes($username)."'"))) {
			clearcookies();
			}
	}
	$discuz_uid=$_DSESSION['discuz_uid'];
	$discuz_pw=$_DSESSION['discuz_pw'];
	$discuz_user=$_DSESSION['discuz_user'];
/*
	if($discuz_uid) {
		if(!($_DSESSION = $db->fetch_first("SELECT $membertablefields, m.styleid
			FROM {$tablepre}members m WHERE m.uid='$discuz_uid' AND m.password='$discuz_pw' AND m.secques='$discuz_secques'"))) {
			clearcookies();
		}
	}
*/
	
	if(ipbanned($onlineip)) $_DSESSION['ipbanned'] = 1;

	$_DSESSION['sid'] = random(6);
	$_DSESSION['seccode'] = random(6, 1);
}

$_DSESSION['dateformat'] = empty($_DSESSION['dateformat']) || empty($_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1])? $_DCACHE['settings']['dateformat'] : $_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1];
$_DSESSION['timeformat'] = empty($_DSESSION['timeformat']) ? $_DCACHE['settings']['timeformat'] : ($_DSESSION['timeformat'] == 1 ? 'h:i A' : 'H:i');
$_DSESSION['timeoffset'] = isset($_DSESSION['timeoffset']) && $_DSESSION['timeoffset'] != 9999 ? $_DSESSION['timeoffset'] : $_DCACHE['settings']['timeoffset'];

$membertablefields = '';
@extract($_DSESSION);

$newpm = $prompt & 1;
$doingtask = $prompt & 2 ? 1 : 0;

$lastvisit = empty($lastvisit) ? $timestamp - 86400 : $lastvisit;
$timenow = array('time' => gmdate("$dateformat $timeformat", $timestamp + 3600 * $timeoffset),
	'offset' => ($timeoffset >= 0 ? ($timeoffset == 0 ? '' : '+'.$timeoffset) : $timeoffset));

if(PHP_VERSION > '5.1') {
	@date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
}

$accessadd1 = $accessadd2 = $modadd1 = $modadd2 = $metadescription = '';
if(empty($discuz_uid) || empty($discuz_user)) {
	$discuz_user = $extgroupids = '';
	$discuz_uid = $adminid = $posts = $digestposts = $pageviews = $oltime = $invisible
		= $credits = $extcredits1 = $extcredits2 = $extcredits3 = $extcredits4
		= $extcredits5 = $extcredits6 = $extcredits7 = $extcredits8 = 0;
	$groupid = empty($groupid) || $groupid != 6 ? 7 : 6;

} else {
	$discuz_userss = $discuz_user;
	$discuz_user = addslashes($discuz_user);

	if($accessmasks) {
		$accessadd1 = ', a.allowview, a.allowpost, a.allowreply, a.allowgetattach, a.allowpostattach';
		$accessadd2 = "LEFT JOIN {$tablepre}access a ON a.uid='$discuz_uid' AND a.fid=f.fid";
	}

	if($adminid == 3) {
		$modadd1 = ', m.uid AS ismoderator';
		$modadd2 = "LEFT JOIN {$tablepre}moderators m ON m.uid='$discuz_uid' AND m.fid=f.fid";
	}
}
/*
if($errorreport == 2 || ($errorreport == 1 && $adminid > 0)) {
	error_reporting(E_ERROR | E_WARNING | E_PARSE);
}
*/

define('FORMHASH', formhash());

$statstatus && !$inajax && require_once DISCUZ_ROOT.'./include/counter.inc.php';

$extra = isset($extra) && @preg_match("/^[&=;a-z0-9]+$/i", $extra) ? $extra : '';

$rsshead = $navtitle = $navigation = '';

$_DSESSION['groupid'] = $groupid = empty($ipbanned) ? (empty($groupid) ? 7 : intval($groupid)) : 6;
if(!@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.$groupid.'.php') {
	$grouptype = $db->result_first("SELECT type FROM {$tablepre}usergroups WHERE groupid='$groupid'");
	if(!empty($grouptype)) {
		$cachelost .= ' usergroup_'.$groupid;
	} else {
		$grouptype = 'member';
	}
}

/*
$link_login = 'logging.php?action=login';
$link_logout = 'logging.php?action=logout&amp;formhash='.FORMHASH;
$link_register = $regname;
*/

if($discuz_uid && $_DSESSION) {
	if(!empty($groupexpiry) && $groupexpiry < $timestamp && !in_array(CURSCRIPT, array('wap', 'member'))) {
		dheader("Location: {$boardurl}member.php?action=groupexpiry");
	} elseif($grouptype && $groupid != getgroupid($discuz_uid, array
		(
		'type' => $grouptype,
		'creditshigher' => $groupcreditshigher,
		'creditslower' => $groupcreditslower
		), $_DSESSION)) {
		@extract($_DSESSION);
		$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.intval($groupid).'.php') ? '' : ' usergroup_'.$groupid;
	}
}

$tpp = intval(empty($_DSESSION['tpp']) ? $topicperpage : $_DSESSION['tpp']);
$ppp = intval(empty($_DSESSION['ppp']) ? $postperpage : $_DSESSION['ppp']);

if(!in_array($adminid, array(1, 2, 3))) {
	$alloweditpost = $alloweditpoll = $allowstickthread = $allowmodpost = $allowdelpost = $allowmassprune
		= $allowrefund = $allowcensorword = $allowviewip = $allowbanip = $allowedituser = $allowmoduser
		= $allowbanuser = $allowpostannounce = $allowviewlog = $disablepostctrl = 0;
} elseif(isset($radminid) && $adminid != $radminid && $adminid != $groupid) {
	$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/admingroup_'.intval($adminid).'.php') ? '' : ' admingroup_'.$groupid;
}


$page = isset($page) ? max(1, intval($page)) : 1;
$tid = isset($tid) && is_numeric($tid) ? $tid : 0;
$fid = isset($fid) && is_numeric($fid) ? $fid : 0;
$typeid = isset($typeid) ? intval($typeid) : 0;

$modthreadkey = isset($modthreadkey) && $modthreadkey == modthreadkey($tid) ? $modthreadkey : '';
$auditstatuson = $modthreadkey ? true : false;

if(!empty($tid) || !empty($fid)) {
	if(empty($tid)) {
		$forum = $db->fetch_first("SELECT f.fid, f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
			FROM {$tablepre}forums f
			LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
			WHERE f.fid='$fid'");
	} else {
		$forum = $db->fetch_first("SELECT t.tid, t.closed,".(defined('SQL_ADD_THREAD') ? SQL_ADD_THREAD : '')." f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
			FROM {$tablepre}threads t
			INNER JOIN {$tablepre}forums f ON f.fid=t.fid
			LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
			WHERE t.tid='$tid'".($auditstatuson ? '' : " AND t.displayorder>='0'")." LIMIT 1");
		$tid = $forum['tid'];
	}

	if($forum) {
		$fid = $forum['fid'];
		$forum['ismoderator'] = !empty($forum['ismoderator']) || $adminid == 1 || $adminid == 2 ? 1 : 0;
		foreach(array('postcredits', 'replycredits', 'threadtypes', 'threadsorts', 'digestcredits', 'postattachcredits', 'getattachcredits') as $key) {
			$forum[$key] = !empty($forum[$key]) ? unserialize($forum[$key]) : array();
		}
	} else {
		$fid = 0;
	}
}

$styleid = intval(!empty($_GET['styleid']) ? $_GET['styleid'] :
		(!empty($_POST['styleid']) ? $_POST['styleid'] :
		(!empty($_DSESSION['styleid']) ? $_DSESSION['styleid'] :
		$_DCACHE['settings']['styleid'])));

$styleid = intval(isset($styles[$styleid]) ? $styleid : $_DCACHE['settings']['styleid']);

if(@!include DISCUZ_ROOT.'./forumdata/cache/style_'.intval(!empty($forum['styleid']) ? $forum['styleid'] : $styleid).'.php') {
	$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/style_'.($styleid = $_DCACHE['settings']['styleid']).'.php') ? '' : ' style_'.$styleid;
}

if($cachelost) {
	require_once DISCUZ_ROOT.'./include/cache.func.php';
	updatecache();
	exit('Cache List: '.$cachelost.'<br />Caches successfully created, please refresh.');
}

if(CURSCRIPT != 'wap') {
	if($nocacheheaders) {
		@dheader("Expires: 0");
		@dheader("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE);
		@dheader("Pragma: no-cache");
	}
	if($headercharset) {
		@dheader('Content-Type: text/html; charset='.$charset);
	}
	if(empty($_DCOOKIE['sid']) || $sid != $_DCOOKIE['sid']) {
		dsetcookie('sid', $sid, 604800, 1, true);
	}
}

$_DCOOKIE['loginuser'] = !empty($_DCOOKIE['loginuser']) ? substr(htmlspecialchars($_DCOOKIE['loginuser']), 0, 15) : '';

if(!empty($insenz['cronnextrun']) && $insenz['cronnextrun'] <= $timestamp) {
	require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
	insenz_runcron();
} elseif($cronnextrun && $cronnextrun <= $timestamp) {
	require_once DISCUZ_ROOT.'./include/cron.func.php';
	runcron();
} elseif(isset($insenz['statsnextrun']) && $insenz['statsnextrun'] <= $timestamp) {
	require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
	insenz_onlinestats();
}

if(isset($plugins['include']) && is_array($plugins['include'])) {
	foreach($plugins['include'] as $include) {
		if(!$include['adminid'] || ($include['adminid'] && $include['adminid'] >= $adminid)) {
			@include_once DISCUZ_ROOT.'./plugins/'.$include['script'].'.inc.php';
		}
	}
}

if((!empty($_DCACHE['advs']) || $globaladvs) && !defined('IN_ADMINCP')) {
	require_once DISCUZ_ROOT.'./include/advertisements.inc.php';
}

if(isset($allowvisit) && $allowvisit == 0 && !(CURSCRIPT == 'member' && ($action == 'groupexpiry' || $action == 'activate'))) {
	showmessage('user_banned', NULL, 'HALTED');
} elseif(!(in_array(CURSCRIPT, array('logging', 'wap', 'seccode', 'ajax')) || $adminid == 1)) {
	if($bbclosed) {
		clearcookies();
		$closedreason = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable='closedreason'");
		showmessage($closedreason ? $closedreason : 'board_closed', NULL, 'NOPERM');
	}
	periodscheck('visitbanperiods');
}

if((!empty($fromuid) || !empty($fromuser)) && ($creditspolicy['promotion_visit'] || $creditspolicy['promotion_register'])) {
	require_once DISCUZ_ROOT.'/include/promotion.inc.php';
}

if($uc['addfeed']) {
	$customaddfeed = $customaddfeed == '-1' ? 0 : ($customaddfeed == 0 ? $uc['addfeed'] : intval($customaddfeed));
} else {
	$customaddfeed = 0;
}

$rssauth = $rssstatus && $discuz_uid ? rawurlencode(authcode("$discuz_uid\t".($fid ? $fid : '')."\t".substr(md5($discuz_pw.$discuz_secques), 0, 8), 'ENCODE', md5($_DCACHE['settings']['authkey']))) : '0';
$transferstatus = $transferstatus && $allowtransfer;
$feedpostnum = $feedpostnum && $uchomeurl ? intval($feedpostnum) : 0;



//common.inc.php代码结束


require_once DISCUZ_ROOT.'./include/post.func.php';


$_DTYPE = $checkoption = $optionlist = array();
if($sortid) {
	threadsort_checkoption();
}

$action = 'newthread';
/*
if (($action != 'reply') && ($action != 'newthread' )){
	echo("[err]undefined_action[/err]");
	exit;
}
*/
/*
if(empty($action)) {

	showmessage('undefined_action', NULL, 'HALTED');
}
elseif($action == 'threadsorts') {
	threadsort_optiondata();
	$template = intval($operate) ? 'search_sortoption' : 'post_sortoption';
	include template($template);
	exit;

} elseif(($forum['simple'] & 1) || $forum['redirect']) {
	showmessage('forum_disablepost');
}
*/
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';

$customaddfeed = $customaddfeed ? $customaddfeed : $uchome['addfeed'];

if($action == 'reply') {
	$addfeedcheck = $customaddfeed & 4 ? 'checked="checked"': '';
} elseif(!empty($special) && $action != 'reply') {
	$addfeedcheck = $customaddfeed & 2 ? 'checked="checked"': '';
} else {
	$addfeedcheck = $customaddfeed & 1 ? 'checked="checked"': '';
}


$navigation = $navtitle = $thread = '';
if(!empty($cedit)) {
	unset($inajax, $infloat, $ajaxtarget, $handlekey);
}
/*
if($action == 'edit' || $action == 'reply') {

	if($thread = $db->fetch_first("SELECT * FROM {$tablepre}threads WHERE tid='$tid'".($auditstatuson ? '' : " AND displayorder>='0'"))) {

		$navigation = "&raquo; <a href=\"viewthread.php?tid=$tid\">$thread[subject]</a>";
		$navtitle = $thread['subject'].' - ';
		if($thread['readperm'] && $thread['readperm'] > $readaccess && !$forum['ismoderator'] && $thread['authorid'] != $discuz_uid) {
			showmessage('thread_nopermission', NULL, 'NOPERM');
		}

		$fid = $thread['fid'];
		$special = $thread['special'];

	} else {
		showmessage('thread_nonexistence');
	}
	
	if($action == 'reply' && ($thread['closed'] == 1) && !$forum['ismoderator']) {
		showmessage('post_thread_closed');
	}

}
*/
$navigation = "&raquo; <a href=\"forumdisplay.php?fid=$fid".($extra ? '&'.preg_replace("/^(&)*/", '', $extra) : '')."\">$forum[name]</a> $navigation";
$navtitle = $navtitle.strip_tags($forum['name']).' - ';

if($forum['type'] == 'sub') {
	$fup = $db->fetch_first("SELECT name, fid FROM {$tablepre}forums WHERE fid='$forum[fup]'");
	$navigation = "&raquo; <a href=\"forumdisplay.php?fid=$fup[fid]\">$fup[name]</a> $navigation";
	$navtitle = $navtitle.strip_tags($fup['name']).' - ';
}

periodscheck('postbanperiods');
/*
if($forum['password'] && $forum['password'] != $_DCOOKIE['fidpw'.$fid]) {
	showmessage('forum_passwd', "forumdisplay.php?fid=$fid");
}

if(empty($forum['allowview'])) {
	if(!$forum['viewperm'] && !$readaccess) {
		showmessage('group_nopermission', NULL, 'NOPERM');
	} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
		showmessage('forum_nopermission', NULL, 'NOPERM');
	}
} elseif($forum['allowview'] == -1) {
	showmessage('forum_access_view_disallow');
}
*/
formulaperm($forum['formulaperm']);
/*
if(!$adminid && $newbiespan && (!$lastpost || $timestamp - $lastpost < $newbiespan * 3600)) {
	if($timestamp - ($db->result_first("SELECT regdate FROM {$tablepre}members WHERE uid='$discuz_uid'")) < $newbiespan * 3600) {
		showmessage('post_newbie_span');
	}
}
*/
$special = empty($special) || !is_numeric($special) || $special < 0 || $special > 6 ? 0 : intval($special);

$allowpostattach = $forum['allowpostattach'] != -1 && ($forum['allowpostattach'] == 1 || (!$forum['postattachperm'] && $allowpostattach) || ($forum['postattachperm'] && forumperm($forum['postattachperm'])));
$attachextensions = $forum['attachextensions'] ? $forum['attachextensions'] : $attachextensions;
$enctype = $allowpostattach ? 'enctype="multipart/form-data"' : '';
$maxattachsize_mb = $maxattachsize / 1048576 >= 1 ? round(($maxattachsize / 1048576), 1).'M' : round(($maxattachsize / 1024)).'K';

$postcredits = $forum['postcredits'] ? $forum['postcredits'] : $creditspolicy['post'];
$replycredits = $forum['replycredits'] ? $forum['replycredits'] : $creditspolicy['reply'];
$digestcredits = $forum['digestcredits'] ? $forum['digestcredits'] : $creditspolicy['digest'];
$postattachcredits = $forum['postattachcredits'] ? $forum['postattachcredits'] : $creditspolicy['postattach'];

$maxprice = isset($extcredits[$creditstrans]) ? $maxprice : 0;

$extra = rawurlencode($extra);
$notifycheck = empty($emailnotify) ? '' : 'checked="checked"';
$stickcheck = empty($sticktopic) ? '' : 'checked="checked"';
$digestcheck = empty($addtodigest) ? '' : 'checked="checked"';

$subject = isset($subject) ? dhtmlspecialchars(censor(trim($subject))) : '';
$subject = !empty($subject) ? str_replace("\t", ' ', $subject) : $subject;
$message = isset($message) ? censor(trim($message)) : '';
$polloptions = isset($polloptions) ? censor(trim($polloptions)) : '';
$readperm = isset($readperm) ? intval($readperm) : 0;
$price = isset($price) ? intval($price) : 0;
$tagstatus = $tagstatus && $forum['allowtag'] ? ($tagstatus == 2 ? 2 : $forum['allowtag']) : 0;

if(empty($bbcodeoff) && !$allowhidecode && !empty($message) && preg_match("/\[hide=?\d*\].+?\[\/hide\]/is", preg_replace("/(\[code\](.+?)\[\/code\])/is", ' ', $message))) {
	showmessage('post_hide_nopermission');
}

if(periodscheck('postmodperiods', 0)) {
	$modnewthreads = $modnewreplies = 1;
} else {
	$censormod = censormod($subject."\t".$message);
	$modnewthreads = (!$allowdirectpost || $allowdirectpost == 1) && ($forum['modnewposts'] || $censormod) ? 1 : 0;
	$modnewreplies = (!$allowdirectpost || $allowdirectpost == 2) && ($forum['modnewposts'] == 2 || $censormod) ? 1 : 0;
}

$urloffcheck = $usesigcheck = $smileyoffcheck = $codeoffcheck = $htmloncheck = $emailcheck = '';

$seccodecheck = ($seccodestatus & 4) && (!$seccodedata['minposts'] || $posts < $seccodedata['minposts']);
$secqaacheck = $secqaa['status'][2] && (!$secqaa['minposts'] || $posts < $secqaa['minposts']);

$allowpostpoll = $allowpost && $allowpostpoll && ($forum['allowpostspecial'] & 1);
$allowposttrade = $allowpost && $allowposttrade && ($forum['allowpostspecial'] & 2);
$allowpostreward = $allowpost && $allowpostreward && ($forum['allowpostspecial'] & 4) && isset($extcredits[$creditstrans]);
$allowpostactivity = $allowpost && $allowpostactivity && ($forum['allowpostspecial'] & 8);
$allowpostdebate = $allowpost && $allowpostdebate && ($forum['allowpostspecial'] & 16);
$allowpostvideo = $allowpost && $allowpostvideo && ($forum['allowpostspecial'] & 32) && $videoopen;
$usesigcheck = $discuz_uid && $sigstatus ? 'checked="checked"' : '';

$allowanonymous = $forum['allowanonymous'] || $allowanonymous ? 1 : 0;

if($action == 'newthread' && $forum['allowspecialonly'] && !$special) {
	if($allowpostpoll) {
		$special = 1;
	} elseif($allowposttrade) {
		$special = 2;
	} elseif($allowpostreward) {
		$special = 3;
	} elseif($allowpostactivity) {
		$special = 4;
	} elseif($allowpostdebate) {
		$special = 5;
	} elseif($allowpostvideo) {
		$special = 6;
	}
	if(!$special) {
		showmessage('undefined_action', NULL, 'HALTED');
	}
}

$editorid = 'e';
$editoroptions = str_pad(decbin($editoroptions), 2, 0, STR_PAD_LEFT);
$editormode = $editormode == 2 ? $editoroptions{0} : $editormode;
$allowswitcheditor = $editoroptions{1};

$swfupload = $swfupload && $allowpostattach;
if($swfupload) {
	require_once DISCUZ_ROOT.'./include/swfupload.func.php';
	$swfattachs = getswfattach();
}

if(!empty($infloat)) {
	$policyarray = array();
	foreach($creditspolicy as $operation => $policy) {		
		if(in_array($operation, array('post', 'reply', 'digest', 'postattach', 'getattach'))) {
			$policyarray[$operation] = $policy;
			if($forum) {
				$policyarray[$operation] = $forum[$operation.'credits'] ? $forum[$operation.'credits'] : $creditspolicy[$operation];
			}
		}
	}
	
	$creditsarray = array();
	for($i = 1; $i <= 8; $i++) {
		if(isset($extcredits[$i])) {
			foreach($policyarray as $operation => $policy) {
				$addcredits = in_array($operation, array('getattach', 'forum_getattach')) ? -$policy[$i] : $policy[$i];
				$creditsarray[$operation][$i] = empty($policy[$i]) ? 0 : (is_numeric($policy[$i]) ? '<b>'.($addcredits > 0 ? '+'.$addcredits : $addcredits).'</b> '.$extcredits[$i]['unit'] : $policy[$i]);
			}
		}
	}
}

$posturl = "action=$action&fid=$fid".
	(!empty($tid) ? "&tid=$tid" : '').
	(!empty($pid) ? "&pid=$pid" : '').
	(!empty($special) ? "&special=$special" : '').
	(!empty($sortid) ? "&sortid=$sortid" : '').
	(!empty($typeid) ? "&sortid=$typeid" : '').
	(!empty($firstpid) ? "&firstpid=$firstpid" : '').
	(!empty($addtrade) ? "&addtrade=$addtrade" : '');

/*
if($action == 'newthread') {
	($forum['allowpost'] == -1) && showmessage('forum_access_disallow');
	require_once DISCUZ_ROOT.'./include/newthread.inc.php';
} elseif($action == 'reply') {
	($forum['allowreply'] == -1) && showmessage('forum_access_disallow');
	require_once DISCUZ_ROOT.'./include/newreply.inc.php';
} elseif($action == 'edit') {
	($forum['allowpost'] == -1) && showmessage('forum_access_disallow');
	require_once DISCUZ_ROOT.'./include/editpost.inc.php';
} elseif($action == 'newtrade') {
	($forum['allowpost'] == -1) && showmessage('forum_access_disallow');
	require_once DISCUZ_ROOT.'./include/newtrade.inc.php';
}
*/

//newthread.inc.php开始
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

$discuz_action = 11;
/*
if(($special == 1 && !$allowpostpoll) || ($special == 2 && !$allowposttrade) || ($special == 3 && !$allowpostreward) || ($special == 4 && !$allowpostactivity) || ($special == 5 && !$allowpostdebate) || ($special == 6 && !$allowpostvideo)) {
	showmessage('group_nopermission', NULL, 'NOPERM');
}


if($special == 6) {
	require_once DISCUZ_ROOT.'./api/video.php';
	require_once DISCUZ_ROOT.'./include/insenz.func.php';
}*/

if(!$discuz_uid && !((!$forum['postperm'] && $allowpost) || ($forum['postperm'] && forumperm($forum['postperm'])))) {
	showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(empty($forum['allowpost'])) {
	if(!$forum['postperm'] && !$allowpost) {
		showmessage('group_nopermission', NULL, 'NOPERM');
	} elseif($forum['postperm'] && !forumperm($forum['postperm'])) {
		showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
	}
} elseif($forum['allowpost'] == -1) {
	showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
}

if($url && !empty($qihoo['relate']['webnum'])) {
	$from = in_array($from, array('direct', 'iframe')) ? $from : '';
	if($data = @implode('', file("http://search.qihoo.com/sint/content.html?surl=$url&md5=$md5&ocs=$charset&ics=$charset&from=$from"))) {
		preg_match_all("/(\w+):([^\>]+)/i", $data, $data);
		if(!$data[2][1]) {
			$subject = trim($data[2][3]);
			$message = !$editormode ? str_replace('[br]', "\n", trim($data[2][4])) : str_replace('[br]', '<br />', trim($data[2][4]));
		} else {
			showmessage('reprint_invalid');
		}
	}
}

//checklowerlimit($postcredits);
//if(!submitcheck('topicsubmit', 0, $seccodecheck, $secqaacheck)) {
/*
	$modelid = $modelid ? intval($modelid) : '';
	$isfirstpost = 1;
	$tagoffcheck = '';
	$showthreadsorts = !empty($sortid); 

	$icons = '';
	if(!$special && is_array($_DCACHE['icons'])) {
		$key = 1;
		foreach($_DCACHE['icons'] as $id => $icon) {
			$icons .= ' <input class="radio" type="radio" name="iconid" value="'.$id.'" /><img src="images/icons/'.$icon.'" alt="" />';
			$icons .= !(++$key % 10) ? '<br />' : '';
		}
	}

	if($special == 2 && $allowposttrade) {
		$expiration_7days = date('Y-m-d', $timestamp + 86400 * 7);
		$expiration_14days = date('Y-m-d', $timestamp + 86400 * 14);
		$trade['expiration'] = $expiration_month = date('Y-m-d', mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
		$expiration_3months = date('Y-m-d', mktime(0, 0, 0, date('m')+3, date('d'), date('Y')));
		$expiration_halfyear = date('Y-m-d', mktime(0, 0, 0, date('m')+6, date('d'), date('Y')));
		$expiration_year = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')+1));

		$forum['tradetypes'] = $forum['tradetypes'] == '' ? -1 : unserialize($forum['tradetypes']);		

	} elseif($special == 6 && $allowpostvideo) {

		$videoAccount = new VideoClient_Util($appid, $siteid, $sitekey);
		$videoupload = $videoAccount->createUploadFrom($option, array('url' => 'data.php'));

		$query = $db->query("SELECT value FROM {$tablepre}settings WHERE variable='videoinfo'");
		$settings = unserialize($db->result($query, 0));

		if($settings['videotype'] && is_array($settings['videotype'])) {
			$vtypeselect = '<select name="vclass">';
			foreach($settings['videotype'] as $key => $type) {
				if($type['able']) {
					$vtypeselect .= '<option value="'.$key.'"> '.$type['name'].'</option>';
				}
			}
			$vtypeselect .= '</select>';
		}

	}

	if($special == 4) {
		$activitytypelist = $activitytype ? explode("\n", trim($activitytype)) : '';
	}

	include template('post');
*/
//} else {
	
	if($subject == '') {
		//showmessage('post_sm_isnull');
		echo("[err]subject is null[/err]");
		exit();
	}

	if(!$sortid && !$special && $message == '') {
//		showmessage('post_sm_isnull');
		echo("[err]message is null[/err]");
		exit();
	}

	/*if($post_invalid = checkpost($special)) {
		showmessage($post_invalid);
	}
*/
	if(checkflood()) {
		showmessage('post_flood_ctrl');
	}

	if($allowpostattach && is_array($_FILES['attach'])) {
		foreach($_FILES['attach']['name'] as $attachname) {
			if($attachname != '') {
				checklowerlimit($postattachcredits);
				break;
			}
		}
	}

	$typeid = isset($typeid) && isset($forum['threadtypes']['types'][$typeid]) ? $typeid : 0;
	$iconid = !empty($iconid) && isset($_DCACHE['icons'][$iconid]) ? $iconid : 0;
	$displayorder = $modnewthreads ? -2 : (($forum['ismoderator'] && !empty($sticktopic)) ? 1 : 0);
	$digest = ($forum['ismoderator'] && !empty($addtodigest)) ? 1 : 0;
	$readperm = $allowsetreadperm ? $readperm : 0;
	$isanonymous = $isanonymous && $allowanonymous ? 1 : 0;
	$price = intval($price);
	$price = $maxprice && !$special ? ($price <= $maxprice ? $price : $maxprice) : 0;
/*
	if(!$typeid && $forum['threadtypes']['required'] && !$special) {
		showmessage('post_type_isnull');
	}

	if(!$sortid && $forum['threadsorts']['required'] && !$special) {
		showmessage('post_sort_isnull');
	}
*/
	if($price > 0 && floor($price * (1 - $creditstax)) == 0) {
//		showmessage('post_net_price_iszero');
		echo("[err]discuz7 error:post_net_price_iszero[/err]");
		exit();
	}
/*
	if($special == 1) {

		$pollarray = array();
		foreach($polloption as $key => $value) {
			if(trim($value) === '') {
				unset($polloption[$key]);
			}
		}

		if(count($polloption) > $maxpolloptions) {
			showmessage('post_poll_option_toomany');
		} elseif(count($polloption) < 2) {
			showmessage('post_poll_inputmore');
		}

		$maxchoices = !empty($multiplepoll) ? (!$maxchoices || $maxchoices >= count($polloption) ? count($polloption) : $maxchoices) : '';
		$pollarray['options'] = $polloption;
		$pollarray['multiple'] = !empty($multiplepoll);
		$pollarray['visible'] = empty($visibilitypoll);
		$pollarray['overt'] = !empty($overt);

		if(preg_match("/^\d*$/", trim($maxchoices)) && preg_match("/^\d*$/", trim($expiration))) {
			if(!$pollarray['multiple']) {
				$pollarray['maxchoices'] = 1;
			} elseif(empty($maxchoices)) {
				$pollarray['maxchoices'] = 0;
			} elseif($maxchoices == 1) {
				$pollarray['multiple'] = 0;
				$pollarray['maxchoices'] = $maxchoices;
			} else {
				$pollarray['maxchoices'] = $maxchoices;
			}
			if(empty($expiration)) {
				$pollarray['expiration'] = 0;
			} else {
				$pollarray['expiration'] = $timestamp + 86400 * $expiration;
			}
		} else {
			showmessage('poll_maxchoices_expiration_invalid');
		}

	} elseif($special == 3) {

		$rewardprice = intval($rewardprice);
		if($rewardprice < 1) {
			showmessage('reward_credits_please');
		} elseif($rewardprice > 32767) {
			showmessage('reward_credits_overflow');
		} elseif($rewardprice < $minrewardprice || ($maxrewardprice > 0 && $rewardprice > $maxrewardprice)) {
			if($maxrewardprice > 0) {
				showmessage('reward_credits_between');
			} else {
				showmessage('reward_credits_lower');
			}
		} elseif(($realprice = $rewardprice + ceil($rewardprice * $creditstax)) > $_DSESSION["extcredits$creditstransextra[2]"]) {
			showmessage('reward_credits_shortage');
		}

		$price = $rewardprice;

		$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[2]=extcredits$creditstransextra[2]-$realprice WHERE uid='$discuz_uid'");

	} elseif($special == 4) {

		$activitytime = intval($activitytime);
		if(empty($starttimefrom[$activitytime])) {
			showmessage('activity_fromtime_please');
		} elseif(@strtotime($starttimefrom[$activitytime]) === -1 || @strtotime($starttimefrom[$activitytime]) === FALSE) {
			showmessage('activity_fromtime_error');
		} elseif($activitytime && ((@strtotime($starttimefrom) > @strtotime($starttimeto) || !$starttimeto))) {
			showmessage('activity_fromtime_error');
		} elseif(!trim($activityclass)) {
			showmessage('activity_sort_please');
		} elseif(!trim($activityplace)) {
			showmessage('activity_address_please');
		} elseif(trim($activityexpiration) && (@strtotime($activityexpiration) === -1 || @strtotime($activityexpiration) === FALSE)) {
			showmessage('activity_totime_error');
		}

		$activity = array();
		$activity['class'] = dhtmlspecialchars(trim($activityclass));
		$activity['starttimefrom'] = @strtotime($starttimefrom[$activitytime]);
		$activity['starttimeto'] = $activitytime ? @strtotime($starttimeto) : 0;
		$activity['place'] = dhtmlspecialchars(trim($activityplace));
		$activity['cost'] = intval($cost);
		$activity['gender'] = intval($gender);
		$activity['number'] = intval($activitynumber);

		if($activityexpiration) {
			$activity['expiration'] = @strtotime($activityexpiration);
		} else {
			$activity['expiration'] = 0;
		}
		if(trim($activitycity)) {
			$subject .= '['.dhtmlspecialchars(trim($activitycity)).']';
		}

	} elseif($special == 5) {

		if(empty($affirmpoint) || empty($negapoint)) {
			showmessage('debate_position_nofound');
		} elseif(!empty($endtime) && (!($endtime = @strtotime($endtime)) || $endtime < $timestamp)) {
			showmessage('debate_endtime_invalid');
		} elseif(!empty($umpire)) {
			if(!$db->result_first("SELECT COUNT(*) FROM {$tablepre}members WHERE username='$umpire'")) {
				$umpire = dhtmlspecialchars($umpire);
				showmessage('debate_umpire_invalid');
			}
		}
		$affirmpoint = dhtmlspecialchars($affirmpoint);
		$negapoint = dhtmlspecialchars($negapoint);
		$stand = intval($stand);

	} elseif($special == 6) {
		if(empty($vid) || empty($vsubject) || empty($vtag)) {
			showmessage('video_required_invalid');
		}
	}
*/
	$sortid = $special && $forum['threadsorts']['types'][$sortid] ? 0 : $sortid;
	$typeexpiration = intval($typeexpiration);

	if($forum['threadsorts']['expiration'][$typeid] && !$typeexpiration) {
		showmessage('threadtype_expiration_invalid');
	}

	$optiondata = array();
	if($forum['threadsorts']['types'][$sortid] && !$forum['allowspecialonly']) {
		$optiondata = threadsort_validator($typeoption);
	}

	$author = !$isanonymous ? $discuz_user : '';

	$moderated = $digest || $displayorder > 0 ? 1 : 0;

	$attachment = ($allowpostattach && $attachments = attach_upload()) ? ($imageexists ? 2 : 1) : 0;

	$subscribed = !empty($emailnotify) && $discuz_uid ? 1 : 0;

	$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, sortid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, special, attachment, subscribed, moderated)
		VALUES ('$fid', '$readperm', '$price', '$iconid', '$typeid', '$sortid', '$author', '$discuz_uid', '$subject', '$timestamp', '$timestamp', '$author', '$displayorder', '$digest', '$special', '$attachment', '$subscribed', '$moderated')");
	$tid = $db->insert_id();

	if($subscribed) {
		$db->query("REPLACE INTO {$tablepre}subscriptions (uid, tid, lastpost, lastnotify)
			VALUES ('$discuz_uid', '$tid', '$timestamp', '$timestamp')", 'UNBUFFERED');
	}

	if($special == 3 && $allowpostreward) {
		$db->query("INSERT INTO {$tablepre}rewardlog (tid, authorid, netamount, dateline) VALUES ('$tid', '$discuz_uid', $realprice, '$timestamp')");
	}

	$db->query("REPLACE INTO {$tablepre}mythreads (uid, tid, dateline, special) VALUES ('$discuz_uid', '$tid', '$timestamp', '$special')", 'UNBUFFERED');

	if($moderated) {
		updatemodlog($tid, ($displayorder > 0 ? 'STK' : 'DIG'));
		updatemodworks(($displayorder > 0 ? 'STK' : 'DIG'), 1);
	}

	if($special == 1) {
		$db->query("INSERT INTO {$tablepre}polls (tid, multiple, visible, maxchoices, expiration, overt)
			VALUES ('$tid', '$pollarray[multiple]', '$pollarray[visible]', '$pollarray[maxchoices]', '$pollarray[expiration]', '$pollarray[overt]')");
		foreach($pollarray['options'] as $polloptvalue) {
			$polloptvalue = dhtmlspecialchars(trim($polloptvalue));
			$db->query("INSERT INTO {$tablepre}polloptions (tid, polloption) VALUES ('$tid', '$polloptvalue')");
		}

	} elseif($special == 4 && $allowpostactivity) {
		$db->query("INSERT INTO {$tablepre}activities (tid, uid, cost, starttimefrom, starttimeto, place, class, gender, number, expiration)
			VALUES ('$tid', '$discuz_uid', '$activity[cost]', '$activity[starttimefrom]', '$activity[starttimeto]', '$activity[place]', '$activity[class]', '$activity[gender]', '$activity[number]', '$activity[expiration]')");

	} elseif($special == 5 && $allowpostdebate) {

		$db->query("INSERT INTO {$tablepre}debates (tid, uid, starttime, endtime, affirmdebaters, negadebaters, affirmvotes, negavotes, umpire, winner, bestdebater, affirmpoint, negapoint, umpirepoint)
			VALUES ('$tid', '$discuz_uid', '$timestamp', '$endtime', '0', '0', '0', '0', '$umpire', '', '', '$affirmpoint', '$negapoint', '')");

	} elseif($special == 6 && $allowpostvideo) {

		$vid = dhtmlspecialchars($vid);
		$vsubject = dhtmlspecialchars($vsubject);
		$vclass = intval($vclass);
		$visup = intval($visup);
		$vlength = intval($vlength);
		$vautoplay = $vautoplay ? intval($vautoplay) : 2;
		$vshare = $vshare ? intval($vshare) : 1;

		$videoAccount = new VideoClient_VideoService($appid, $siteid, $sitekey);
		$result = $videoAccount->upload($vid, $tid, $visup, insenz_convert($vsubject, 1), insenz_convert($vtag, 1), '', $vclass, $vautoplay, $vshare);
		$query = $db->query("INSERT INTO {$tablepre}videos (vid, tid, uid, dateline, vthumb, vtitle, vclass, vtime, visup, vautoplay)
			VALUES ('$vid', '$tid', '$discuz_uid', '$timestamp', '', '$vsubject', '$vclass', '$vlength', '$visup', '$vautoplay')", 'SILENT');

	}

	if($forum['threadsorts']['types'][$sortid] && !empty($optiondata) && is_array($optiondata)) {
		foreach($optiondata as $optionid => $value) {
			$db->query("INSERT INTO {$tablepre}typeoptionvars (sortid, tid, optionid, value, expiration)
				VALUES ('$sortid', '$tid', '$optionid', '$value', '".($typeexpiration ? $timestamp + $typeexpiration : 0)."')");
		}
	}

	$bbcodeoff = checkbbcodes($message, !empty($bbcodeoff));
	$smileyoff = checksmilies($message, !empty($smileyoff));
	$parseurloff = !empty($parseurloff);
	//$htmlon = bindec(($tagstatus && !empty($tagoff) ? 1 : 0).($allowhtml && !empty($htmlon) ? 1 : 0));
	
	$htmlon = ($htmlon==1 || !isset($htmlon)) ? 1 : 0; //ET修改

	$pinvisible = $modnewthreads ? -2 : 0;
	$message = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $message);
	$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
		VALUES ('$fid', '$tid', '1', '$discuz_user', '$discuz_uid', '$subject', '$timestamp', '$message', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '$attachment')");
	$pid = $db->insert_id();

	if($tagstatus && $tags != '') {
		$tags = str_replace(array(chr(0xa3).chr(0xac), chr(0xa1).chr(0x41), chr(0xef).chr(0xbc).chr(0x8c)), ',', censor($tags));
		if(strexists($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;
				}
				if(!$tagstatus) {
					$db->query("INSERT {$tablepre}threadtags (tagname, tid) VALUES ('$tagname', $tid)", 'UNBUFFERED');
				}
				$tagcount++;
				if($tagcount > 4) {
					unset($tagarray);
					break;
				}
			}
		}
	}

	$tradeaid = 0;
	if($attachment) {
		$searcharray = $pregarray = $replacearray = array();
		foreach($attachments as $key => $attach) {
			$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, price, filename, description, filetype, filesize, attachment, downloads, isimage, uid, thumb, remote, width)
				VALUES ('$tid', '$pid', '$timestamp', '$attach[perm]', '$attach[price]', '$attach[name]', '$attach[description]', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$attach[uid]', '$attach[thumb]', '$attach[remote]', '$attach[width]')");
			$searcharray[] = '[local]'.$localid[$key].'[/local]';
			$pregarray[] = '/\[localimg=(\d{1,3}),(\d{1,3})\]'.$localid[$key].'\[\/localimg\]/is';
			$replacearray[] = '[attach]'.$db->insert_id().'[/attach]';
		}
		$message = str_replace($searcharray, $replacearray, preg_replace($pregarray, $replacearray, $message));
		$db->query("UPDATE {$tablepre}posts SET message='$message' WHERE pid='$pid'");
		updatecredits($discuz_uid, $postattachcredits, count($attachments));
	}
	if($swfupload) {
		updateswfattach();
	}

	if($modnewthreads) {
		$db->query("UPDATE {$tablepre}forums SET todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
		showmessage('post_newthread_mod_succeed', "forumdisplay.php?fid=$fid");
	} else {

		$feed = array(
			'icon' => '',
			'title_template' => '',
			'title_data' => array(),
			'body_template' => '',
			'body_data' => array(),
			'title_data'=>array(),
			'images'=>array()
		);
		if($addfeed && $forum['allowfeed']) {
			if($special == 0) {
				$feed['icon'] = 'thread';
				$feed['title_template'] = 'feed_thread_title';
				$feed['body_template'] = 'feed_thread_message';
				$feed['body_data'] = array(
					'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
					'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
				);
			} elseif($special > 0) {
				if($special == 1) {
					$feed['icon'] = 'poll';
					$feed['title_template'] = 'feed_thread_poll_title';
					$feed['body_template'] = 'feed_thread_poll_message';
					$feed['body_data'] = array(
						'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
						'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
					);
				} elseif($special == 3) {
					$feed['icon'] = 'reward';
					$feed['title_template'] = 'feed_thread_reward_title';
					$feed['body_template'] = 'feed_thread_reward_message';
					$feed['body_data'] = array(
						'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
						'rewardprice'=> $rewardprice,
						'extcredits' => $extcredits[$creditstransextra[2]]['title'],
						'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
					);
				} elseif($special == 4) {
					$feed['icon'] = 'activity';
					$feed['title_template'] = 'feed_thread_activity_title';
					$feed['body_template'] = 'feed_thread_activity_message';
					$feed['body_data'] = array(
						'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
						'starttimefrom' => $starttimefrom[$activitytime],
						'activityplace'=> $activityplace,
						'cost'=> $cost,
						'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
					);
				} elseif($special == 5) {
					$feed['icon'] = 'debate';
					$feed['title_template'] = 'feed_thread_debate_title';
					$feed['body_template'] = 'feed_thread_debate_message';
					$feed['body_data'] = array(
						'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
						'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150),
						'affirmpoint'=> cutstr(strip_tags(preg_replace("/\[.+?\]/is", '', $affirmpoint)), 150),
						'negapoint'=> cutstr(strip_tags(preg_replace("/\[.+?\]/is", '', $negapoint)), 150)
					);
				} elseif($special == 6) {
					$feed['icon'] = 'video';
					$feed['title_template'] = 'feed_thread_video_title';
					$feed['body_template'] = 'feed_thread_video_message';
					$feed['body_data'] = array(
						'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
						'play' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\" class=\"playbutton\">Play</a>",
						'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150),
						'vlength'=> sprintf("%02d", intval($vlength / 60)).':'.sprintf("%02d", intval($vlength % 60)),
					);
				}
			}

			if($special == 6) {
				$feed['images'][] = array('url' => VideoClient_Util::getThumbUrl($vid, 'small'), 'link' => "{$boardurl}viewthread.php?tid=$tid");
			} else {
				if(in_array($attachments[1]['type'], array('image/gif', 'image/jpeg', 'image/png'))) {
					$attachurl = preg_match("/^((https?|ftps?):\/\/|www\.)/i", $attachurl) ? $attachurl : $boardurl.$attachurl;
					$imgurl = $attachurl.'/'.$attachments[1]['attachment'].($attachments[1]['thumb'] && $attachments[1]['type'] != 'image/gif' ? '.thumb.jpg' : '');
					$feed['images'][] = $attachments[1]['attachment'] ? array('url' => $imgurl, 'link' => "{$boardurl}viewthread.php?tid=$tid") : array();
				}
			}

			if($feed) {
				postfeed($feed);
			}
		}

		if($digest) {
			foreach($digestcredits as $id => $addcredits) {
				$postcredits[$id] = (isset($postcredits[$id]) ? $postcredits[$id] : 0) + $addcredits;
			}
		}
		updatepostcredits('+', $discuz_uid, $postcredits);

		$subject = str_replace("\t", ' ', $subject);
		$lastpost = "$tid\t$subject\t$timestamp\t$author";
		$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+1, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
		if($forum['type'] == 'sub') {
			$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
		}
		echo("[reply]tid=".$tid."[/reply]");
		exit();	

		//showmessage('post_newthread_succeed', "viewthread.php?tid=$tid&extra=$extra");

	}
//}
//newthread.inc.php结束
?>