<?php
!function_exists('readover') && exit('Forbidden');
require_once(R_P.'require/updateforum.php');

$t_typedb = array();
$t_per    = $t_exits = 0;
$t_db     = $foruminfo['t_type'];

if ($t_db) {
	$t_typedb = explode("\t",$t_db);
	$t_typedb = array_unique ($t_typedb);
	$t_per	  = $t_typedb[0];
	unset($t_typedb[0]);
	foreach ($t_typedb as $value) {
		$value && $t_exits = 1;
	}
}
$db_forcetype = $t_exits && $t_per=='2' && $article==0 && !$admincheck ? 1 : 0; // 是否需要强制主题分类

if ($article == 0) {
	$pw_tmsgs = GetTtable($tid);
	$tpcdb = $db->get_one("SELECT t.tid,t.fid AS tfid,t.author,t.authorid,t.icon,t.locked,t.postdate,t.lastpost, t.subject,t.type,t.ifcheck,t.special,state,t.anonymous,t.ifmail,t.ptable,t.ifhide,tm.content,tm.aid,tm.ifsign,tm.tags,tm.magic FROM pw_threads t LEFT JOIN $pw_tmsgs tm USING(tid) WHERE t.tid=".pwEscape($tid));
	!$tpcdb['tid'] && Showmsg('illegal_tid');
	@extract($tpcdb);
	$pw_posts = GetPtable($ptable);
	$ifmailck = $ifmail>1 ? 'checked' : '';
	list($magicid,$magicname) = explode("\t",$magic);
} else {
	!is_numeric($pid) && Showmsg('illegal_tid');
	$pw_posts = GetPtable('N',$tid);
	$atcdb = $db->get_one("SELECT aid,ifsign,tid,fid AS tfid,author,authorid,icon,postdate,subject,ifcheck,content,anonymous,ifhide FROM $pw_posts WHERE pid=".pwEscape($pid));
	!$atcdb['tid'] && Showmsg('illegal_tid');
	@extract($atcdb);
	$special = 0;
}
$tfid != $fid && Showmsg('illegal_tid');
$page = floor($article/$db_readperpage)+1;

if (!$isGM && !pwRights($isBM,'deltpcs')) {
	if ($groupid == 'guest' || $authorid != $winduid) {
		Showmsg('modify_noper');
	} elseif ($locked%3 > 0) {
		Showmsg('modify_locked');
	}
}
if ($winduid != $authorid && $groupid != 3 && $groupid != 4) {
	$authordb = $db->get_one("SELECT groupid FROM pw_members WHERE uid=".pwEscape($authorid));
	if (($authordb['groupid'] == 3 || $authordb['groupid'] == 4)) {
		Showmsg('modify_admin');
	}
}
if ($_G['edittime'] && ($timestamp - $postdate) > $_G['edittime'] * 60) {
	Showmsg('modify_timelimit');
}
$hideemail = 'disabled';
$icon = (int)$icon;

if (empty($_POST['step'])) {

	$attach = '';
	if ($aid) {
		$attachs = unserialize(stripslashes($aid));
		if (is_array($attachs)) {
			foreach ($attachs as $key => $value) {
				list($value['attachurl'],) = geturl($value['attachurl'],'lf');
				$attach .= "'$key' : ['$value[name]', '$value[size]', '$value[attachurl]', '$value[type]', '$value[special]', '$value[needrvrc]', '$value[ctype]', '$value[desc]'],";
			}
			$attach = rtrim($attach,',');
		}
	}
	if ($article == 0) {
		if ($foruminfo['cms']) {
			include_once(R_P.'require/c_search.php');
			list($tids,$kname) = search_tid($tid);
		}
		$ptype	 = $t_typedb[$type];
		$ptypeid = $type;

		switch ($special) {
			case 1:
				@extract($db->get_one("SELECT * FROM pw_polls WHERE tid=".pwEscape($tid)));
				$votearray = unserialize($voteopts);
				$multi = $ifmodify = $ifpreview = '';
				$multiple && $multi = 'checked';
				$modifiable && $ifmodify = 'checked';
				$previewable && $ifpreview = 'checked';
				$vote_close = ($state || ($timelimit && $timestamp - $postdate > $timelimit * 86400)) ? 1 : 0;
				$voteable = ($_G['modifyvote'] && $vote_close == 0) ? '' : 'disabled';
				$regdatelimit = $regdatelimit ? get_date($regdatelimit,'Y-m-d') : '';
				$creditlimit = unserialize($creditlimit);
				$postnumlimit = $postnumlimit > 0 ? $postnumlimit : '';
				empty($creditlimit) && $creditlimit = array();
				foreach ($creditlimit as $key => $value) {
					${'ifcreditlimit'.$key} = $value;
				}
				break;
			case 2:
				$act = $db->get_one("SELECT * FROM pw_activity WHERE tid=".pwEscape($tid));
				$act['starttime'] = get_date($act['starttime'],"Y-m-d H:i");
				$act['endtime']   = get_date($act['endtime'],"Y-m-d H:i");
				$act['deadline']  = get_date($act['deadline'],"Y-m-d H:i");
				${'sel_'.$act['sexneed']} = 'checked';
				break;
			case 3:
				@extract($db->get_one("SELECT cbtype,catype FROM pw_reward WHERE tid=".pwEscape($tid)));
				$cbselect = "<option value=\"$cbtype\">".(is_numeric($cbtype) ? $_CREDITDB[$cbtype][0] : ${'db_'.$cbtype.'name'}).'</option>';
				$caselect = "<option value=\"$catype\">".(is_numeric($catype) ? $_CREDITDB[$catype][0] : ${'db_'.$catype.'name'}).'</option>';
				list(,$rw_b_val,$rw_a_val) = explode("\t",$forumset['rewarddb']);
				break;
			case 4:
				$trade = $db->get_one("SELECT t.*,mb.tradeinfo FROM pw_trade t LEFT JOIN pw_memberinfo mb USING(uid) WHERE t.tid=".pwEscape($tid));
				${'tspt_'.$trade['transport']} = 'checked';
				${'degree_'.$trade['degree']} = 'selected';
				for ($i = 0; $i < 2; $i++) {
					${'paym_'.pow(2,$i)} = $trade['paymethod'] & pow(2,$i) ? 'checked' : '';
				}
				if (is_array($tinfo = unserialize($trade['tradeinfo'])) && $tinfo['tradetype']) {
					$trade['tradetype'] = $tinfo['tradetype'];
				}
				unset($tinfo);
				break;
			case 5:
				$debate = $db->get_one("SELECT tid,obtitle,retitle,endtime,umpire,judge FROM pw_debates WHERE tid=".pwEscape($tid));
				$debateable = (!$debate['judge'] && $debate['endtime']>$timestamp) ? "" : "disabled";
				$debate['endtime'] = get_date($debate['endtime'],"Y-m-d H:i");
				break;
			default:
				$special = 0;
		}
		list($tags) = explode("\t",$tags);
	}
	empty($subject) && $subject=' ';

	$htmcheck    = $ifsign < 2 ? '' : 'checked';
	!$ifanonymous && $anonymous && $ifanonymous = 'checked';
	!$htmlatt && $ifhide && $htmlatt = 'checked';
	$atc_title   = $subject;
	$atc_content = str_replace(array('<','>'),array('&lt;','&gt;'),$content);

	if (strpos($atc_content,$db_bbsurl) !== false) {
		$atc_content = str_replace('p_w_picpath',$db_picpath,$atc_content);
		$atc_content = str_replace('p_w_upload',$db_attachname,$atc_content);
	}

	list($guidename,$forumtitle) = getforumtitle(forumindex($foruminfo['fup'],1),1);
	if (trim($subject)) {
		$guidename .= " &raquo; <a href=\"read.php?tid=$tid\">$subject</a>";
	}
	$db_metakeyword = str_replace(array('|',' - '),',',$forumtitle).'phpwind';
	$db_metadescrip = substrs(strip_tags(str_replace('"','&quot;',$atc_content)),50);

	require_once(R_P.'require/header.php');
	$msg_guide = headguide($guidename);
	require_once PrintEot('post');footer();

} elseif ($_POST['step'] == 1) {

	if (!$isGM) {
		if ($winduid != $authorid && !pwRights($isBM,'modother')) {
			Showmsg('modify_del_right');
		} elseif ($_G['allowdelatc'] == 0) {
			Showmsg('modify_group_right');
		}
	}
	$rt = $db->get_one("SELECT COUNT(*) AS count FROM $pw_posts WHERE tid=".pwEscape($tid)." AND ifcheck='1'");
	$count = $rt['count'] + 1;
	if ($article == 0 && !$admincheck && $count > 1) {
		Showmsg('modify_replied');
	}
	$rs = $db->get_one("SELECT replies,topped FROM pw_threads WHERE tid=".pwEscape($tid));
	if ($rs['replies'] != $rt['count']) {
		$db->update("UPDATE pw_threads SET replies=".pwEscape($rt['count'])."WHERE tid=".pwEscape($tid));
	}
	require_once(R_P.'require/credit.php');
	$creditset = $credit->creditset($creditset,$db_creditset);
	if ($aid) {
		delete_att(array($aid));
		pwFtpClose($ftp);
	}
	if ($article == 0) {
		$deltype  = 'deltpc';
		$deltitle = substrs($subject,28);
		if ($count == 1) {
			$db->update("DELETE FROM $pw_tmsgs WHERE tid=".pwEscape($tid));
			$db->update("DELETE FROM pw_threads WHERE tid=".pwEscape($tid));
			P_unlink(R_P."$db_htmdir/$fid/".date('ym',$postdate)."/$tid.html");
		} else {
			$rt = $db->get_one("SELECT * FROM $pw_posts WHERE tid=".pwEscape($tid)."ORDER BY postdate LIMIT 1");
			if ($count == 2) {
				$lastpost	= $rt['postdate'];
				$lastposter	= $rt['author'];
			} else {
				$lt = $db->get_one("SELECT postdate,author FROM $pw_posts WHERE tid=".pwEscape($tid)."ORDER BY postdate DESC LIMIT 1");
				$lastpost	= $lt['postdate'];
				$lastposter	= $lt['author'];
			}
			$count -= 2;
			$db->update("DELETE FROM $pw_posts WHERE pid=".pwEscape($rt['pid']));
			$pwSQL = $rt['subject'] ? array('subject'=>$rt['subject']) : array();
			$pwSQL += array(
				'icon'		=> $rt['icon'],
				'author'	=> $rt['author'],
				'authorid'	=> $rt['authorid'],
				'postdate'	=> $rt['postdate'],
				'lastpost'	=> $lastpost,
				'lastposter'=> $lastposter,
				'replies'	=> $count
			);
			$db->update("UPDATE pw_threads SET ".pwSqlSingle($pwSQL,false)." WHERE tid=".pwEscape($tid));

			$db->update("UPDATE $pw_tmsgs SET " . pwSqlSingle(array(
				'aid'		=> $rt['aid'],				'userip'	=> $rt['userip'],
				'ifsign'	=> $rt['ifsign'],			'ipfrom'	=> $rt['ipfrom'],
				'alterinfo'	=> $rt['alterinfo'],		'ifconvert'	=> $rt['ifconvert'],
				'content'	=> $rt['content']
			),false) . " WHERE tid=".pwEscape($tid));
		}
		$msg_delrvrc  = abs($creditset['Delete']['rvrc']);
		$msg_delmoney = abs($creditset['Delete']['money']);
		$credit->addLog('topic_Delete',$creditset['Delete'],array(
			'uid'		=> $authorid,
			'username'	=> $author,
			'ip'		=> $onlineip,
			'fname'		=> strip_tags($forum[$fid]['name']),
			'operator'	=> $windid
		));
		$credit->sets($authorid,$creditset['Delete'],false);
	} else {
		$deltype  = 'delrp';
		$deltitle = $subject ? substrs($subject,28) : substrs($content,28);
		$db->update("DELETE FROM $pw_posts WHERE pid=".pwEscape($pid));
		$db->update("UPDATE pw_threads SET replies=replies-1 WHERE tid=".pwEscape($tid));
		$msg_delrvrc  = abs($creditset['Deleterp']['rvrc']);
		$msg_delmoney = abs($creditset['Deleterp']['money']);
		$credit->addLog('topic_Deleterp',$creditset['Deleterp'],array(
			'uid'		=> $authorid,
			'username'	=> $author,
			'ip'		=> $onlineip,
			'fname'		=> strip_tags($forum[$fid]['name']),
			'operator'	=> $windid
		));
		$credit->sets($authorid,$creditset['Deleterp'],false);
	}
	$credit->setMdata($authorid,'postnum',-1);
	$credit->runsql();

	if ($db_guestread) {
		require_once(R_P.'require/guestfunc.php');
		clearguestcache($tid,$rs['replies']);
	}
	P_unlink(D_P.'data/bbscache/c_cache.php');
	updateforum($fid);
	if ($rs['topped']) {
		updatetop();
	}
	$msg_delrvrc = floor($msg_delrvrc/10);
	require_once(R_P.'require/writelog.php');
	$log = array(
		'type'      => 'delete',
		'username1' => $author,
		'username2' => $windid,
		'field1'    => $fid,
		'field2'    => '',
		'field3'    => '',
		'descrip'   => $deltype.'_descrip',
		'timestamp' => $timestamp,
		'ip'        => $onlineip,
		'tid'		=> $tid,
		'forum'		=> $foruminfo['name'],
		'subject'	=> $deltitle,
		'affect'	=> "{$db_rvrcname}：-{$msg_delrvrc}，{$db_moneyname}：-{$msg_delmoney}",
		'reason'	=> 'edit delete article!'
	);
	writelog($log);
	if ($foruminfo['allowhtm'] && $article<=$db_readperpage ) {
		include_once(R_P.'require/template.php');
	}
	if ($deltype == 'delrp') {
		refreshto("read.php?tid=$tid",'enter_thread');
	} else {
		refreshto("thread.php?fid=$fid",'enter_thread');
	}
} elseif ($_POST['step'] == 2) {

	InitGP(array('atc_anonymous','atc_iconid','atc_newrp','atc_tags','atc_hideatt','magicid','magicname'),'P');

	if ($article == 0) {
		if (!$p_type || empty($t_typedb[$p_type]) || ($t_per == 0 && !$admincheck)) {
			$w_type = 0;
		} else {
			$w_type = $p_type;
		}
		$db_forcetype && $w_type=='0' && Showmsg('force_tid_select');
	}
	$atc_tags = ($db_iftag && $atc_tags) ? check_tag($atc_tags) : '';
	list($atc_title,$atc_content,$ifconvert,$ifwordsfb) = check_data($action);
	$sqladd = $upmemdata = '';
	$runsql = array();

	switch ($special) {
		case 1:
			$voteopts  = $db->get_value("SELECT voteopts FROM pw_polls WHERE tid=".pwEscape($tid));
			$votearray = unserialize($voteopts);
			InitGP(array('vt_selarray','regdatelimit'),'P');
			InitGP(array('timelimit','multiplevote','modifiable','mostvotes','previewable','vote_close','leastvotes','postnumlimit','creditlimit'),'P',2);
			if ($_G['modifyvote'] && is_array($votearray) && is_array($vt_selarray)) {
				$newvotearray = array();
				foreach ($vt_selarray as $key => $value) {
					$value = trim($value);
					if ($value) {
						!$votearray[$key][1] && $votearray[$key][1] = 0;
						$newvotearray[$key] = array(stripslashes($value), $votearray[$key][1]);
					}
				}
				$vtcount = count($newvotearray);
				if (empty($multiplevote)) {
					$mostvotes = 1;
				} elseif (!is_numeric($mostvotes) || $mostvotes > $vtcount || $mostvotes < 1) {
					$mostvotes = $vtcount;
				}
				if (empty($multiplevote) || !is_numeric($leastvotes) || $leastvotes > $mostvotes || $leastvotes < 1) {
					$leastvotes = 1;	
				}
				$voteopts = serialize($newvotearray);
				!$modifiable && $modifiable = 0;
				!$previewable && $previewable = 0;
				$timelimit < 0 && $timelimit = 0;
				$regdatelimit = strtotime($regdatelimit);
				$regdatelimit = $regdatelimit > $timestamp ? $timestamp : $regdatelimit;
				foreach ($creditlimit as $key => $value) {
					if (!empty($value)) {
						$creditlimit_temp[$key] = (int)$value; 
					}
				}
				$creditlimit = serialize($creditlimit_temp);
				$postnumlimit = (int)$postnumlimit > 0 ? (int)$postnumlimit : '';
				$db->update("UPDATE pw_polls SET ".pwSqlSingle(array(
					'voteopts'		=> $voteopts,			'modifiable'	=> $modifiable,
					'previewable'	=> $previewable,		'multiple'		=> $multiplevote,
					'mostvotes'		=> $mostvotes,			'timelimit'		=> $timelimit,
					'leastvotes'	=> $leastvotes,			'regdatelimit' 	=> $regdatelimit,
					'creditlimit' 	=> $creditlimit,		'postnumlimit' 	=> $postnumlimit
				),false). " WHERE tid=".pwEscape($tid));
			}
			$vote_close && $sqladd .= ",state='1'";
			break;
		case 2:
			InitGP(array('act_subject','act_location','act_starttime','act_deadline','act_endtime', 'act_sex'),'P');
			InitGP(array('act_num','act_costs'),'P',2);
			!($act_subject && $act_starttime && $act_deadline) && Showmsg('active_data_empty');
			$act_starttime= PwStrtoTime($act_starttime);
			$act_endtime  = PwStrtoTime($act_endtime);
			$act_deadline = PwStrtoTime($act_deadline);
			$act = $db->get_one("SELECT * FROM pw_activity WHERE tid=".pwEscape($tid));

			$timestamp > $act['starttime'] && $act['starttime'] != $act_starttime && Showmsg('can_not_modify_start');
			$act_starttime < $timestamp && $act['starttime'] != $act_starttime && Showmsg('starttime_limit');

			$act_endtime < $timestamp && $act['endtime'] > $act_endtime && Showmsg('can_not_end');
			$act_endtime && $act_starttime > $act_endtime && Showmsg('endtime_limit');

			$act_endtime && $act_deadline > $act_endtime && $act_deadline != $act['deadline'] && Showmsg('deadline_endtime_limit');

			@extract($db->get_one('SELECT COUNT(*) AS count FROM pw_actmember WHERE actid='.pwEscape($tid).' AND state=1'));
			$act_num < $count && Showmsg('active_num_limit');
			$act_num<1 && $act_num=0;
			$act_costs<1 && $act_costs=0;
			$db->update("UPDATE pw_activity SET ".pwSqlSingle(array(
				'subject'	=> $act_subject,
				'starttime'	=> $act_starttime,
				'endtime'	=> $act_endtime,
				'location'	=> $act_location,
				'num'		=> $act_num,
				'sexneed'	=> $act_sex,
				'costs'		=> $act_costs,
				'deadline'	=> $act_deadline
			)) . " WHERE tid=".pwEscape($tid));
			break;
		case 3:
			if (empty($_POST['addreward'])) break;

			$rewdb = $db->get_one("SELECT cbtype,catype,timelimit FROM pw_reward WHERE tid=".pwEscape($tid));
			if ($_POST['ctype']['best'] <> $rewdb['cbtype'] || $_POST['ctype']['active'] <> $rewdb['catype']) {
				Showmsg('reward_credit_error');
			}
			require_once(R_P.'require/postreward.php');
			$runsql[] = 'UPDATE pw_reward SET cbval=cbval+' . pwEscape($bonus['best']) . ',caval=caval+' . pwEscape($bonus['active']) . ',timelimit=' . pwEscape($timelimit) . " WHERE tid=".pwEscape($tid);
			break;
		case 4:
			InitGP(array('goodsname','price','costprice','locus','mailfee','expressfee','emsfee'));
			InitGP(array('degree','ptype','goodsnum','paymethod','transport'), 2);
			!$goodsname && $goodsname = $atc_title;
			if (!is_numeric($costprice) || $costprice <= 0) {
				Showmsg('goods_setprice');
			}
			$goodsnum < 1 && Showmsg('goods_num_error');
			$paymethod = array_sum($paymethod);
			$paymethod < 1 && Showmsg('goods_pay_error');
			!is_numeric($price) && $price = 0;

			if ($transport) {
				!is_numeric($mailfee) && $mailfee = 0;
				!is_numeric($expressfee) && $expressfee = 0;
				!is_numeric($emsfee) && $emsfee = 0;
				if (!$mailfee && !$expressfee && !$emsfee) {
					Showmsg('goods_logistics');
				}
			} else {
				$mailfee = $expressfee = $emsfee = 0;
			}
			$goodsicon = '';
			break;
		case 5:
			require_once(R_P.'require/postdebate.php');
			break;
	}
	$ifcheck && $ifcheck = alarm($atc_title,$atc_content);
	/**
	* 附件修改
	*/
	$oldattach = $replacedb = $unsetattach = array();
	if ($aid) {
		InitGP(array('keep','oldatt_special','oldatt_needrvrc'), 'P', 2);
		InitGP(array('oldatt_ctype','oldatt_desc'), 'P');
		$oldattach = unserialize(stripslashes($aid));
		foreach ($oldattach as $key => $value) {
			if (!@in_array($key,$keep)) {
				$unsetattach[$key] = $value;
				unset($oldattach[$key]);
			} else {
				$v = array(
					'special'	=> $oldatt_special[$key],		'ctype'		=> $oldatt_ctype[$key],
					'needrvrc'	=> $oldatt_needrvrc[$key],		'desc'		=> $oldatt_desc[$key]
				);
				if ($v['needrvrc'] > 0 && ($v['special'] == 1 && $htmlhide == '' && in_array($v['ctype'],$db_enhideset['type']) || $v['special'] == 2 && $htmlsell == '' && in_array($v['ctype'],$db_sellset['type']))) {

				} else {
					$v['needrvrc'] = $v['special'] = 0;
					$v['ctype'] = '';
				}
				$oldattach[$key] = array_merge($oldattach[$key], $v);

				if (array_key_exists('replace_'.$key, $_FILES)) {
					$db_attachnum++;
					$replacedb[$key] = $oldattach[$key];
				} elseif ($value['needrvrc'] <> $v['needrvrc'] || $value['special'] <> $v['special'] || $value['ctype'] <> $v['ctype'] || $value['desc'] <> $v['desc']) {
					$runsql[] = 'UPDATE pw_attachs SET ' . pwSqlSingle(array(
						'needrvrc'	=> $v['needrvrc'],
						'descrip'	=> $v['desc'],
						'special'	=> $v['special'],
						'ctype'		=> $v['ctype']
					)) . ' WHERE aid=' . pwEscape($key);
				}
			}
		}
	}
	require_once(R_P.'require/postupload.php');

	$upmemdata = is_object($credit) ? $credit->runsql($winduid) : '';
	if ($attachs) {
		$attachs = unserialize(stripslashes($attachs));
		foreach ($attachs as $key => $value) {
			$oldattach[$key] = $value;
		}
		$upmemdata .= ($upmemdata ? ',' : '')."uploadtime=".pwEscape($winddb['uploadtime']).",uploadnum=".pwEscape($winddb['uploadnum']);
	}
	if ($upmemdata) {
		$db->update("UPDATE pw_memberdata SET $upmemdata WHERE uid=".pwEscape($winduid));
	}
	if ($oldattach) {
		$oldattach = addslashes(serialize($oldattach));
	} else {
		$oldattach = '';
	}
	$atc_iconid = is_numeric($atc_iconid) ? $atc_iconid : $icon;
	$timeofedit = get_date($timestamp);
	$anonymous  = (($isGM || $forumset['anonymous'] && $_G['anonymous']) && $atc_anonymous) ? 1 : 0;
	$ifhide		= (($isGM || $foruminfo['allowhide'] && $_G['allowhidden']) && $atc_hideatt) ? 1 : 0;

	if ($groupid != 3 && $postdate + 300 < $timestamp) {
		$altername = $anonymous && $windid==$author ? $db_anonymousname : $windid;
		$alterinfo = getLangInfo('post','edit_post');
	} else {
		$alterinfo = '';
	}
	if ($winduid != $authorid) {
		/**
		* 管理员编辑帖子的安全日记
		*/
		require_once(R_P.'require/writelog.php');
		$log = array(
			'type'      => 'edit',
			'username1' => $author,
			'username2' => $windid,
			'field1'    => $fid,
			'field2'    => '',
			'field3'    => '',
			'descrip'   => 'edit_descrip',
			'timestamp' => $timestamp,
			'ip'        => $onlineip,
			'tid'		=> $tid,
			'forum'		=> $foruminfo['name'],
			'subject'	=> substrs($subject,28),
			'reason'	=> 'edit article'
		);
		writelog($log);
	}

	$atc_content = trim($atc_content);
	if ($authorid == $winduid) {
		$pwSQL = array('userip' => $onlineip, 'ipfrom' => $ipfrom);
	} else {
		$pwSQL = array();
	}
	if ($article == 0) {
		if ($db_iftag) {
			if ($atc_tags != $tags) {
				update_tag($tid,$atc_tags);
			}
			$atc_tags .= "\t".relate_tag($atc_title,$atc_content);
		}
		$ifmagic   = 0;
		$magic     = '';
		if ($db_windmagic && $magicid) {
			$ifmagic	= 1;
			$magic		= $magicid."\t".$magicname;
		}
		$pwSQL += array(
			'aid'		=> $oldattach,
			'ifsign'	=> $atc_usesign,
			'alterinfo'	=> $alterinfo,
			'tags'		=> $atc_tags,
			'ifconvert'	=> $ifconvert,
			'ifwordsfb'	=> $ifwordsfb,
			'content'	=> $atc_content,
			'magic'		=> $magic
		);
		$db->update("UPDATE $pw_tmsgs SET ".pwSqlSingle($pwSQL)."WHERE tid=".pwEscape($tid));
		if ($aids) {
			$db->update("UPDATE pw_attachs SET tid=".pwEscape($tid)." WHERE aid IN($aids)");
		}
		if ($anonymous != $tpcdb['anonymous'] && $postdate==$lastpost) {
			$lastposter = $anonymous ? $db_anonymousname : $author;
			$sqladd .= ",lastposter=".pwEscape($lastposter);
		}
	} else {
		$pwSQL += array(
			'aid'		=> $oldattach,
			'icon'		=> $atc_iconid,
			'subject'	=> $atc_title,
			'ifsign'	=> $atc_usesign,
			'alterinfo'	=> $alterinfo,
			'ifconvert'	=> $ifconvert,
			'ifwordsfb'	=> $ifwordsfb,
			'content'	=> $atc_content,
			'anonymous'	=> $anonymous,
			'ifhide'	=> $ifhide,
			'ifcheck'	=> $ifcheck
		);
		$db->update("UPDATE $pw_posts SET ".pwSqlSingle($pwSQL)." WHERE pid=".pwEscape($pid));
		if ($aids) {
			$db->update("UPDATE pw_attachs SET tid=".pwEscape($tid).",pid=".pwEscape($pid)." WHERE aid IN($aids)");
		}
		if ($anonymous != $atcdb['anonymous']) {
			$lt = $db->get_one("SELECT pid FROM $pw_posts WHERE tid=".pwEscape($tid)." ORDER BY postdate DESC LIMIT 1");
			if ($pid == $lt['pid']) {
				$lastposter = $anonymous ? $db_anonymousname : $author;
				$sqladd .= ",lastposter=".pwEscape($lastposter);
			}
		}
	}
	$ifupload = getattachtype($tid);

	if ($article == 0) {
		$ifmail = $db_replysitemail && $atc_newrp ? 2 : 0;
		$pwSQL = pwSqlSingle(array(
			'icon'		=> $atc_iconid,
			'subject'	=> $atc_title,
			'type'		=> $w_type,
			'ifupload'	=> $ifupload,
			'ifmail'	=> $ifmail,
			'anonymous'	=> $anonymous,
			'ifmagic'	=> $ifmagic,
			'ifhide'	=> $ifhide,
			'ifcheck'	=> $ifcheck
		));
		$db->update("UPDATE pw_threads SET $pwSQL $sqladd WHERE tid=".pwEscape($tid));
	} else {
		$db->update("UPDATE pw_threads SET ifupload=".pwEscape($ifupload)."$sqladd WHERE tid=".pwEscape($tid));
	}
	if ($unsetattach) {
		delete_att(array(serialize($unsetattach)));
		pwFtpClose($ftp);
	}
	if ($runsql) {
		foreach ($runsql as $key => $value){
			$value && $db->update($value);
		}
	}
	if ($special == 4) {
		$pwSQL = array(
			'tid'		=> $tid,			'name'		=> $goodsname,
			'degree'	=> $degree,			'type'		=> $ptype,
			'num'		=> $goodsnum,		'price'		=> $price,
			'costprice'	=> $costprice,		'locus'		=> $locus,
			'paymethod'	=> $paymethod,		'transport'	=> $transport,
			'mailfee'	=> $mailfee,		'expressfee'=> $expressfee,
			'emsfee'	=> $emsfee
		);
		$goodsicon && $pwSQL['icon'] = $goodsicon;
		$db->update("UPDATE pw_trade SET " . pwSqlSingle($pwSQL) . " WHERE tid=" . pwEscape($tid));
	}

	//Start elementupdate
	if (($db_ifpwcache & 512) && $elementpic && $pid == 'tpc') {
		require_once(R_P.'require/elementupdate.class.php');
		$elementupdate = new ElementUpdate($fid);
		$elementupdate->newPicUpdate($elementpic['aid'],$fid,$tid,$elementpic['attachurl'],'',$atc_content);
		$elementupdate->updateSQL();
	}
	//End elementupdate
	if ($ifcheck && $foruminfo['allowhtm'] && !$foruminfo['cms'] && $article < $db_readperpage) {
		include_once (R_P.'require/template.php');
	}
	$rt = $db->get_one("SELECT lastpost FROM pw_forumdata WHERE fid=".pwEscape($fid));
	$lastpost = explode("\t",$rt['lastpost']);

	if ($lastpost[2] == $postdate) {
		lastinfo($fid,$foruminfo['allowhtm'],'',$foruminfo['cms'].'B');
	}
	refreshto("read.php?tid=$tid&page=$page&toread=1#$pid",$ifcheck ? 'enter_thread' : 'post_check');
}
?>