<?php
!function_exists('readover') && exit('Forbidden');
require_once(D_P.'data/bbscache/level.php');
require_once(R_P.'require/updateforum.php');
require_once(R_P.'require/tool.php');

!$db_toolifopen && Showmsg('toolcenter_close');
!$windid && Showmsg('not_login');

require_once(R_P.'require/credit.php');

$userdb = array(
	'money'		=> $winddb['money'],
	'rvrc'		=> $userrvrc,
	'credit'	=> $winddb['credit'],
	'currency'	=> $winddb['currency']
);
foreach ($credit->get($winduid,'CUSTOM') as $key => $value) {
	$userdb[$key] = $value;
}
InitGP(array('action'));

if (empty($action)) {

	$query = $db->query("SELECT * FROM pw_tools WHERE state=1 ORDER BY vieworder");
	while($rt = $db->fetch_array($query)){
		$rt['descrip'] = substrs($rt['descrip'],30);
		!$rt['creditype'] && $rt['creditype'] = 'currency';
		$tooldb[] = $rt;
	}
	require_once PrintHack('index');footer();

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

	$query = $db->query("SELECT u.*,t.name,t.price,t.creditype,t.stock FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE u.uid=".pwEscape($winduid));
	while ($rt = $db->fetch_array($query)) {
		!$rt['creditype'] && $rt['creditype'] = 'currency';
		$tooldb[] = $rt;
	}
	require_once PrintHack('index');footer();

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

	!$db_allowtrade && Showmsg('trade_close');
	InitGP(array('uid'));
	$sqladd = $owner = '';
	if (is_numeric($uid)) {
		$rt = $db->get_one("SELECT username FROM pw_members WHERE uid=".pwEscape($uid));
		if (!$rt) {
			$errorname = $uid;
			Showmsg('user_not_exists');
		}
		$sqladd = "AND u.uid=".pwEscape($uid);
		$owner  = $rt['username'];
	}
	$query = $db->query("SELECT u.*,t.name,t.descrip,t.logo,t.creditype,m.username FROM pw_usertool u LEFT JOIN pw_members m USING(uid) LEFT JOIN pw_tools t ON t.id=u.toolid WHERE sellnums!=0 $sqladd");
	while ($rt = $db->fetch_array($query)) {
		$rt['descrip'] = substrs($rt['descrip'],45);
		!$rt['creditype'] && $rt['creditype'] = 'currency';
		$tooldb[] = $rt;
	}
	require_once PrintHack('index');footer();

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

	!$db_allowtrade && Showmsg('trade_close');
	InitGP(array('id'));

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

		$rt = $db->get_one("SELECT u.*,t.name,t.price,t.creditype,t.logo FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE uid='$winduid' AND toolid=".pwEscape($id));
		!$rt && Showmsg('undefined_action');
		$rt['nums'] == 0 && Showmsg('unenough_toolnum');
		!$rt['creditype'] && $rt['creditype'] = 'currency';
		require_once PrintHack('index');footer();

	} else {

		$rt = $db->get_one("SELECT u.*,t.name FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id));
		if ($rt) {
			InitGP(array('nums','price'),'P');
			$nums   = (int)$nums;
			$price  = (int)$price;
			$price <= 0 && Showmsg('illegal_nums');
			$nums  <= 0 && Showmsg('illegal_nums');
			$rt['nums'] < $nums && Showmsg('unenough_nums');

			$db->update("UPDATE pw_usertool SET nums=nums-".pwEscape($nums).",sellnums=sellnums+".pwEscape($nums).",sellprice=".pwEscape($price)."WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id));
			$logdata = array(
				'type'		=>	'sell',
				'nums'		=>	$nums,
				'money'		=>	$price,
				'descrip'	=>	'sell_descrip',
				'uid'		=>	$winduid,
				'username'	=>	$windid,
				'ip'		=>	$onlineip,
				'time'		=>	$timestamp,
				'toolname'	=>	$rt['name'],
				'from'		=>	'',
			);
			writetoollog($logdata);
			refreshto("hack.php?H_name=toolcenter&action=mytool",'operate_success');
		} else {
			Showmsg('undefined_action');
		}
	}
} elseif ($action == 'buyuser') {

	InitGP(array('id','uid'));

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

		$rt = $db->get_one("SELECT * FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE u.toolid=".pwEscape($id)."AND u.uid=".pwEscape($uid));
		if ($rt) {
			$condition = unserialize($rt['conditions']);
			$groupids  = $condition['group'];
			$fids      = $condition['forum'];

			foreach ($condition['credit'] as $key => $value) {
				$key == 'rvrc' && $value /= 10;
				$condition['credit'][$key] = (int)$value;
			}
			$usergroup = "";
			$num = 0;
			foreach ($ltitle as $key => $value) {
				if ($key != 1 && $key != 2) {
					if (strpos($groupids,','.$key.',') !== false) {
						$num++;
						$htm_tr = $num%5 == 0 ?  '</tr><tr>' : '';
						$usergroup .=" <td width='20%'>$value</td>$htm_tr";
					}
				}
			}
			$num        = 0;
			$forumcheck = "";
			$sqladd     = " AND f_type!='hidden' AND cms='0'";
			$query      = $db->query("SELECT fid,name FROM pw_forums WHERE type<>'category' AND cms='0'");
			while ($fm = $db->fetch_array($query)) {
				if (strpos($fids,','.$fm['fid'].',') !== false) {
					$num ++;
					$htm_tr = $num % 5 == 0 ? '</tr><tr>' : '';
					$forumcheck .= "<td width='20%'>$fm[name]</td>$htm_tr";
				}
			}
			!$rt['creditype'] && $rt['creditype'] = 'currency';
			require_once PrintHack('index');footer();
		} else {
			Showmsg('undefined_action');
		}
	} else{

		$toolinfo = $db->get_one("SELECT u.*,t.name,t.creditype,m.username FROM pw_usertool u LEFT JOIN pw_members m USING(uid) LEFT JOIN pw_tools t ON t.id=u.toolid WHERE u.toolid=".pwEscape($id)."AND u.uid=".pwEscape($uid));

		$nums  = (int)GetGP('nums');
		$nums <= 0 && Showmsg('illegal_nums');
		$price = $toolinfo['sellprice'] * $nums;
		$toolinfo['sellnums'] < $nums && Showmsg('unenough_sellnum');

		if ($winduid == $toolinfo['uid']) {
			$logdata = array(
				'type'		=>	'buy',
				'nums'		=>	$nums,
				'money'		=>	$price,
				'descrip'	=>	'buyself_descrip',
				'uid'		=>	$winduid,
				'username'	=>	$windid,
				'ip'		=>	$onlineip,
				'time'		=>	$timestamp,
				'toolname'	=>	$toolinfo['name'],
				'from'		=>	'',
			);
			writetoollog($logdata);
			$db->update("UPDATE pw_usertool SET nums=nums+".pwEscape($nums).",sellnums=sellnums-".pwEscape($nums)."WHERE uid=".pwEscape($toolinfo['uid'],false)."AND toolid=".pwEscape($id));
		} else {
			/*
			$lockfile = D_P.'data/bbscache/lock_buyusertool.txt';
			$fp = fopen($lockfile,'wb+');
			flock($fp,LOCK_EX);
			*/
			if (procLock('tool_buyuser',$winduid)) {

				!$toolinfo['creditype'] && $toolinfo['creditype'] = 'currency';
				if ($credit->get($winduid, $toolinfo['creditype']) < $price) {
					$creditname = $credit->cType[$toolinfo['creditype']];
					Showmsg('unenough_money');
				}
				$credit->addLog('hack_toolubuy',array($toolinfo['creditype'] => -$price),array(
					'uid'		=> $winduid,
					'username'	=> $windid,
					'ip'		=> $onlineip,
					'seller'	=> $toolinfo['username'],
					'nums'		=> $nums,
					'toolname'	=> $toolinfo['name']
				));
				$credit->addLog('hack_toolsell',array($toolinfo['creditype'] => $price),array(
					'uid'		=> $toolinfo['uid'],
					'username'	=> $toolinfo['username'],
					'ip'		=> $onlineip,
					'buyer'		=> $windid,
					'toolname'	=> $toolinfo['name']
				));
				$credit->set($winduid,$toolinfo['creditype'],-$price,false);
				$credit->set($toolinfo['uid'],$toolinfo['creditype'],$price,false);
				$credit->runsql();

				$db->pw_update(
					"SELECT uid FROM pw_usertool WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id),
					"UPDATE pw_usertool SET nums=nums+".pwEscape($nums)."WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id),
					"INSERT INTO pw_usertool SET ".pwSqlSingle(array('nums'=>$nums,'uid'=>$winduid,'toolid'=>$id))
				);
				//fclose($fp);
				$db->update("UPDATE pw_usertool SET sellnums=sellnums-".pwEscape($nums)."WHERE uid=".pwEscape($toolinfo['uid'],false)."AND toolid=".pwEscape($id));

				$logdata = array(
					'type'		=> 'buy',
					'nums'		=> $nums,
					'money'		=> $price,
					'descrip'	=> 'buyuser_descrip',
					'uid'		=> $winduid,
					'username'	=> $windid,
					'ip'		=> $onlineip,
					'time'		=> $timestamp,
					'toolname'	=> $toolinfo['name'],
					'from'		=> $toolinfo['username'],
				);
				writetoollog($logdata);

				procUnLock('tool_buyuser',$winduid);
			}
		}
		refreshto("hack.php?H_name=toolcenter&action=user",'operate_success');
	}
} elseif ($action == 'buy') {

	InitGP(array('id'));

	if (!$_POST['step']) {
		$rt = $db->get_one("SELECT * FROM pw_tools WHERE id=".pwEscape($id));
		if ($rt['state'] == 0) {
			Showmsg('tool_buyclose');
		}
		if ($rt) {
			$rt['stock'] == 0 && Showmsg('no_stock');
			$condition = unserialize($rt['conditions']);
			$groupids  = $condition['group'];
			$fids      = $condition['forum'];

			foreach($condition[credit] as $key => $value){
				$key == 'rvrc' && $value /= 10;
				$condition['credit'][$key] = (int)$value;
			}
			$usergroup = "";
			$num = 0;
			foreach($ltitle as $key=>$value){
				if($key != 1 && $key != 2){
					if(strpos($groupids,','.$key.',') !== false){
						$num ++;
						$htm_tr = $num%5 == 0 ?  '</tr><tr>' : '';
						$usergroup .= "<td width='20%'>$value</td>$htm_tr";
					}
				}
			}
			$num        = 0;
			$forumcheck = "<table cellspacing='0' cellpadding='0' border='0' width='100%' align='center'><tr>";
			$sqladd     = " AND f_type!='hidden' AND cms='0'";
			$query      = $db->query("SELECT fid,name FROM pw_forums WHERE type<>'category' AND cms='0'");
			while($fm = $db->fetch_array($query)){
				if(strpos($fids,','.$fm['fid'].',') !== false){
					$num ++;
					$htm_tr = $num % 5 == 0 ? '</tr><tr>' : '';
					$forumcheck .= "<td width='20%'>$fm[name]</td>$htm_tr";
				}
			}
			$forumcheck.="</tr></table>";
			!$rt['creditype'] && $rt['creditype'] = 'currency';
			require_once PrintHack('index');footer();
		} else {
			Showmsg('undefined_action');
		}
	} else {
		/*
		$lockfile = D_P.'data/bbscache/lock_buytool.txt';
		$fp = fopen($lockfile,'wb+');
		flock($fp,LOCK_EX);
		*/
		if (procLock('tool_buy',$winduid)) {

			$toolinfo = $db->get_one("SELECT * FROM pw_tools WHERE id=".pwEscape($id));
			$nums  = (int)GetGP('nums');
			$nums <= 0 && Showmsg('illegal_nums');
			$price = $toolinfo['price'] * $nums;
			$toolinfo['stock'] < $nums && Showmsg('unenough_stock');
			!$toolinfo['creditype'] && $toolinfo['creditype'] = 'currency';
			if ($credit->get($winduid, $toolinfo['creditype']) < $price) {
				$creditname = $credit->cType[$toolinfo['creditype']];
				Showmsg('unenough_money');
			}
			$credit->addLog('hack_toolbuy',array($toolinfo['creditype'] => -$price),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'nums'		=> $nums,
				'toolname'	=> $toolinfo['name']
			));
			$credit->set($winduid,$toolinfo['creditype'],-$price);

			$db->update("UPDATE pw_tools SET stock=stock-".pwEscape($nums)."WHERE id=".pwEscape($id));
			$db->pw_update(
				"SELECT uid FROM pw_usertool WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id),
				"UPDATE pw_usertool SET nums=nums+".pwEscape($nums)."WHERE uid=".pwEscape($winduid)."AND toolid=".pwEscape($id),
				"INSERT INTO pw_usertool SET ".pwSqlSingle(array('nums'=>$nums,'uid'=>$winduid,'toolid'=>$id))
			);

			fclose($fp);
			$logdata = array(
				'type'		=>	'buy',
				'nums'		=>	$nums,
				'money'		=>	$price,
				'descrip'	=>	'buy_descrip',
				'uid'		=>	$winduid,
				'username'	=>	$windid,
				'ip'		=>	$onlineip,
				'time'		=>	$timestamp,
				'toolname'	=>	$toolinfo['name'],
				'from'		=>	'',
			);
			writetoollog($logdata);

			procUnLock('tool_buy',$winduid);
		}
		refreshto("hack.php?H_name=toolcenter",'operate_success');
	}
} elseif ($action == 'use' || $action=='ajax') {

	$toolid = (int)GetGP('toolid');
	if (!$toolid) {
		$tooldb = array();
		$query  = $db->query("SELECT * FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE u.uid=".pwEscape($winduid)."ORDER BY vieworder");
		while ($rt = $db->fetch_array($query)) {
			$rt['descrip'] = substrs($rt['descrip'],45);
			$tooldb[] = $rt;
		}
		if (!$tooldb) {
			Showmsg('no_tool');
		}
		require_once PrintHack('index');footer();
	}
	$tooldb = $db->get_one("SELECT u.nums,t.name,t.filename,t.state,t.type,t.conditions FROM pw_usertool u LEFT JOIN pw_tools t ON t.id=u.toolid WHERE u.uid=".pwEscape($winduid)."AND u.toolid=".pwEscape($toolid));

	!$db_toolifopen && Showmsg('toolcenter_close');
	if (!$tooldb || $tooldb['nums'] <= 0) {
		Showmsg('nothistool');
	}
	if ($tooldb['type'] == 1) {
		!$tid && Showmsg('illegal_tid');
		$condition = unserialize($tooldb['conditions']);
		$tpcdb = $db->get_one("SELECT fid,subject,authorid,topped,toolfield FROM pw_threads WHERE tid=".pwEscape($tid));
		if(!$tpcdb){
			Showmsg('illegal_tid');
		}
		if($condition['forum'] && strpos($condition['forum'],",$tpcdb[fid],") === false){
			Showmsg('tool_forumlimit');
		}
	}
	CheckUserTool($winduid,$tooldb);

	if (file_exists(H_P.'require/'.$tooldb['filename'].'.php')) {
		require_once Pcv(H_P.'require/'.$tooldb['filename'].'.php');
	} else {
		Showmsg('tooluse_not_finished');
	}
}
?>