<?php
define('THIS_SCRIPT', 'buypost');
require_once 'global.php';
$lang = load_lang($lang, 'buypost' );

$action = strtolower(trim($action));
if ('' === $action) {
	$action = 'default';
}
$gettitle = $stats = $lang['HeaderTitle'][$action];
head();

define('USER_ID', $userid);
if (USER_ID <= 0) {	//	用户未登录
	showmsg($lang['MustLogin']);
}
define('MEMBER_NAME', $membername);

define('ROOT_ID', $id + 0);
define('ROOT_ID_A', $rootid + 0);
define('ANNOUNCE_ID', $replyid + 0);
if (ROOT_ID <= 0) {	//	非法的参数	————	
	showmsg($lang['err.str0']);
	exit;
}
if (ANNOUNCE_ID <= 0) {	//	非法的参数	————	
	showmsg($lang['err.str0']);
	exit;
}
define('TABLE_PREFIX', $dv);

$actionmethod = 'Action_'.$action;
if (function_exists($actionmethod)) {
	$posttable = _getPostTableByTopicid(ROOT_ID_A>0?ROOT_ID_A:ROOT_ID);
	if (false === $posttable) {	//	非法的参数	————	找不到主题所对应的数据表
		showmsg($lang['err.str0']);
		exit;
	} else {
		define('POST_TABLE', $posttable);
	}
	$actionmethod();
} else {	//	非法的参数	————	没有可提供服务的函数
	showmsg($lang['err.str0']);
	exit;
}
footer();

function Action_default()	//	购买帖子
{
	if (ROOT_ID_A <= 0) {	//	非法的参数	————	
		showmsg($lang['err.str0']);
		exit;
	}
	global $db, $lang;
	$rs =& $db->getResultSet("SELECT /*!40001 SQL_CACHE */ body,postbuyuser,username,postuserid,getmoneytype FROM ".POST_TABLE." WHERE announceid='".ANNOUNCE_ID."'");
	if (false === $rs) {	//	您查找的数据暂不存在！
		showmsg($lang['err.str1']);
		exit;
	}
	$postinfo =& $rs[0];
	if ($postinfo['getmoneytype'] > 0) {	//	由于帖子使用了特殊类型，所以不能采用金钱购买帖。
		showmsg($lang['err.str2']);
		exit;
	}
	$strcontent = htmlspecialchars($postinfo['body']);
	if ('' === $strcontent) {
		showmsg($lang['err.str6']);
		exit;
	}
	$postbuyuser = trim($postinfo['postbuyuser']);
	preg_match('/\[USEMONEY\s*=\s*([0-9]+)]((.|\n)*)\[\/USEMONEY]/i', $strcontent, $matchs);
	if (!is_numeric($matchs[1])) {
		$matchs[1] = 0;
	}
	$matchedmoney = $matchs[1] + 0;
	$usermoney = $db->scalar("SELECT userwealth FROM ".TABLE_PREFIX."user WHERE userid='".USER_ID."'") + 0;
	if (MEMBER_NAME == $postinfo['username']) {	//	请不要购买自己发布的帖子！
		js_alert($lang['err.str3']);
	} elseif ($usermoney > $matchedmoney) {
		if ($postbuyuser !== '') {
			if (false !== strpos("|{$postbuyuser}|", '|'.MEMBER_NAME.'|')) {	//	您已购买过此贴！
				js_alert($lang['err.str5']);
			} else {
				$db->query("UPDATE ".TABLE_PREFIX."user SET userwealth=userwealth-'{$matchedmoney}' WHERE userid='".USER_ID."'");
				$db->query("UPDATE ".TABLE_PREFIX."user SET userwealth=userwealth+'{$matchedmoney}' WHERE userid='{$postinfo['postuserid']}'");
				$postinfo['postbuyuser'] .= $db->escape_string('|'.MEMBER_NAME);
				$db->query("UPDATE ".POST_TABLE." SET postbuyuser='{$postinfo['postbuyuser']}' WHERE announceid='".ANNOUNCE_ID."'");
				js_alert($lang['tpl.str0']);	//	购买成功！
			}
		} else {
			$db->query("UPDATE ".TABLE_PREFIX."user SET userwealth=userwealth-'{$matchedmoney}' WHERE userid='".USER_ID."'");
			$db->query("UPDATE ".TABLE_PREFIX."user SET userwealth=userwealth+'{$matchedmoney}' WHERE userid='{$postinfo['postuserid']}'");
			$postinfo['postbuyuser'] .= $db->escape_string('|'.MEMBER_NAME);
			$db->query("UPDATE ".POST_TABLE." SET postbuyuser='{$postinfo['postbuyuser']}' WHERE announceid='".ANNOUNCE_ID."'");
			js_alert($lang['tpl.str0']);	//	购买成功！
		}
	} else {	//	您的余额不足！
		js_alert($lang['err.str4']);
	}
	print '<script type="text/javascript">parent.location.href = "dispbbs.php?boardid='.$GLOBALS['boardid'].'&id='.ROOT_ID_A.'&replyid='.ANNOUNCE_ID.'&star=1&skin=1#'.ANNOUNCE_ID.'";</script>';
}//end function Action_default

function Action_view()	//	查看购买贴子的用户
{
	global $db, $lang;
	$postbuyuser = trim($db->scalar("SELECT postbuyuser FROM ".POST_TABLE." WHERE announceid='".ANNOUNCE_ID."'"));
	require printout('buypost');
}//end function Action_view

function Action_buy()	//	金币购买帖子 
{
	global $db, $lang;
	$rs =& $db->getResultSet("SELECT postbuyuser,username,postuserid,getmoney,getmoneytype,topic FROM ".POST_TABLE." WHERE rootid='".ROOT_ID."' AND parentid=0 AND getmoneytype='3'");
	if (false === $rs) {	//	您查找的数据暂不存在！
		showmsg($lang['err.str1']);
		exit;
	}
	$isupdate = false;
	$postinfo =& $rs[0];
	$getmoney = trim($postinfo['getmoney']);
	if (!is_numeric($getmoney)) {
		$getmoney = 0;
	}
	if ($getmoney < 0) {	//	由于此贴金币设置数据错误，购买失败。
		showmsg($lang['err.str7']);
		exit;
	}
	$postinfo['postbuyuser'] = $postbuyuser = trim($postinfo['postbuyuser']);
	$tousername = trim($postinfo['username']);
	$postuserid = trim($postinfo['postuserid']);
	$getmoneytype = trim($postinfo['getmoneytype']);
	$topic = trim($postinfo['topic']);
	if ($userid != $postuserid AND $getmoney != 0 AND false !== strpos($postbuyuser, '|||$PayMoney|||') AND false === strpos($postbuyuser, '|||'.MEMBER_NAME.'|||')) {
		$strtmp = explode('|||', $postbuyuser, 2);
		$buymoneyinfo = explode('@@@', $strtmp[0]);
		$buymoneyinfo[1] += 0;
		$buymoneyinfo[2] += 0;
		//购买数量限制(设置为“-1”则不限制)
		if (0 == $buymoneyinfo[1]) {	//	本帖子已售完。
			showmsg($lang['err.str9']);
			exit;
		} elseif ($buymoneyinfo[1] > 0) {
			$buymoneyinfo[1] -= 1;
		}
		/*
		//Start 当VIP不需要付费时将GetMoney清为0
		//End 当VIP不需要付费时将GetMoney清为0
		//*/
		//Start 可购买用户名单限制(每个用户名用英文逗号“,”分隔符分开，注意区分大小写)
			$buymoneyinfo[3] = trim($buymoneyinfo[3]);
			if ($buymoneyinfo[3] !== '') {
				if (false === strpos(",{$buymoneyinfo[3]},", ','.MEMBER_NAME.',')) {	//	购买失败，非作者指定的用户不能购买该帖。
					showmsg($lang['err.str10']);
					exit;
				}
			}
		//End 可购买用户名单限制(每个用户名用英文逗号“,”分隔符分开，注意区分大小写)
		global $userinfo;
		if ($getmoney > $userinfo['usermoney']) {	//	你的用户金币不足，购买该帖失败。
			showmsg($lang['err.str11']);
			exit;
		}
		$buymoneyinfo[0] = $buymoneyinfo[0] + $getmoney;
		$strtmp[0] = "{$buymoneyinfo[0]}@@@{$buymoneyinfo[1]}@@@{$buymoneyinfo[2]}@@@{$buymoneyinfo[3]}";
		$postinfo['postbuyuser'] = $db->escape_string("{$strtmp[0]}|||{$strtmp[1]}".MEMBER_NAME."|||");
		$db->query("UPDATE ".POST_TABLE." SET postbuyuser='{$postinfo['postbuyuser']}' WHERE rootid='".ROOT_ID."' AND parentid=0 AND getmoneytype='3'");
		$db->query("UPDATE ".TABLE_PREFIX."user SET usermoney=usermoney-'".$getmoney."' WHERE userid='".USER_ID."'");
		$db->query("UPDATE ".TABLE_PREFIX."user SET usermoney=usermoney+'".$getmoney."' WHERE userid='{$postinfo['postuserid']}'");
		$isupdate = true;
	} else {	//	你不能重复购买或者不能购买自已的金币帖子。
		showmsg($lang['err.str8']);
		exit;
	}
	if (true === $isupdate) {
		showmsg(str_replace(array('{$TPL_BOARD_ID}', '{$TPL_ID}', '{$TPL_TOPIC}', '{$TPL_GETMONEY}', '{$TPL_TOUSERNAME}'), array($GLOBALS['boardid'], ROOT_ID, $topic, $getmoney, $tousername), $lang['tpl.str1']), 1, $_SERVER['HTTP_REFERER']);
		exit;
	}
}//end function Action_buy

function Action_send()	//	赠送金币
{
	global $db, $lang;
	$rs =& $db->getResultSet("SELECT postbuyuser,getmoney,topic,announceid FROM ".POST_TABLE." WHERE rootid='".ROOT_ID."' AND parentid='0' AND getmoneytype='1' AND postuserid='".USER_ID."'", array('pageSize'=>1));
	if (false === $rs) {	//	您查找的数据暂不存在！
		showmsg($lang['err.str1']);
		exit;
	}
	$postinfo =& $rs[0];
	$postbuyuser = $postinfo['postbuyuser'] = trim($postinfo['postbuyuser']);
	$getmoney = trim($postinfo['getmoney']);
	$topic = trim($postinfo['topic']);
	$toannounceid = trim($postinfo['announceid']);
	$tousername = trim($GLOBALS['UserName']);
	$tmpstr = explode('|||', $postbuyuser, 2);
	if (!is_numeric($tmpstr[0])) {
		$tmpstr[0] = 0;
	}
	if (false !== strpos($postbuyuser, "|||{$tousername},")) {
		$issenduser = $lang['tpl.str4'];
	} else {
		$issenduser = $lang['tpl.str5'];
	}
	if ('savemoney' === strtolower(trim($_POST['doaction']))) {
		if (!ChkPost()) {	//	您提交的数据不合法，请不要从外部提交发言。
			showmsg($lang['ChkPostError']);
			exit;
		}
		$sendmoney = trim($_POST['sendmoney']);
		if (!is_numeric($sendmoney)) {	//	非法的参数。
			showmsg($lang['err.str0']);
			exit;
		} else {
			$sendmoney  += 0;
		}
		if ($tmpstr[0] < 0) {	//	赠送的金币数太少或已超出了剩余金币数。
			showmsg($lang['err.str12']);
			exit;
		}
		$tmpstr[0] += $sendmoney;
		if ($remainmoney OR $sendmoney < 1 OR $tmpstr[0]>$getmoney) {	//	赠送的金币数太少或已超出了剩余金币数。
			showmsg($lang['err.str12']);
			exit;
		}
		if ($sendmoney < 1 OR $tmpstr[0] > $getmoney) {	//	赠送的金币数太少或已超出了剩余金币数。
			showmsg($lang['err.str13']);
			exit;
		}
		//Start 读取回复用户信息，更新GetMoney数值
			$rs2 =& $db->getResultSet("SELECT username,postuserid,getmoney FROM ".POST_TABLE." WHERE announceid='".ANNOUNCE_ID."'", array('pageSize'=>1));
			if (false === $rs2) {	//	您查找的数据暂不存在！
				showmsg($lang['err.str1']);
				exit;
			} else {
				$destpostinfo =& $rs2[0];
				$tousername = trim($destpostinfo['username']);
				$postuserid = trim($destpostinfo['postuserid']);
				if ($postuserid == USER_ID) {	//	赠送金币帖不能对自已赠送金币。
					showmsg($lang['err.str14']);
					exit;
				}
				$destpostinfo['getmoney'] += $sendmoney;
				$db->query("UPDATE ".POST_TABLE." SET getmoney='{$destpostinfo['getmoney']}' WHERE announceid='".ANNOUNCE_ID."'");
			}
		//End 读取回复用户信息，更新GetMoney数值
		$tmpstr[1] = "{$tmpstr[1]}|||{$tousername},{$sendmoney}";
		$postbuyuser = "{$tmpstr[0]}|||{$tmpstr[1]}";
		//更新目标用户，增加金币
			$db->query("UPDATE ".TABLE_PREFIX."user SET usermoney=usermoney+'{$sendmoney}' WHERE userid='{$postuserid}'");
		//更新分表中主题行PostBuyUser数据
			$db->query("UPDATE ".POST_TABLE." SET postbuyuser='".$db->escape_string($postbuyuser)."' WHERE announceid='{$toannounceid}'");
		showmsg(str_replace(array('{$TPL_BOARD_ID}', '{$TPL_ID}', '{$TPL_REPLY_ID}', '{$TPL_TOPIC}', '{$TPL_TOUSERNAME}', '{$TPL_SENDMONEY}', '{$TPL_MONEY}'), array($GLOBALS['boardid'], ROOT_ID, ANNOUNCE_ID, $topic, $tousername, $sendmoney, ($getmoney-$tmpstr[0])), $lang['tpl.str6']), 1, $_SERVER['HTTP_REFERER']);
	} else {
		require printout('buypost');
	}
}//end function Action_send

function Action_close()	//	结帖操作
{
	global $db, $lang, $boardmaster, $userinfo;
	$rs =& $db->getResultSet("SELECT postbuyuser,getmoney,topic,announceid FROM ".POST_TABLE." WHERE rootid='".ROOT_ID."' AND parentid='0' AND getmoneytype='1' ".(true !== $boardmaster ? " AND postuserid='".USER_ID."' ":""), array('pageSize'=>1));
	if (false === $rs) {	//	您查找的数据暂不存在！
		showmsg($lang['err.str1']);
		exit;
	}
	$postinfo =& $rs[0];
	$postbuyuser = $postinfo['postbuyuser'] = trim($postinfo['postbuyuser']);
	$getmoney = trim($postinfo['getmoney']);
	$topic = trim($postinfo['topic']);
	$toannounceid = trim($postinfo['announceid']);
	$tmpstr = explode('|||', $postbuyuser, 2);
	if ('saveclose' === strtolower(trim($_POST['doaction']))) {
		if (!ChkPost()) {	//	您提交的数据不合法，请不要从外部提交发言。
			showmsg($lang['ChkPostError']);
			exit;
		}
		$sendmoney = $getmoney - $tmpstr[0];
		if ($sendmoney < 0) {
			$sendmoney = 0;
		}
		//Start 更新用户，返还金币
			if ($sendmoney > 0) {
				$db->query("UPDATE ".TABLE_PREFIX."user SET usermoney=usermoney+'{$sendmoney}' WHERE userid='".USER_ID."'");
				$userinfo['usermoney'] += $sendmoney;	//	修改用户金币数量
			}
		//End 更新用户，返还金币
		//Start 更新帖子类型
			$db->query("UPDATE ".TABLE_PREFIX."topic SET getmoneytype='5' WHERE topicid='".ROOT_ID."'");
			$db->query("UPDATE ".POST_TABLE." SET getmoneytype='5' WHERE announceid='{$toannounceid}'");
		//End 更新帖子类型
		$insertlogmsg = str_replace(array('{$TPL_TOPIC}', '$TPL_SENDMONEY}'), array($topic, $sendmoney), $lang['tpl.str2']);
		$db->query("INSERT INTO ".TABLE_PREFIX."log(l_AnnounceID, l_BoardID, l_touser, l_username, l_content, l_ip, l_type) VALUES('".ROOT_ID."', '{$GLOBALS['boardi']}', '".MEMBER_NAME."', '".MEMBER_NAME."', '".$db->escape_string($insertlogmsg)."', '".$db->escape_string($GLOBALS['usertrueip'])."', '5')");
		showmsg(str_replace(array('{$TPL_BOARD_ID}', '{$TPL_ID}', '{$TPL_TOPIC}', '{$TPL_SENDMONEY}'), array($GLOBALS['boardid'], ROOT_ID, $topic, $sendmoney), $lang['tpl.str3']), 1, $_SERVER['HTTP_REFERER']);
		exit;
	} else {
		require printout('buypost');
	}
}//end function Action_close

function _getPostTableByTopicid($topicid)
{
	if ($topicid <= 0) {
		return false;
	}
	static $posttable;
	if (empty($posttable)) {
		global $db;
		$posttable = $db->scalar("SELECT /*!40001 SQL_CACHE */ posttable FROM ".TABLE_PREFIX."topic WHERE topicid='".$topicid."'");
	}
	return $posttable;
}//end function _getPostTableByTopicid

function escapejscode($jscode)
{
	return str_replace(array('\\', '"', "\r", "\n"), array('\\\\', '\\"', '\r', '\n'), $jscode);
}//end function escapejscode
function js_alert($message)
{
	print '<script type="text/javascript">alert("'.escapejscode($message).'");</script>';
}//end function js_alert
?>