<?php
define('SCR','job');
require_once('global.php');

InitGP(array('action'));

if ($action == 'sign') {

	Cookie('newpic',$timestamp);
	refreshto("$db_bfn",'operate_success');

} elseif ($action == 'preview') {

	require_once(R_P.'require/bbscode.php');
	require_once(R_P.'require/header.php');
	InitGP(array('atc_content'),'P');
	$atc_content = str_replace("\n","<br>",$atc_content);
	$atc_content = wordsfb($atc_content);
	$preatc = convert($atc_content,$db_windpost);
	require_once PrintEot('preview');footer();

} elseif ($action == 'redirect') {

	InitGP(array('goto'));
	InitGP(array('aid'),'GP',2);
	$rt = $db->get_one('SELECT uid,uploadtime FROM pw_attachs WHERE aid='.pwEscape($aid));
	if ($rt) {
		$urladd = '';
		if ($goto == 'next') {
			$rt = $db->get_one("SELECT aid,tid FROM pw_attachs WHERE uid=".pwEscape($rt['uid'])." AND type='img' AND aid<".pwEscape($aid)." ORDER BY aid DESC LIMIT 1");
			!$rt['aid'] && $urladd = '&nonext=1';
		} elseif ($goto == 'pre') {
			$rt = $db->get_one("SELECT aid,tid FROM pw_attachs WHERE uid=".pwEscape($rt['uid'])." AND type='img' AND aid>".pwEscape($aid)." ORDER BY aid LIMIT 1");
			!$rt['aid'] && $urladd = '&nopre=1';
		}
		$rt['aid'] && $aid=$rt['aid'];
		ObHeader("show.php?action=pic&tid=$rt[tid]&aid=$aid$urladd");
	} else {
		Showmsg('pic_not_exists');
	}
} elseif ($action == 'previous') {
	$rt = $db->get_one('SELECT fid,postdate,lastpost FROM pw_threads WHERE tid='.pwEscape($tid));
	$rt || Showmsg('data_error');
	$fid = (int)$rt['fid'];
	$goto = Char_cv(GetGP('goto'));
	if ($goto == "next") {
		$tid = $db->get_value("SELECT tid FROM pw_threads WHERE fid=".pwEscape($fid,false)."AND ifcheck='1' AND topped='0' AND lastpost<".pwEscape($rt['lastpost'],false)."ORDER BY lastpost DESC LIMIT 1");
	} else {
		$tid = $db->get_value("SELECT tid FROM pw_threads WHERE fid=".pwEscape($fid,false)."AND ifcheck='1' AND topped='0' AND lastpost>".pwEscape($rt['lastpost'],false)."ORDER BY lastpost ASC LIMIT 1");
	}
	if ($tid) {
		ObHeader("read.php?tid=$tid");
	} else {
		ObHeader("thread.php?fid=$fid");
	}
} elseif ($action == 'mutiupload') {

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

		$_G['uploadtype'] && $db_uploadfiletype = $_G['uploadtype'];
		$db_uploadfiletype = !empty($db_uploadfiletype) ? unserialize($db_uploadfiletype) : array();
		$filetype = '';
		foreach ($db_uploadfiletype as $key => $value) {
			$filetype .= ($filetype ? ',' : '') . $key . ':' . $value;
		}
		$pwServer['HTTP_USER_AGENT'] = 'Shockwave Flash';
		$swfhash = GetVerify($winduid);

		echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><swf><filetype>{$filetype}</filetype><uid>{$winduid}</uid><step>2</step><verify>{$swfhash}</verify></swf>";

	} else {

		InitGP(array('uid','verify'),'P');
		$swfhash = GetVerify($uid);
		checkVerify('swfhash');
		if (!$db_allowupload) {
			Showmsg('upload_close');
		}
		$rt = $db->get_one("SELECT groupid,memberid FROM pw_members WHERE uid=" . pwEscape($uid));
		$groupid = $rt['groupid'] == '-1' ? $rt['memberid'] : $rt['groupid'];
		if (file_exists(D_P."data/groupdb/group_$groupid.php")) {
			require_once Pcv(D_P."data/groupdb/group_$groupid.php");
		} else {
			require_once(D_P.'data/groupdb/group_1.php');
		}
		if ($_G['allowupload'] == 0) {
			Showmsg('upload_group_right');
		}
		$_G['allownum'] = 15;
		$uploadnum = $db->get_value("SELECT COUNT(*) AS sum FROM pw_attachs WHERE tid=0 AND pid='0' AND uid=" . pwEscape($uid));
		if ($uploadnum >= $_G['allownum']) {
			Showmsg('upload_num_error');
		}
		$_G['uploadtype'] && $db_uploadfiletype = $_G['uploadtype'];
		$db_uploadfiletype = !empty($db_uploadfiletype) ? unserialize($db_uploadfiletype) : array();

		require_once(R_P.'require/postfunc.php');
		$db_ifftp = $db_watermark = $db_ifathumb = $db_attachdir = $fid = 0;
		$attachdir .= '/mutiupload';
		$uploaddb = UploadFile($uid);
		foreach ($uploaddb as $key => $value) {
			$value['name'] = pwConvert($value['name'],$db_charset,'utf-8');
			$db->update("INSERT INTO pw_attachs SET ".pwSqlSingle(array(
				'fid'		=> 0,					'uid'		=> $uid,
				'tid'		=> 0,					'pid'		=> 0,
				'hits'		=> 0,					'name'		=> $value['name'],
				'type'		=> $value['type'],		'size'		=> $value['size'],
				'attachurl'	=> $value['attachurl'],	'uploadtime'=> $timestamp,
				'ifthumb'	=> $value['ifthumb']
			)));
		}
		exit;
	}

} elseif ($action == 'download') {

	set_time_limit(300);
	InitGP(array('aid','pid'));
	(!$tid || !is_numeric($aid)) && Showmsg('job_attach_error');
	if (is_numeric($pid)) {
		$table = GetPtable('N',$tid);
		$where = 'pid='.pwEscape($pid);
		$post  = $db->get_one("SELECT fid,aid,author,authorid FROM $table WHERE pid=".pwEscape($pid));
	} else {
		$table = GetTtable($tid);
		$where = 'tid='.pwEscape($tid);
		$post  = $db->get_one("SELECT t.fid,t.author,t.authorid,tm.aid FROM pw_threads t LEFT JOIN $table tm USING(tid) WHERE t.tid=".pwEscape($tid));
	}
	$attach = unserialize(stripslashes($post['aid']));
	$fid = $post['fid'];
	$attachurl = '';
	!$attach[$aid] && Showmsg('job_attach_error');
	@extract($attach[$aid]);
	if (!$attachurl || strpos($attachurl,'..') !== false) {
		Showmsg('job_attach_error');
	}
	if (!$windid && GetCookie('winduser') && $ol_offset) {
		$userdb = explode("\t",getuserdb(D_P."data/bbscache/online.php",$ol_offset));
		if ($userdb && $userdb[2] == $onlineip) {
			$winddb = $db->get_one("SELECT m.uid,m.username,m.groupid,m.memberid,m.groups,md.money,md.rvrc FROM pw_members m LEFT JOIN pw_memberdata md USING(uid) WHERE m.uid=".pwEscape($userdb['8']));
			$winduid  = $winddb['uid'];
			$groupid  = $winddb['groupid'];
			$groupid == '-1' && $groupid=$winddb['memberid'];
			$userrvrc = (int)($winddb['rvrc']/10);
			$windid	  = $winddb['username'];
			if (file_exists(D_P."data/groupdb/group_$groupid.php")) {
				require_once Pcv(D_P."data/groupdb/group_$groupid.php");
			} else {
				require_once(D_P."data/groupdb/group_1.php");
			}
		}
		define('FX',1);
	}
	require_once(R_P.'require/forum.php');
	$foruminfo = $db->get_one('SELECT f.name,f.f_type,f.style,f.password,f.allowvisit,f.forumadmin,f.fupadmin,f.allowdownload,fe.forumset FROM pw_forums f LEFT JOIN pw_forumsextra fe USING(fid) WHERE f.fid='.pwEscape($fid));
	!$foruminfo && Showmsg('data_error');
	wind_forumcheck($foruminfo);
	/*
	* 獲取管理權限
	*/
	if ($groupid == '3' || admincheck($foruminfo['forumadmin'],$foruminfo['fupadmin'],$windid)) {
		$admincheck = 1;
	} else {
		$admincheck = 0;
	}
	/**
	* 版塊權限判斷
	*/
	if ($foruminfo['allowdownload'] && !allowcheck($foruminfo['allowdownload'],$groupid,$winddb['groups']) && !$admincheck) {
		Showmsg('job_attach_forum');
	}
	/**
	* 用戶組權限判斷
	*/
	if (!$foruminfo['allowdownload'] && $_G['allowdownload']==0 && !$admincheck) {
		Showmsg('job_attach_group');
	}
	if (!$attach_url && !$db_ftpweb && !is_readable("$attachdir/$attachurl")) {
		Showmsg('job_attach_error');
	}

	$filename = basename("$attachdir/$attachurl");
	$fileext  = substr(strrchr($attachurl,'.'),1);
	$filesize = 0;

	if (strpos($pwServer['HTTP_USER_AGENT'], 'MSIE')!==false && $fileext == 'torrent') {
		$attachment = 'inline';
	} else {
		$attachment = 'attachment';
	}
	if ($db_charset == 'utf-8') {
		if (function_exists('mb_convert_encoding')) {
			$name = mb_convert_encoding($name, "gbk",'utf-8');
		} else {
			require_once(R_P.'wap/chinese.php');
			$chs  = new Chinese('UTF8','gbk');
			$name = $chs->Convert($name);
		}
	}
	$fgeturl = geturl($attachurl);
	!$fgeturl[0] && Showmsg('job_attach_error');

	$credit = null;
	if ($needrvrc > 0 && !$admincheck) {
		!$windid && Showmsg('job_attach_special');
		require_once(R_P.'require/credit.php');
		if ($special == '2') {
			if (!$ifbuy = $db->get_one("SELECT uid FROM pw_attachbuy WHERE aid=" . pwEscape($aid) . " AND uid=" . pwEscape($winduid))) {
				!$ctype && $ctype = 'money';
				$usercredit = $credit->get($winduid,$ctype);
				$creditName = $credit->cType[$ctype];
				$db_sellset['price'] > 0 && $needrvrc = min($needrvrc, $db_sellset['price']);
				if ($usercredit < $needrvrc) {
					Showmsg('job_attach_sale');
				}
				$db->update("INSERT INTO pw_attachbuy SET " . pwSqlSingle(array(
					'aid'	=> $aid,	'uid'	=> $winduid,
					'ctype'	=> $ctype,	'cost'	=> $needrvrc
				)));
				$credit->addLog('topic_attbuy',array($ctype => -$needrvrc),array(
					'uid'		=> $winduid,
					'username'	=> $windid,
					'ip'		=> $onlineip
				));
				$credit->set($winduid, $ctype, -$needrvrc, false);

				if ($db_sellset['income'] < 1 || ($income = $db->get_value("SELECT SUM(cost) AS sum FROM pw_attachbuy WHERE aid=" . pwEscape($aid))) < $db_sellset['income']) {
					$credit->addLog('topic_attsell',array($ctype => $needrvrc),array(
						'uid'		=> $post['authorid'],
						'username'	=> $post['author'],
						'ip'		=> $onlineip,
						'buyer'		=> $windid
					));
					$credit->set($post['authorid'], $ctype, $needrvrc, false);
				}
			}
		} else {
			!$ctype && $ctype = 'rvrc';
			$usercredit = $credit->get($winduid,$ctype);
			if ($usercredit < $needrvrc) {
				$creditName = $credit->cType[$ctype];
				Showmsg('job_attach_rvrc');
			}
		}
	}
	if ($_G['allowdownload'] == 1) {
		$forumset = unserialize($foruminfo['forumset']);
		list($uploadcredit,,$downloadmoney,) = explode("\t",$forumset['uploadset']);
		if ($downloadmoney) {
			require_once(R_P.'require/credit.php');
			if ($downloadmoney > 0 && $credit->get($winduid,$uploadcredit) < $downloadmoney) {
				$creditname = $credit->cType[$uploadcredit];
				Showmsg('download_money_limit');
			}
			$credit->addLog('topic_download',array($uploadcredit => -$downloadmoney),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'fname'		=> $foruminfo['name']
			));
			if (!$credit->set($winduid, $uploadcredit, -$downloadmoney, false)) {
				Showmsg('undefined_action');
			}
		}
	}
	if (isset($credit) && $credit->cUser) {
		$credit->runsql();
	}

	$attach[$aid]['hits']++;
	$attach = addslashes(serialize($attach));
	$db->update("UPDATE $table SET aid=".pwEscape($attach)." WHERE $where");
	$db->update('UPDATE pw_attachs SET hits=hits+1 WHERE aid='.pwEscape($aid));

	if ($db_attachhide && $size>$db_attachhide && $type == 'zip' && !defined('FX')) {
		ObHeader($fgeturl[0]);
	} elseif ($fgeturl[1] == 'Local') {
		$fgeturl[0] = R_P.$fgeturl[0];
		$filesize   = filesize($fgeturl[0]);
	}
	$ctype = '';
	switch($fileext) {
		case "pdf"	: $ctype = "application/pdf"; break;
		case "rar"	:
		case "zip"	: $ctype = "application/zip"; break;
		case "doc"	: $ctype = "application/msword"; break;
		case "xls"	: $ctype = "application/vnd.ms-excel"; break;
		case "ppt"	: $ctype = "application/vnd.ms-powerpoint"; break;
		case "gif"	: $ctype = "image/gif"; break;
		case "png"	: $ctype = "image/png"; break;
		case "jpeg"	:
		case "jpg"	: $ctype = "image/jpeg"; break;
		case "wav"	: $ctype = "audio/x-wav"; break;
		case "mpeg"	:
		case "mpg"	:
		case "mpe"	: $ctype = "video/x-mpeg"; break;
		case "mov"	: $ctype = "video/quicktime"; break;
		case "avi"	: $ctype = "video/x-msvideo"; break;
		case "txt"	: $ctype = "text/plain"; break;
		default		: $ctype = "application/octet-stream";
	}
	ob_end_clean();
	header('Last-Modified: '.gmdate('D, d M Y H:i:s',$timestamp+86400).' GMT');
	header('Expires: '.gmdate('D, d M Y H:i:s',$timestamp+86400).' GMT');
	header('Cache-control: max-age=86400');
	header('Content-Encoding: none');
	header("Content-Disposition: $attachment; filename=\"$name\"");
	header("Content-type: $ctype");
	header("Content-Transfer-Encoding: binary");
	$filesize && header("Content-Length: $filesize");
	$i = 1;
	while (!@readfile($fgeturl[0])) {
			if (++$i > 3) break;
	}
	exit;

} elseif ($action == 'showimg') {

	InitGP(array('verify','pid','aid'));
	if ($verify != md5("showimg{$tid}{$pid}{$fid}{$aid}{$db_hash}")) {
		Showmsg('undefined_action');
	}
	if (function_exists('file_get_contents')) {
		$rs = $db->get_one('SELECT attachurl FROM pw_attachs WHERE aid='.pwEscape($aid).' AND tid='.pwEscape($tid).' AND fid='.pwEscape($fid));
		if ($rs) {
			$fgeturl = geturl($rs['attachurl']);
			if ($fgeturl[0]) {
				echo file_get_contents($fgeturl[0]);exit;
			}
		}
	}
	Showmsg('job_attach_error');

} elseif ($action == 'deldownfile') {

	PostCheck();
	InitGP(array('aid','pid','page'));
	(!$tid || !is_numeric($aid)) && Showmsg('job_attach_error');
	if (is_numeric($pid)) {
		$table = $pw_posts = GetPtable('N',$tid);
		$where = 'pid='.pwEscape($pid);
		$post  = $db->get_one("SELECT fid,tid,aid AS oldaid,authorid FROM $pw_posts WHERE pid=".pwEscape($pid));
	} else {
		$table = $pw_tmsgs = GetTtable($tid);
		$where = 'tid='.pwEscape($tid);
		$post  = $db->get_one("SELECT t.tid,t.fid,t.authorid,t.ptable,tm.aid AS oldaid FROM pw_threads t LEFT JOIN $pw_tmsgs tm USING(tid) WHERE t.tid=".pwEscape($tid));
		$pw_posts = GetPtable($post['ptable']);
	}
	$tid    = $post['tid'];
	$fid    = $post['fid'];
	$attach = unserialize(stripslashes($post['oldaid']));
	$attachurl = '';
	!$attach[$aid] && Showmsg('job_attach_error');
	@extract($attach[$aid]);
	if (!$attachurl || strpos($attachurl,'..') !== false) {
		Showmsg('job_attach_error');
	}
	require_once(R_P.'require/forum.php');
	require_once(R_P.'require/updateforum.php');

	$foruminfo = $db->get_one('SELECT name,f_type,style,password,allowvisit,forumadmin,fupadmin,allowhtm,cms FROM pw_forums WHERE fid='.pwEscape($fid));
	!$foruminfo && Showmsg('data_error');
	wind_forumcheck($foruminfo);
	/*
	*  獲取管理權限
	*/
	$isGM = CkInArray($windid,$manager);
	$isBM = admincheck($foruminfo['forumadmin'],$foruminfo['fupadmin'],$windid);
	if ($isGM || pwRights($isBM,'delattach')) {
		$admincheck = 1;
	} else {
		$admincheck = 0;
	}
	if ($groupid != 'guest' && ($admincheck || $post['authorid'] == $winduid)) {
		pwDelatt($attachurl,$db_ifftp);
		pwFtpClose($ftp);
		$attach = unserialize(stripslashes($post['oldaid']));
		unset($attach[$aid]);
		if ($attach) {
			$attach = serialize($attach);
		} else {
			$attach = '';
		}
		$db->update("UPDATE $table SET aid=".pwEscape($attach,false)." WHERE $where");
		$db->update("DELETE FROM pw_attachs WHERE aid=".pwEscape($aid));

		$ifupload = getattachtype($tid);
		$db->update('UPDATE pw_threads SET ifupload='.pwEscape($ifupload).' WHERE tid='.pwEscape($tid));
		if ($foruminfo['allowhtm'] && $page == 1) {
			require_once(R_P.'require/template.php');
			empty($j_p) && $j_p="read.php?tid=$tid";
			refreshto($j_p,'operate_success');
		} else {
			refreshto("read.php?tid=$tid&page=$page",'operate_success');
		}
	} else {
		Showmsg('job_attach_right');
	}
} elseif ($action == 'viewtody') {

	$wind_in = 'vt';
	if ($db_today == 0) {
		Showmsg('job_viewtody_close');
	}
	InitGP(array('page'),'GP',2);
	require_once(R_P.'require/header.php');
	$check_admin="N";
	if (CkInArray($windid,$manager)) $check_admin="Y";
	$page < 1 && $page = 1;
	$filename = D_P.'data/bbscache/today.php';
	$dbtdsize = 100+1;
	$seed = $page*$db_perpage;$count=0;
	if ($fp = @fopen($filename,"rb")) {
		flock($fp,LOCK_SH);
		$node=fread($fp,$dbtdsize);
		$nodedb=explode("\t",$node);/*頭結點在第二個數據段*/
		$nodefp=$dbtdsize*$nodedb[1];
		fseek($fp,$nodefp,SEEK_SET);
		$todayshow=fseeks($fp,$dbtdsize,$seed);/*傳回數組*/
		fseek($fp,0,SEEK_END);
		$count=floor(ftell($fp)/$dbtdsize)-1;
		fclose($fp);
	}
	if ($count%$db_perpage==0) {
		$numofpage = $count/$db_perpage;  //$numofpage為 一共多少頁
	} else {
		$numofpage = floor($count/$db_perpage)+1;
	}
	if ($page > $numofpage)
		$page = $numofpage;

	$pagemin = min(($page-1)*$db_perpage , $count-1);
	$pagemax = min($pagemin+$db_perpage-1, $count-1);
	$pages = numofpage($count,$page,$numofpage,"job.php?action=viewtody&");

	$inbbsdb = array();
	for ($i = $pagemin; $i <= $pagemax; $i++) {
		if (!trim($todayshow[$i]))
			continue;
		list($inbbs['user'],$null1,$null2,$inbbs['rgtime'],$inbbs['logintime'],$inbbs['intime'],$inbbs['ip'],$inbbs['post'],$inbbs['rvrc'],$null) = explode("\t",$todayshow[$i]);
		$inbbs['rawuser']	= rawurlencode($inbbs['user']);
		$inbbs['rvrc']		= floor($inbbs['rvrc']/10);
		$inbbs['rgtime']	= get_date($inbbs['rgtime']);
		$inbbs['logintime']	= get_date($inbbs['logintime']);
		$inbbs['intime']	= get_date($inbbs['intime']);
		if ($check_admin == "N") {
			$inbbs['ip'] = "secret";
		}
		$inbbsdb[] = $inbbs;
	}

	require_once PrintEot('todayinbbs');footer();

} elseif ($action == 'buytopic') {

	PostCheck();
	InitGP(array('pid'));
	$tpcs = array();
	if ($pid == 'tpc') {
		$table = GetTtable($tid);
		$tpcs  = $db->get_one("SELECT t.author,t.authorid,t.subject,tm.userip,tm.content,tm.buy FROM pw_threads t LEFT JOIN $table tm ON tm.tid=t.tid WHERE t.tid=".pwEscape($tid));
		$where = '';
	} elseif (is_numeric($pid)) {
		$table = GetPtable('N',$tid);
		$tpcs  = $db->get_one("SELECT author,authorid,subject,userip,content,buy FROM $table WHERE pid=".pwEscape($pid).' AND tid='.pwEscape($tid));
		$where = ' AND pid='.pwEscape($pid);
	}
	!$tpcs && Showmsg('illegal_tid');

	!$tpcs['subject'] && $tpcs['subject'] = preg_replace('/\[.*?\]/i','',substrs($tpcs['content'],25));
	$tpcs['content'] = substr($tpcs['content'],strpos($tpcs['content'],'[sell=')+6);
	$cost = substr($tpcs['content'],0,strpos($tpcs['content'],']'));
	list($creditvalue,$credittype) = explode(',',$cost);

	if (empty($windid) || $winduid == $tpcs['authorid']) {
		Showmsg('undefined_action');
	}
	if ($tpcs['buy'] && strpos(','.$tpcs['buy'].',',','.$windid.',') !== false) {
		Showmsg('job_havebuy');
	}
	$count	 = count(explode(',',$tpcs['buy']));
	$creditvalue = (int)$creditvalue;
	if ($creditvalue < 1) {
		$creditvalue = 1;
	} elseif ($db_sellset['price'] && $creditvalue > $db_sellset['price']) {
		$creditvalue = $db_sellset['price'];
	}
	require_once(R_P.'require/credit.php');
	!isset($credit->cType[$credittype]) && $credittype = 'money';

	if ($credit->get($winduid,$credittype) < $creditvalue) {
		$creditname = $credit->cType[$credittype];
		Showmsg('job_buy_noenough');
	}
	$credit->addLog('topic_buy',array($credittype => -$creditvalue),array(
		'uid'		=> $winduid,
		'username'	=> $windid,
		'ip'		=> $onlineip,
		'tid'		=> $tid,
		'subject'	=> $tpcs['subject']
	));
	$credit->set($winduid,$credittype,-$creditvalue,false);

	$creditvalue>10 && $creditvalue = $creditvalue*0.9;
	$income = $creditvalue * $count;
	if (!$db_sellset['income'] || $income < $db_sellset['income']) {
		$credit->addLog('topic_sell',array($credittype => $creditvalue),array(
			'uid'		=> $tpcs['authorid'],
			'username'	=> $tpcs['author'],
			'ip'		=> $tpcs['userip'],
			'tid'		=> $tid,
			'subject'	=> $tpcs['subject'],
			'buyer'		=> $windid
		));
		$credit->set($tpcs['authorid'],$credittype,$creditvalue,false);
	}
	$credit->runsql();
	$tpcs['buy'] .= ($tpcs['buy'] ? "," : '').$windid;
	$db->update("UPDATE $table SET buy=".pwEscape($tpcs['buy'],false)." WHERE tid=".pwEscape($tid).$where);

	refreshto("read.php?tid=$tid",'operate_success');

} elseif ($action == 'vote') {

	PostCheck();
	require_once(R_P.'require/forum.php');
	$rt = $db->get_one('SELECT t.fid,t.tid,t.postdate,t.lastpost,t.state,t.locked,t.ifcheck,p.* FROM pw_polls p LEFT JOIN pw_threads t ON p.tid=t.tid WHERE p.tid='.pwEscape($tid));
	!$rt && Showmsg('data_error');
	@extract($rt);
	/**
	* 得到版塊基本信息,版塊權限驗證
	*/

	$foruminfo = $db->get_one('SELECT name,f_type,style,password,allowvisit,forumadmin,fupadmin,allowhtm,cms FROM pw_forums WHERE fid='.pwEscape($fid));
	!$foruminfo && Showmsg('data_error');
	wind_forumcheck($foruminfo);

	/*
	*  獲取管理權限
	*/
	if ($groupid == '3' || $groupid == '4' || admincheck($foruminfo['forumadmin'],$foruminfo['fupadmin'],$windid)) {
		$admincheck = 1;
	} else {
		$admincheck = 0;
	}
	/*
	*用戶組權限驗證
	*/
	$_G['allowvote'] == 0 && Showmsg('job_vote_right');

	if (!$admincheck && $locked > 0) {
		Showmsg('job_vote_lock');
	} elseif ($state || ($timelimit && $timestamp - $postdate > $timelimit * 86400)) {
		Showmsg('job_vote_close');
	}
	InitGP(array('voteid','voteaction'),'P');
	$votearray = unserialize($voteopts);

	if (empty($voteid) || !is_array($voteid)) {
		Showmsg('job_vote_sel');
	}
	$voteid = array_unique($voteid);
	$v_sum  = count($voteid);
	if ($multiple && $v_sum > $mostvotes || !$multiple && $v_sum != 1) {
		Showmsg('job_vote_num');
	}
	$sql_1 = '';
	if ($groupid == 'guest') {
		$windid  = $onlineip;
		$winduid = 0;
		$sql_1	 = ' AND username=' . pwEscape($windid);
	}
	$sqlw = 'tid=' . pwEscape($tid) . ' AND uid=' . pwEscape($winduid) . $sql_1;

	$sql_2 = ',voters=voters+1';
	if ($voteaction == 'modify') {
		if ($_G['edittime'] && ($timestamp - $postdate) > $_G['edittime'] * 60) {
			Showmsg('modify_timelimit');
		} elseif (!$modifiable) {
			Showmsg('vote_not_modify');
		}
		$query = $db->query("SELECT vote FROM pw_voter WHERE $sqlw");
		while ($rt = $db->fetch_array($query)) {
			if (isset($votearray[$rt['vote']])) {
				$votearray[$rt['vote']][1]--;
			}
			$sql_2 = '';
		}
		$db->update("DELETE FROM pw_voter WHERE $sqlw");
	} else {
		if ($db->get_value("SELECT COUNT(*) AS SUM FROM pw_voter WHERE $sqlw") > 0) {
			Showmsg('job_havevote');
		}
	}
	$pwSQL = array();
	foreach ($voteid as $k => $id) {
		if (isset($votearray[$id])) {
			$votearray[$id][1]++;
			$pwSQL[] = array($tid, $winduid, $windid, $id, $timestamp);
		}
	}
	$voteopts = serialize($votearray);
	$db->update('UPDATE pw_polls SET voteopts='.pwEscape($voteopts,false)."$sql_2 WHERE tid=" . pwEscape($tid));
	if ($pwSQL) {
		$db->update("INSERT INTO pw_voter (tid,uid,username,vote,time) VALUES " . pwSqlMulti($pwSQL,false));
	}
	if ($locked < 3 && $lastpost < $timestamp) {
		$db->update('UPDATE pw_threads SET lastpost='.pwEscape($timestamp).' WHERE tid='.pwEscape($tid));
	}
	if ($foruminfo['allowhtm'] == 1) {
		require_once(R_P.'require/template.php');
	}
	empty($j_p) && $j_p = "read.php?tid=$tid";
	refreshto($j_p,'operate_success');

} elseif ($action == 'reward') {

	!$winduid && Showmsg('undefined_action');
	InitGP(array('pid','type'));
	$rs = $db->get_one('SELECT r.*,t.fid,t.author,t.authorid,t.ptable,t.subject,t.postdate,t.special,t.state FROM pw_reward r LEFT JOIN pw_threads t USING(tid) WHERE r.tid='.pwEscape($tid));

	if (empty($rs) || $rs['special']<>3 || $rs['state']<>0) {
		Showmsg('illegal_tid');
	}
	$pw_posts = GetPtable($rs['ptable']);
	$authorid = $rs['authorid'];
	$author	  = $rs['author'];
	$fid	  = $rs['fid'];
	$authorid!= $winduid && Showmsg('reward_noright');

	$rt = $db->get_one("SELECT tid,fid,author,authorid,ifreward FROM $pw_posts WHERE pid=".pwEscape($pid));
	if ($rt['tid'] != $tid || $rt['authorid'] == $authorid) {
		Showmsg('illegal_tid');
	}

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

		require_once(R_P.'require/header.php');
		${'sel_'.$type} = 'checked';
		require_once PrintEot('reward');footer();

	} else {

		PostCheck();
		require_once(R_P.'require/credit.php');
		include_once(D_P.'data/bbscache/forum_cache.php');

		if ($type == '1') {
			$db->update("UPDATE pw_threads SET state='1' WHERE tid=".pwEscape($tid));
			$db->update('UPDATE pw_reward SET '.pwSqlSingle(array('author'=>$rt['author'],'pid'=>$pid)).' WHERE tid='.pwEscape($tid));
			$db->update("UPDATE $pw_posts SET ifreward='2' WHERE pid=".pwEscape($pid));
			$credit->addLog('reward_answer',array($rs['cbtype'] => $rs['cbval']),array(
				'uid'		=> $rt['authorid'],
				'username'	=> $rt['author'],
				'ip'		=> $onlineip,
				'fname'		=> $forum[$fid]['name']
			));
			$credit->set($rt['authorid'],$rs['cbtype'],$rs['cbval'],false); /*最佳答案者加分*/
			$credit->addLog('reward_return',array($rs['cbtype'] => $rs['cbval']),array(
				'uid'		=> $authorid,
				'username'	=> $author,
				'ip'		=> $onlineip,
				'fname'		=> $forum[$fid]['name']
			));
			$credit->set($authorid,$rs['cbtype'],$rs['cbval'],false); /*懸賞者返分*/
			return_value($rt['tid'],$rs['catype'],$rs['caval']);
		} else {
			$rt['ifreward'] && Showmsg('reward_helped');
			$rs['caval'] < 1 && Showmsg('reward_help_error');
			$db->update('UPDATE pw_reward SET caval=caval-1 WHERE tid='.pwEscape($rt['tid']));
			$db->update("UPDATE $pw_posts SET ifreward='1' WHERE pid=".pwEscape($pid));
			$credit->addLog('reward_active',array($rs['catype'] => 1),array(
				'uid'		=> $rt['authorid'],
				'username'	=> $rt['author'],
				'ip'		=> $onlineip,
				'fname'		=> $forum[$fid]['name']
			));
			$credit->set($rt['authorid'],$rs['catype'],1,false);  /*熱心助人者加分*/
		}
		$credit->runsql();

		if ($_POST['ifmsg']) {
			require_once(R_P.'require/msg.php');

			if ($type == '1') {
				$affect = $credit->cType[$rs['cbtype']].":".$rs['cbval'];
			} else {
				$affect = $credit->cType[$rs['catype']].":1";
			}
			$msg = array(
				'toUser'		=>$rt['author'],
				'subject'	=> 'reward_title_'.$type,
				'content'	=> 'reward_content_'.$type,
				'other'		=> array(
					'fid'		=> $fid,
					'tid'		=> $rt['tid'],
					'subject'	=> $rs['subject'],
					'postdate'	=> get_date($rs['postdate']),
					'forum'		=> $forum[$fid]['name'],
					'affect'    => $affect,
					'admindate'	=> get_date($timestamp),
					'reason'	=> 'None'
				)
			);
			pwSendMsg($msg);
		}
		refreshto("read.php?tid=$rt[tid]&page=$page",'operate_success');
	}

} elseif ($action == 'endreward') {

	!$winduid && Showmsg('undefined_action');
	require_once(R_P.'require/forum.php');
	InitGP(array('ifmsg','type'));

	$rt = $db->get_one('SELECT r.*,t.fid,t.author,t.authorid,t.postdate,t.fid,t.subject,t.ptable,t.special,t.state,f.forumadmin,f.fupadmin FROM pw_reward r LEFT JOIN pw_threads t ON r.tid=t.tid LEFT JOIN pw_forums f ON t.fid=f.fid WHERE r.tid='.pwEscape($tid));

	if (empty($rt) || $rt['special']<>3 || $rt['state']<>0) {
		Showmsg('illegal_tid');
	}
	$fid	  = $rt['fid'];
	$authorid = $rt['authorid'];
	$author	  = $rt['author'];
	$pw_posts = GetPtable($rt['ptable']);

	if ($groupid!='3' && $groupid!='4' && !admincheck($rt['forumadmin'],$rt['fupadmin'],$windid)) {
		Showmsg('mawhole_right');
	}
	if (empty($_POST['step'])) {

		require_once(R_P.'require/header.php');
		require_once PrintEot('reward');footer();

	} else {

		PostCheck();
		require_once(R_P.'require/credit.php');
		include_once(D_P.'data/bbscache/forum_cache.php');

		if ($type == '1') {
			$db->update("UPDATE pw_threads SET state='2' WHERE tid=".pwEscape($tid));
			$credit->addLog('reward_return',array($rt['cbtype'] => $rt['cbval']*2),array(
				'uid'		=> $authorid,
				'username'	=> $author,
				'ip'		=> $onlineip,
				'fname'		=> $forum[$fid]['name']
			));
			$credit->set($authorid,$rt['cbtype'],$rt['cbval']*2,false);
		} else {
			if ($timestamp < $rt['timelimit'] && $groupid!='3' && $groupid!='4') {
				Showmsg('reward_time_limit');
			}
			$db->update("UPDATE pw_threads SET state='3' WHERE tid=".pwEscape($tid));
		}
		return_value($tid,$rt['catype'],$rt['caval']);

		if ($ifmsg) {
			require_once(R_P.'require/msg.php');

			if ($type == '1') {
				$affect = $credit->cType[$rt['cbtype']].":".($rt['cbval']*2);
			} else {
				$affect = '';
			}
			$msg = array(
				'toUser'	=> $rt['author'],
				'subject'	=> 'endreward_title_'.$type,
				'content'	=> 'endreward_content_'.$type,
				'other'		=> array(
					'manager'	=> $windid,
					'fid'		=> $fid,
					'tid'		=> $tid,
					'subject'	=> $rt['subject'],
					'postdate'	=> get_date($rt['postdate']),
					'forum'		=> $forum[$fid]['name'],
					'affect'    => $affect,
					'admindate'	=> get_date($timestamp),
					'reason'	=> 'None'
				)
			);
			pwSendMsg($msg);
		}
		refreshto("read.php?tid=$tid",'operate_success');
	}
} elseif ($action == 'rewardmsg') {

	!$winduid && Showmsg('undefined_action');
	$rt = $db->get_one('SELECT r.timelimit,t.fid,t.subject,t.authorid,t.postdate,t.special,t.state,f.forumadmin FROM pw_reward r LEFT JOIN pw_threads t ON r.tid=t.tid LEFT JOIN pw_forums f ON t.fid=f.fid WHERE r.tid='.pwEscape($tid));

	if (empty($rt) || $rt['timelimit'] > $timestamp || $rt['special']<>3 || $rt['state']<>0) {
		Showmsg('illegal_tid');
	}
	$rt['authorid'] != $winduid && Showmsg('reward_noright');
	!$rt['forumadmin'] && Showmsg('reward_no_forumadmin');
	require_once(R_P.'require/msg.php');
	include_once(D_P.'data/bbscache/forum_cache.php');

	$admin_db = explode(',',substr($rt['forumadmin'],1,-1));
	$ifsend = $db->get_one("SELECT g.mid FROM pw_msg g LEFT JOIN pw_msgc mc ON g.mid=mc.mid LEFT JOIN pw_members m ON g.touid=m.uid WHERE g.type='rebox' AND g.fromuid=".pwEscape($winduid,false)."AND m.username=".pwEscape($admin_db[0],false)."AND mc.title LIKE '%:$tid)%'");
	$ifsend && Showmsg('reward_have_sendmsg');
	$msg = array(
		'toUser'	=> $admin_db,
		'fromUid'	=> $winduid,
		'fromUser'	=> $windid,
		'subject'	=> 'rewardmsg_title',
		'content'	=> 'rewardmsg_content',
		'other'		=> array(
			'fid'		=> $rt['fid'],
			'tid'		=> $tid,
			'subject'	=> $rt['subject'],
			'postdate'	=> get_date($rt['postdate']),
			'forum'		=> $forum[$rt['fid']]['name'],
			'admindate'	=> get_date($timestamp),
			'reason'	=> "None"
		)
	);
	pwSendMsg($msg);
	Showmsg('rewardmsg_success');

} elseif ($action == 'taglist') {

	!$db_iftag && Showmsg('tag_closed');
	require_once(R_P.'require/header.php');
	$query = $db->query("SELECT * FROM pw_tags WHERE ifhot='0' ORDER BY num DESC LIMIT 100");
	$tagdb = array();
	while ($rt = $db->fetch_array($query)) {
		$tagdb[] = $rt;
	}
	require_once PrintEot('tag');footer();

} elseif ($action == 'tag') {

	!$db_iftag && Showmsg('tag_closed');
	InitGP(array('tagname','page'));
	$metakeyword = strip_tags($tagname);
	$db_metakeyword = $metakeyword;
	$subject = $metakeyword.' - ';

	require_once(R_P.'require/header.php');
	include_once(D_P.'data/bbscache/forum_cache.php');

	$rs = $db->get_one('SELECT tagid,num FROM pw_tags WHERE tagname='.pwEscape($tagname));
	(!is_numeric($page) || $page<1) && $page = 1;
	$limit = pwLimit(($page-1)*$db_readperpage,$db_readperpage);
	$pages = numofpage($rs['num'],$page,ceil($rs['num']/$db_readperpage), "job.php?action=tag&tagname=".rawurlencode($tagname)."&");
	$query = $db->query('SELECT * FROM pw_tagdata tg LEFT JOIN pw_threads t USING(tid) WHERE tg.tagid='.pwEscape($rs['tagid']).$limit);
	$tiddb = array();
	while ($rt = $db->fetch_array($query)) {
		if ($rt['titlefont']) {
			$titledetail=explode("~",$rt['titlefont']);
			if ($titledetail[0]) $rt['subject'] = "<font color=$titledetail[0]>$rt[subject]</font>";
			if ($titledetail[1]) $rt['subject'] = "<b>$rt[subject]</b>";
			if ($titledetail[2]) $rt['subject'] = "<i>$rt[subject]</i>";
			if ($titledetail[3]) $rt['subject'] = "<u>$rt[subject]</u>";
		}
		if ($rt['special']==1) {
			$p_status = $rt['locked'] == 0 ? 'vote' : 'votelock';
		} elseif ($rt['locked']>0) {
			$p_status = $rt['locked'] == 1 ? 'topiclock' : 'topicclose';
		} else {
			$p_status = $rt['replies']>=10 ? 'topichot' : 'topicnew';
		}
		$rt['status'] = "<img src='$imgpath/$stylepath/thread/".$p_status.".gif' border=0>";

		$rt['forumname'] = $forum[$rt['fid']]['name'];
		$rt['postdate'] = get_date($rt['postdate'],"Y-m-d");
		$rt['lastpost'] = get_date($rt['lastpost']);
		$rt['lastposterraw'] = rawurlencode($rt['lastposter']);
		$rt['anonymous'] && $rt['author']!=$windid && $groupid!='3' && $rt['author']=$db_anonymousname;

		$tiddb[] = $rt;
	}
	require_once PrintEot('tag');footer();

} elseif ($action == 'topost') {

	InitGP(array('pid'));
	$page = '';
	if (!is_numeric($tid) || !is_numeric($pid)) {
		Showmsg('data_error');
	}

	$pw_posts = GetPtable('N',$tid);
	$postdb = $db->get_one("SELECT p.postdate,p.ifreward,t.special,f.forumset FROM $pw_posts p LEFT JOIN pw_threads t ON p.tid=t.tid LEFT JOIN pw_forumsextra f ON p.fid=f.fid WHERE p.pid=".pwEscape($pid));
	!$postdb && Showmsg('data_error');
	$postdate  = $postdb['postdate'];
	$forumset  = unserialize($postdb['forumset']);
	$special   = $postdb['special'];
	$ifreward  = $postdb['ifreward'];

	if ($winddb['p_num']) {
		$db_readperpage = $winddb['p_num'];
	} elseif ($forumset['readnum']) {
		$db_readperpage = $forumset['readnum'];
	}

	if ($special) {
		if ($ifreward == 1) {
			$postsnum = $db->get_value("SELECT COUNT(*) FROM $pw_posts WHERE tid=".pwEscape($tid)." AND postdate<=".pwEscape($postdate)." AND ifreward<>'0'");
			$postsnumadd = $db->get_value("SELECT COUNT(*) FROM $pw_posts WHERE tid=".pwEscape($tid)." AND postdate>".pwEscape($postdate)." AND ifreward='2'");
			$postsnum = $postsnum + $postsnumadd;
		} elseif ($ifreward == 2) {
			$page = 1;
		} else {
			$postsnum = $db->get_value("SELECT COUNT(*) FROM $pw_posts WHERE tid=".pwEscape($tid)." AND postdate<=".pwEscape($postdate));
			$postsnumadd = $db->get_value("SELECT COUNT(*) FROM $pw_posts WHERE tid=".pwEscape($tid)." AND postdate>".pwEscape($postdate)." AND ifreward<>'0'");
			$postsnum = $postsnum + $postsnumadd;
		}
	} else {
		$postsnum = $db->get_value("SELECT COUNT(*) FROM $pw_posts WHERE tid=".pwEscape($tid)." AND postdate<=".pwEscape($postdate));
	}
	empty($page) && $page = ceil(($postsnum+1)/$db_readperpage);
	ObHeader("read.php?tid=$tid&page=$page#$pid");

} elseif ($action == 'birth') {

	require_once(R_P.'require/header.php');
	require_once(R_P.'require/birth.php');
	require_once PrintEot('birth');footer();

} elseif ($action == 'erasecookie') {

	checkVerify('loginhash');
	$cookiepre = CookiePre().'_';
	foreach ($_COOKIE as $key => $value) {
		if (strpos($key,$cookiepre)===0) {
			Cookie(substr($key,strlen($cookiepre)),'',0);
		}
	}
	$referer = strpos($pwServer['HTTP_REFERER'],$db_bbsurl)===0 ? $pwServer['HTTP_REFERER'] : $db_bbsurl.'/'.$db_bfn;
	ObHeader($referer);
}

function fseeks($fp,$dbtdsize,$seed) {
	$num = 0;
	while ($break!=1 && $num<$seed) {
		$num++;
		$sdata=fread($fp,$dbtdsize);
		$sdb=explode("\t",$sdata);
		$sdbnext=$sdb[2]*$dbtdsize;
		if ($sdbnext!='NULL') {
			fseek($fp,$sdbnext,SEEK_SET);
		} else {
			$break = 1;
		}
		$todayshow[] = $sdata;
	}
	return $todayshow;
}

function return_value($tid,$rw_a_name,$rw_a_val) {
	global $db,$pw_posts,$authorid,$author,$onlineip,$forum,$fid,$credit;

	if ($rw_a_val < 1) {
		return ;
	}
	$p_a = $u_a = array();
	$query = $db->query("SELECT pid,author,authorid FROM $pw_posts WHERE tid=".pwEscape($tid)." AND ifreward='0' AND authorid!=".pwEscape($authorid)." GROUP BY authorid ORDER BY postdate ASC LIMIT $rw_a_val");
	while ($user = $db->fetch_array($query)) {
		$credit->addLog('reward_active',array($rw_a_name => 1),array(
			'uid'		=> $user['authorid'],
			'username'	=> $user['author'],
			'ip'		=> $onlineip,
			'fname'		=> $forum[$fid]['name']
		));
		$p_a[] = $user['pid'];
		$u_a[] = $user['authorid'];
		$rw_a_val--;
	}
	$p_a && $db->update("UPDATE $pw_posts SET ifreward='1' WHERE pid IN(" . pwImplode($p_a) . ')');
	$u_a && $credit->setus($u_a,array($rw_a_name => 1),false);
	if ($rw_a_val > 0) {
		$credit->addLog('reward_return',array($rw_a_name => $rw_a_val),array(
			'uid'		=> $authorid,
			'username'	=> $author,
			'ip'		=> $onlineip,
			'fname'		=> $forum[$fid]['name']
		));
		$credit->set($authorid,$rw_a_name,$rw_a_val,false);
	}
}

function getuserdb($filename,$offset) {
	global $db_olsize;
	if (!$offset || $offset%($db_olsize+1)!=0) {
		return false;
	} else {
		$fp = fopen($filename,"rb");
		flock($fp,LOCK_SH);
		fseek($fp,$offset);
		$Checkdata = fread($fp,$db_olsize);
		fclose($fp);
		return $Checkdata;
	}
}
?>