<?
include("includes/config.php");
include("includes/functions.php");
session_start();
include("includes/session.php");
$Session = new Session();
$Session->read();
foreach($_GET as $var => $val) {
	$get[$var] = @stripslashes(trim($val));
	$get_safe[$var] = @mysql_escape_string($get[$var]);
}
foreach($_POST as $var => $val) {
	$post[$var] = @stripslashes(trim($val));
	$post_safe[$var] = @mysql_escape_string($post[$var]);
}
$user_ip = GetIP();
if (isset($_COOKIE["sess_key"]) && !isset($_SESSION["user"]["id"])) {
	$GetLogInfo = mysql_query("SELECT user_id from sessions where sess_key = '".addslashes($_COOKIE["sess_key"])."'") or print(mysql_error() . " " . __FILE__ . " #" . __LINE__);
	if(mysql_num_rows($GetLogInfo) == 1) {
		$_SESSION["user"]["id"] = mysql_result($GetLogInfo, 0);
	}
	@mysql_free_result($GetLogInfo);
}
if(isset($_SESSION["user"]) || $_SESSION["user"]["id"] != ""){
	$loggedin = true;
	$sess_user_id = $_SESSION["user"]["id"];
	$sess_user_status = $_SESSION["user"]["status"];
	$CharacterInfo = GetCharacterInfo($sess_user_id);
	$WeaponInfo = GetWeaponInfo($CharacterInfo);
	$ArmourInfo = GetArmourInfo($CharacterInfo);
	$strMod = ceil($CharacterInfo['strength'] / 2);
}
$population = mysql_query("SELECT COUNT(id) from users WHERE status > 0") or print(mysql_error() . " " . __FILE__ . " #" . __LINE__);
$population = mysql_result($population, 0);
$online = mysql_query("SELECT COUNT(id) FROM sessions WHERE (UNIX_TIMESTAMP() - last_update) < 7200") or print(mysql_error() . " " . __FILE__ . " #" . __LINE__);
$online = mysql_result($online, 0);
$page = $_GET["page"];
$page = str_replace("../", "", $page); // no backtracking!
$page = str_replace("./", "", $page); // Stop it!!
$page = str_replace("/", "", $page); // Im gonna hurt you..
$page = str_replace(substr(strrchr($page,"."),1), "",$page); // remove extention... no page.html or anyhting fruity like .zip
if(file_exists("./pages/$page.php")){
	if(file_exists("./includes/{$page}_functions.php")){
		include("./includes/{$page}_functions.php");
	}
}
if($loggedin){
	//get alerts & messages
	$AQ = mysql_query("SELECT COUNT(id) FROM alerts WHERE receiver_id = '{$CharacterInfo['id']}' AND seen = '0'") or print(mysql_error() . " " . __FILE__ . " #" . __LINE__);
	if(mysql_result($AQ, 0) > 0){
		$Alert = true;
	}
	
	$MQ = mysql_query("SELECT COUNT(id) FROM messages WHERE receiver_id = '{$CharacterInfo['id']}' AND seen = '0'") or print(mysql_error() . " " . __FILE__ . " #" . __LINE__);
	if(mysql_result($MQ, 0) > 0){
		$Message = true;
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Free browser based MMRPG. Only a registration is required! Kingsleyville" />
<meta name="keywords" content="online gaming,kingsleyville,Kingsley Muir,kingsley,ville" />
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<title>Welcome to Kingsleyville</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="includes/jquery.js" type="text/javascript"></script>
<?
$dh = opendir("includes");
$JSFiles = array();
while (($file = readdir($dh)) !== false) {
	if(substr($file, 0, 7) == "jquery." && $file != "jquery.js") {
		$JSFiles[] = $file;
	}
}
closedir($dh);
sort($JSFiles);
foreach($JSFiles as $value) {
	print "<script type=\"text/javascript\" src=\"includes/$value\"></script>\n";
}
?>
<script src="includes/javascripts.js" type="text/javascript"></script>
<script type="text/javascript">
var timeHour	= <?=date("g"); ?>;
var timeMin		= <?=date("i"); ?>;
var timeSec		= <?=date("s"); ?>;
var timeAmPm	= "<?=date("a"); ?>";
window.setInterval( 'changeTime()', 1000 );
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
var m = new Image();
m.src = "images/icon_load_wb.gif";
</script>
</head>
<body>
<div id="container">
        <h1>Kingsleyville</h1>
        <div id="buttons">
		<div id="kst"> <?=date("g:i:s a");?> KST </div>
        <a href="?page=home"><img src="images/home.jpg" alt="Home" /></a>
        </div>
<div id="navcont">
    <ul id="nav">
		<li><a href="?page=home">Home</a></li>
		<?
		if($sess_user_status == 2){
			print "<li><a href=\"?page=admin\">Admin</a></li>";
		}
		?>
        <li><a href="?page=job">Job Info</a></li>
        <li><a href="?page=usercp">UserCP</a></li>
        <li><a href="?page=games">Games</a></li>
        <li><a href="?page=submit_bug">Submit Bug</a></li>
        <li><a href="?page=training">Training</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</div>    
    <div id="info">
        <div id="whatisthis">
			<?
			if($_SESSION["user"]["id"] != ""){
				?>
				<table cellpadding="5" cellspacing="0">
					<tr>
						<td colspan="4" align="center"><b>Hello, <?=$CharacterInfo["name"];?>!</b></td>
					</tr>
					<tr>
						<td>Weapon:</td>
						<td style="border-right: 1px solid #000;"><?=$WeaponInfo["name"];?><!-- (<?=$WeaponInfo["min_damage"];?>-<?=($WeaponInfo["max_damage"] + $strMod);?>)--></td>
						<td>Armour:</td>
						<td><?=$ArmourInfo["name"];?><!-- (<?=$ArmourInfo["value"];?>-<?=($ArmourInfo["value"] + $strMod);?>)--></td>
					</tr>
					<tr>
						<td>Hit Points:</td>
						<td style="border-right: 1px solid #000;"><?=$CharacterInfo["now_hp"]."/".$CharacterInfo["max_hp"];?></td>
						<td>Level: </td>
						<td><?=$CharacterInfo['level'];?></td>
					</tr>
					<tr>
						<td>Exp: </td>
						<td style="border-right: 1px solid #000;"><?=$CharacterInfo['exp'];?></td>
						<td>Money:</td>
						<td id="money"><?=format($CharacterInfo['money']);?> KD</td>
					</tr>
					<tr>
						<td colspan="4" align="center"><a href="?page=logout">Logout</a></td>
					</tr>
				</table>
				<?
			} else {
				?>
				<h2>Welcome, Guest</h2>
				<p><a href="?page=register">Register</a><br />
				<a href="?page=login">Login</a></p>
				<?
			}
			?>
    	</div>
            <ul id="templatetypes">
			<li>Site Menu</li>
            <li><a href="?page=bank">Bank</a></li>
            <li><a href="?page=stock_market">Stock Market</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            </ul>
            <ul id="supportlinks">
			<li>User Menu</li>
            <li><a href="?page=hospital">Hospital</a></li>
            <li><a href="?page=stats">Stats</a></li>
            <li><a href="?page=inventory">Inventory</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            </ul>
    </div>
        <div id="content_main">
			<center>
           	<?
			$banned = false;
			if($loggedin){
				$banned = mysql_query("SELECT status FROM users where id = '$sess_user_id'");
				$banned = mysql_result($banned, 0);
				if ($banned == -1){
					$banned = true;
				} else {
					$banned = false;
				}
			}
			if($loggedin) {
				#	Check if training
				$training = false;
				$sqlTraining = mysql_query("SELECT id, DATE_FORMAT(time_expires, '%d/%c/%Y %r') as f_time_expires, UNIX_TIMESTAMP(time_expires) as u_time_expires FROM training WHERE user_id = '{$CharacterInfo['id']}'");
				if(mysql_num_rows($sqlTraining) == 1) {
					if(time() < mysql_result($sqlTraining, 0, 'u_time_expires')) {		// Still training
						print "Sorry! It looks like you're still training for another " . ceil((mysql_result($sqlTraining, 0, 'u_time_expires') - time()) / 60) . " minute(s)<br />";
						$training = true;
					} else {	// training is finished
						#	calculate result of training
						$min = floor($CharacterInfo['level'] * 150);
						$max = $min * 2;
						$xp = mt_rand($min, $max);
						print "You gained " . format($xp) . " exp from your training.<Br />";
						addExp($CharacterInfo['id'], $xp);
						mysql_query("DELETE FROM training WHERE id = '" . mysql_result($sqlTraining, 0, 'id') . "'");
						alert($CharacterInfo['id'], "Training", "You gained " . format($xp) . " exp from your training!");
					}
				}
			}
			if($banned){
				print "I'm sorry, it appears you've been banned :)";
			} else {
				if(!$training) {
					if($Alert == true){
						print "<h2>You have $AN new Alert(s)</h2><br />";
					}
					if($Message == true){
						print "<h2>You have $MN new message(s)</h2><br />";
					}
					//check for death :)
					if($loggedin && $CharacterInfo["now_hp"] == 0 && $page != "hospital"){
						$charge = ($CharacterInfo["level"]*50) * ($CharacterInfo["max_hp"] - $CharacterInfo["now_hp"]);
						$blah = FineMoney($charge,true);
						print "You were rushed to hospital and you were saved. However you were not covered by insurance, and it cost you $charge KD<br />";
					}
					
					//	Random things
					if(mt_rand(1, 200) <= 1) {	//	0.5% chance to get some EXP.
						if($loggedin) {
							addExp($CharacterInfo['id'], mt_rand(1, 5));
						}
					}
					if(mt_rand(1, 200) <= 1) {	//	0.5% chance to find some money
						if($loggedin) {
							$money = mt_rand(1, $CharacterInfo['level'] * 100);
							updateCharacter("money", "(money + {$money})", $CharacterInfo['id']);
							print "You found " . format($money) . " KD!";
						}
					}
					// Load actual page files
					if(file_exists("./pages/$page.php")){
						include("./pages/$page.php");
					} else {
						include("./pages/home.php");
					}
				}
			}
			?>
			</center>
        </div>
    <div id="nav_main">
        <h4>Links</h4>
        <ul>
            <li><a href="?page=census">Census</a></li>
			<li><a href="?page=rich_list">The Rich List</a></li>
            <li>Online: <?=$online?></li>
            <li>Population: <?=$population?></li>
			<li><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
				<input type="hidden" name="cmd" value="_donations">
				<input type="hidden" name="business" value="kmanz69@hotmail.com">
				<input type="hidden" name="item_name" value="Donation">
				<input type="hidden" name="no_shipping" value="0">
				<input type="hidden" name="no_note" value="1">
				<input type="hidden" name="currency_code" value="AUD">
				<input type="hidden" name="tax" value="0">
				<input type="hidden" name="lc" value="AU">
				<input type="hidden" name="bn" value="PP-DonationsBF">
				<input type="image" src="https://www.paypal.com/en_AU/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
				<img alt="" border="0" src="https://www.paypal.com/en_AU/i/scr/pixel.gif" width="1" height="1">
				</form></li>
        </ul>
    </div>
</div>
<div id="footer">
    <div id="copyright">Copyright &copy; 2007</div>
        <ul id="nav_footer">
        <li><a href="#">Link</a> |</li>
        <li>&nbsp;<a href="#">Link</a> |</li>
        <li>&nbsp;<a href="#">Link</a></li>
        </ul>
</div>
</body>
</html>