<?php
session_start();
header('content-type: text/html; charset=utf-8');
require_once('mysql.php');
require_once('functions.php');
$loggedIn = false;
if(isset($_SESSION['uid']) && isset($_SESSION['username'])) {
	$loggedIn = true;
	$login_uid = intval($_SESSION['uid']);
	$uq = "SELECT * FROM users WHERE uid = ".$login_uid."";
	$uquery = mysql_query($uq) or die(mysql_error());
	$user_info = mysql_fetch_assoc($uquery);
	if(!$user_info) { // User dont exist, logout
		$_SESSION = array();
		session_destroy();
		header('Location: ./');
		exit;
	}
	$q = "UPDATE users SET lastlogin = CURRENT_TIMESTAMP WHERE uid = ".$login_uid;
	$query = mysql_query($q) or die(mysql_error());
}

$rankText = array('Regular user', 'Moderator', 'Administrator');

function linkusername($id, $name) {
	return "<a href=\"?user=".intval($id)."\">".htmlspecialchars($name)."</a>";
}
function avatar_url($uid) {
	$q = "SELECT avatar, UNIX_TIMESTAMP(avatar_updated) as timestamp FROM users WHERE uid = ".intval($uid);
	$query = mysql_query($q) or die(mysql_error());
	$res = mysql_fetch_assoc($query);
	if($res && strlen($res['avatar']) > 0) {
		return "avatar.php?uid=".intval($uid)."&timestamp=".$res['timestamp'];
	}
	else {
		return "default_avatar.png";
	}
}

?><!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="chrome=1">
	<title>Forum</title>
	<link rel="stylesheet" href="style.css">
	<script src="forum.js"></script>
</head>
<body>
<script>
window.TITLE = window.document.title;
window.SEPARATOR = " | ";
</script>
<div id="wrapper">
	<div id="main">
	<header>
		<a href="./" class="title">dj.js forum</a>
		
		
		<nav class="tabs">
			<ul>
			
				<li<?php if(empty($_GET)) echo ' class="current"'; ?>><a href="./">Start</a></li>
				<?php
					if($loggedIn) {
						?>
						<li<?php if(isset($_GET['members'])) echo ' class="current"'; ?>><a href="?members">Members</a></li>
						<?php
					}
					else {
						?>
						<?php
					}
				?>
			</ul>
			<ul class="right">
				<?php
				if($loggedIn) {
					$current_uid = intval($_SESSION['uid']);
					$current_username = $_SESSION['username'];
					?>
					<li<?php if(isset($_GET['user']) && intval($_GET['user']) === $current_uid) echo ' class="current"'; ?>><?php echo linkusername($current_uid, $current_username); ?></li>
					<li><a href="?logout">Log out</a></li>
					<?php
				}
				else {
					?>
					<li<?php if(isset($_GET['login'])) echo ' class="current"'; ?>><a href="?login">Log in</a></li>
					<li<?php if(isset($_GET['register'])) echo ' class="current"'; ?>><a href="?register">Register</a></li>
					<?php
				}
				?>
			</ul>
		</nav>
	</header>
	
	<div id="content">
<?php
if(isset($_GET['register'])) {
	?> <script>window.document.title = "Register"+SEPARATOR+TITLE;</script> <?php
	if(!isset($_POST['username']) && !isset($_POST['email']) && !isset($_POST['password'])) {
?>
<h2>Register</h2><br>
<form action="?register" method="post">
<table>
	<tr><td>Username:</td><td><input type=text maxlength=32 name="username" autofocus required></td></tr>
	<tr><td>Email:</td><td><input type=email maxlength=254 name="email" required></td></tr>
	<tr><td>Retype email:</td><td><input type=email maxlength=254 name="retype_email" required></td></tr>
	
	<tr><td>Password:</td><td><input type=password name="password" required></td></tr>
	<tr><td>Retype password:</td><td><input type=password name="retype_password" required></td></tr>
	
	<tr><td colspan=2><input type=submit value="Register"></td></tr>
	</table>
</form>
<?php
	}
	else {
		if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			echo "Invalid email address";
		}
		else if($_POST['email'] !== $_POST['retype_email']) {
			echo "Email don't match.";
		}
		else if($_POST['password'] !== $_POST['retype_password']) {
			echo "Password don't match.";
		}
		else if(strlen($_POST['password']) < 6) {
			echo "Too short password, needs to be longer than six characters.";
		}
		else {
			$q = mysql_query("SELECT uid, username FROM users WHERE username = \"".mysql_real_escape_string($_POST['username'])."\" LIMIT 1");
			if($res=mysql_fetch_assoc($q)) {
				echo "User <b>".htmlspecialchars($res['username'])."</b> already exists";
			}
			else {
				$username = mysql_real_escape_string($_POST['username']);
				$email = mysql_real_escape_string($_POST['email']);
				$password = md5($_POST['password']);
				$q = "INSERT INTO users (username, email, passwordHash, lastlogin) VALUES(\"".$username."\", \"".$email."\", \"".$password."\", CURRENT_TIMESTAMP)";
				$res = mysql_query($q);
				if(!$q || mysql_error()) {
					echo mysql_error();
					echo "<br>Your query: <code>".$q."</code>";
				}
				else {
					$_SESSION['uid'] = mysql_insert_id();
					$_SESSION['username'] = $username;
					header("Location: ?welcome");
				}
			}
		}
	}
} // End register
else if(isset($_GET['login'])) {
	?> <script>window.document.title = "Login"+SEPARATOR+TITLE;</script> <?php
	if(isset($_POST['username']) && isset($_POST['password'])) {
		$username = mysql_real_escape_string($_POST['username']);
		$password = md5($_POST['password']);
		$q = "SELECT username, uid FROM users WHERE username = \"".$username."\" AND passwordHash = \"".$password."\" LIMIT 1";
		$query = mysql_query($q) or die(mysql_error());
		$res = mysql_fetch_assoc($query);
		if(!$res) {
			echo "<h2>Wrong username and/or password</h2>";
		}
		else {
			$q2 = "UPDATE users SET lastlogin = CURRENT_TIMESTAMP WHERE uid = ".$res['uid'];
			mysql_query($q2) or die(mysql_error());
			$_SESSION['uid'] = $res['uid'];
			$_SESSION['username'] = $res['username'];
			echo "<h2>You are now logged in</h2><script>document.location.href = \"./\";</script>";
		}
	}
	else {
?>
<h2>Login</h2><br>
<form action="?login" method="post">
	<table>
	<tr>
		<td>Username</td>
		<td>Password</td>
		<td></td>
	</tr>
	<tr>
		<td><input type=text name="username" required autofocus></td>
		<td><input type=password name="password" required></td>
		<td><input type=submit value="Login"></td>
	</tr>
	</table>
</form>

<?php
	}
} // End login
else if(isset($_GET['logout'])) {
	$_SESSION = array();
	session_destroy();
	echo "<h2>You are now logged out</h2><script>document.location.href = './';</script>";
}
else if(isset($_GET['members'])) {
	?> <script>window.document.title = "Members"+SEPARATOR+TITLE;</script> <?php
	if($loggedIn) {
		$q = "
		SELECT
			users.uid, users.username, UNIX_TIMESTAMP(users.lastlogin) AS lastlogintime, users.lastlogin, COUNT(posts.id) AS postcount, users.permissions
		FROM
			users
		LEFT JOIN
			posts
			ON
			posts.poster_uid=users.uid
		GROUP BY
			users.uid
		ORDER BY
			users.lastlogin
			DESC
		
		";
		$query = mysql_query($q) or die(mysql_error());
		$now = time();
		echo "<h2>Members</h2><br>";
		echo "<table border cellspacing=0 class='nicetable'>
		<tr><th>Avatar</th><th>Username</th><th>Posts</th><th>Last active</th><th>Rank</th></tr>";
		while($row = mysql_fetch_assoc($query)) {
			$time = $now - $row['lastlogintime'];
			$ago = timeAgo($time);
			
			$isOnline = $time/60 < 10; // 10 minutes ago
			
			echo "<tr><td><img src=\"".avatar_url($row['uid'])."\" width=48></td><td>".linkusername($row['uid'], $row['username'])."</td><td>".$row['postcount']."</td><td style=\"background-color: ".($isOnline? '#DFD':'#FDD')."\">".$ago." ago</td><td>".$rankText[intval($row['permissions'])]."</td></tr>";
			//var_dump($row);
		}
		echo "</table>";
	}
	else {
		echo "<h2>You are not logged in!</h2>";
	}
}
else if(isset($_GET['user'])) {
	$uid = intval($_GET['user']);
	
	if($uid >= 0) {
		$q = "SELECT username, email, joindate, lastlogin, avatar, permissions FROM users WHERE uid = ".$uid." LIMIT 1";
		$query = mysql_query($q) or die(mysql_error());
		$user = mysql_fetch_assoc($query);
		if($user) {
			$myProfilePage = $loggedIn && intval($_SESSION['uid']) === $uid;
			
			?>
			<script>window.document.title = <?php echo json_encode($user['username']); ?>+SEPARATOR+TITLE;</script>
			
			<h2>Viewing user profile for <?php echo htmlspecialchars($user['username']); ?></h2>
			<br><img src="<?php echo avatar_url($uid); ?>"><br>
			<?php
			if($myProfilePage) {
				?>
				Change avatar:<br><form action="?avatar" method="post" enctype="multipart/form-data"><input type=file name="avatarfile" required accept="image/*" onchange="this.form.submit();"></form>
				<?php
			}
			?>
			<br>
			<?php
			if($myProfilePage) {
				?>
				E-mail: <?php echo $user['email']; ?><br>
				<?php
			}
			?>
			Rank: <?php echo $rankText[intval($user['permissions'])]; ?><br>
			Joined: <?php echo $user['joindate']; ?><br>
			Last logged in: <?php echo $user['lastlogin']; ?><br>
			
			<a name="userposts"></a>
			<h3>Posts by <?php echo htmlspecialchars($user['username']); ?>:</h3>
			<table border cellspacing=0 class='nicetable'>
			<tr><th align=left>Thread and content</th><th>Category and date</th></tr>
			<?php
			$page = isset($_GET['page'])? max(intval($_GET['page']), 1) : 1;
			$maxposts = 10;
			$from = $page*$maxposts - $maxposts;
			
			$q = "
				SELECT posts.id
				FROM
					posts
				WHERE
					poster_uid = ".$uid." AND hidden = 0
			";
			$query = mysql_query($q) or die(mysql_error());
			$postcount = mysql_num_rows($query);
			$pagecount = ceil($postcount/$maxposts);
			
			
			$pq = "
				SELECT
					posts.*, threads.title, categories.id AS cat_id, categories.name AS cat_name
				FROM
					posts
				JOIN
					threads
					ON
					posts.thread_id=threads.id
				JOIN
					categories
					ON
					categories.id=threads.cat_id
				WHERE
					poster_uid = ".$uid." AND hidden = 0
				GROUP BY
					posts.id
				ORDER BY
					post_date
					DESC
				LIMIT ".$from.", ".$maxposts."
			";
			$postquery = mysql_query($pq) or die(mysql_error());
			while($post = mysql_fetch_assoc($postquery)) {
				?><tr>
					<td><a href="?thread=<?php echo intval($post['thread_id'])."#".$post['id']; ?>"><strong><?php echo htmlspecialchars($post['title']); ?></strong></a><br><?php echo ellipsis(htmlspecialchars($post['content']), 80, true); ?></td>
					<td align=right><a href="?category=<?php echo intval($post['cat_id']); ?>"><?php echo htmlspecialchars($post['cat_name']); ?></a><br><?php echo htmlspecialchars($post['post_date']); ?></td>
				</tr><?php
			}
			?>
			</table>
			<?php
			
			for($i=1; $i <= $pagecount; $i++) {
				if($page === $i) {
					echo "<strong>".$i."</strong> ";
				}
				else {
					echo "<a href=\"?user=".$uid."&page=".$i."#userposts\">".$i."</a> ";
				}
			}
		}
		else {
			echo "User #".$uid." does not exist";
		}
	}
	else {
		echo "Invalid user id";
	}
}
else if(isset($_GET['avatar']) && isset($_FILES['avatarfile'])) {
	if($loggedIn) {
		$uid = intval($_SESSION['uid']);
		$file = $_FILES['avatarfile'];
		$allowed_types=array(
			'image/gif',
			'image/jpeg',
			'image/png',
		);
		if($file['error'] === 0 && $file['size'] < 8*1024*1024) {
			$tmp_name = $file["tmp_name"];
			$name = $file["name"];
			$filedata = file_get_contents($tmp_name);
			$image = imagecreatefromstring($filedata);
			if($image) {
				imagealphablending($image, true);
				list($width_orig, $height_orig) = getimagesize($tmp_name);
			
				$width = 256;
				$height = 256;
			
				$ratio_orig = $width_orig/$height_orig;
				if ($width/$height > $ratio_orig) {
				   $width = min($height*$ratio_orig, $width);
				} else {
				   $height = min($width/$ratio_orig, $height);
				}
			
				$image_p = imagecreatetruecolor($width, $height);
				imagealphablending($image_p, false);
				imagesavealpha($image_p,true);
				$transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
				imagefilledrectangle($image_p, 0, 0, $width, $height, $transparent);
				imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
				
				ob_start();
				imagepng($image_p);
				$imageData = ob_get_contents();
				ob_end_clean();
			
				$q = "UPDATE users SET avatar = '".mysql_real_escape_string($imageData)."', avatar_updated = CURRENT_TIMESTAMP WHERE uid = $uid";
				$query = mysql_query($q) or die(mysql_error());
				header("Location: ?user=$uid");
			}
			else {
				echo "<h2>Invalid image</h2>";
			}
			
		}
		else {
			echo "<h2>File too big or an error occured</h2>";
			echo "Error: ".$file['error']."<br>Filesize: ".($file['size']/1048576)." Mb";
		}
	}
	else {
		echo "<h2>You can't change avatar image, you are not logged in</h2>";
	}
}
else if(isset($_GET['post'])) {
	
	$postId = intval($_GET['post']);
	$pq = "SELECT id, poster_uid, thread_id FROM posts WHERE id = ".$postId."";
	$pquery = mysql_query($pq) or die(mysql_error());
	$post = mysql_fetch_assoc($pquery);
	if($post) {
		$poster_uid = intval($post['poster_uid']);
		$uq = "SELECT permissions FROM users WHERE uid = ".$poster_uid;
		$uquery = mysql_query($uq) or die(mysql_error());
		$post_user = mysql_fetch_assoc($uquery);
		if($loggedIn && isset($_GET['delete']) && ($poster_uid === $login_uid || (intval($user_info['permissions']) >= intval($post_user['permissions']) && intval($user_info['permissions']) > 0))) {
			if(intval($user_info['permissions']) > 0 && intval($_GET['delete']) === 0) {
				// Undelete
				$q = "UPDATE posts SET hidden = 0 WHERE id = ".$postId."";
			}
			else if(intval($_GET['delete']) === 1){
				// Delete
				$q = "UPDATE posts SET hidden = 1 WHERE id = ".$postId."";
			}
			$query = mysql_query($q) or die(mysql_error());
			header("Location: ?thread=".intval($post['thread_id'])."#".intval($postId));
		}
		else {
			echo "Welcome to the ELSE statement";
		}
	}
	else {
		echo "No such post exists!";
	}
}
else if(isset($_GET['newthread'])) {
	?> <script>window.document.title = "New thread"+SEPARATOR+TITLE;</script> <?php
	if($loggedIn) {
		if(isset($_POST['title']) && isset($_POST['content']) && isset($_POST['cat'])) {
			$cat_id = intval($_POST['cat']);
			$qcat = "SELECT id FROM categories WHERE id = ".$cat_id." LIMIT 1";
			$querycat = mysql_query($qcat) or die(mysql_error());
			$result = mysql_fetch_assoc($querycat);
			if($result) {
				$title = mysql_real_escape_string($_POST['title']);
				$content = mysql_real_escape_string($_POST['content']);
				$uid = intval($_SESSION['uid']);
				$qt = "INSERT INTO threads (title, creator, cat_id) VALUES(\"".$title."\", ".$uid.", ".$cat_id.")";
				$queryt = mysql_query($qt) or die(mysql_error());
				$thread_id = mysql_insert_id();
				$qp = "INSERT INTO posts (poster_uid, content, thread_id) VALUES(".$uid.", \"".$content."\", ".$thread_id.")";
				$queryp = mysql_query($qp) or die(mysql_error());
				
				echo "<h2>Posted!</h2><script>document.location.href = \"?thread=".$thread_id."\";</script>";
			}
			else {
				echo "Category does not exist";
			}
		}
		else if(isset($_GET['cat'])) {
			
			$selectedCat = intval($_GET['cat']);
			$qcat = "SELECT id, name FROM categories WHERE id = ".$selectedCat." LIMIT 1";
			$querycat = mysql_query($qcat) or die(mysql_error());
			$cat_info = mysql_fetch_assoc($querycat);
			if($cat_info) {
				
?>


<h2>Create new thread in "<?php echo htmlspecialchars($cat_info['name']); ?>"</h2>

<form action="?newthread" method="post">
<br>
<strong>Thread title:</strong>
<input type=text name="title" style="width: 100%; font-size: 1.5em; font-weight: bold;" autofocus required><br>

<?php
if($selectedCat > 0) {
	?>
	<input type="hidden" name="cat" value="<?php echo $selectedCat; ?>">
	<?php
}
else {
	?>
	<br>
	Category<br>
	<select name="cat"><option value="0">Select a category</option>
	<?php
		$q = "SELECT id, name FROM categories ORDER BY name DESC";
		$query = mysql_query($q) or die(mysql_error());
		while($cat = mysql_fetch_assoc($query)) {
			echo "<option value=\"".intval($cat['id'])."\">".htmlspecialchars($cat['name'])."</option>";
		}
	?>
	</select>
	<br>
	<?php
}
?>

<br>
<strong>First post:</strong>
<table width=100% class="post" cellspacing=0 id="post_new">
	<tr class="posttop"><td colspan=2>
		<div style="float: right;">
			<?php echo date('Y-m-d H:i:s'); ?>
		</div>
	</td></tr>
	<tr>
	<td width=1 class="postpanel">
		<?php echo linkusername($user_info['uid'], $user_info['username']); ?><br>
		<img src="<?php echo avatar_url($user_info['uid']); ?>" width=80>
	</td>
	<td class="postcontent">
		
			<textarea name="content" style="width: 99.5%;" rows=10 id="newpostcontent" required></textarea>
			<input type=submit value="Create thread">
			<hr>
			<div id="newpostpreview"></div>
		
	</td>
	</tr>
</table>

</form>

<?php
			}
			else {
				echo "<strong>Category does not exist</strong>";
			}
		}
		else {
			echo "<strong>No category selected</strong>";
		}
	}
	else {
		echo "<strong>You are not logged in</strong>";
	}
}
else if(isset($_GET['thread'])) {
	if(isset($_POST['content']) && $loggedIn) {
		$content = mysql_real_escape_string($_POST['content']);
		$q = "INSERT INTO posts (content, poster_uid, thread_id) VALUES (\"".$content."\", ".intval($_SESSION['uid']).", ".intval($_GET['thread']).")";
		mysql_query($q) or die(mysql_error());
		$post_id = mysql_insert_id();
		//echo "<h2>Posted!</h2><script>document.location.assert(\"?thread=".intval($_GET['thread'])."#".intval($post_id)."\");</script>";
		header("Location: ?thread=".intval($_GET['thread'])."#".intval($post_id));
	}
	else if($loggedIn && intval($user_info['permissions']) === 2 && isset($_GET['delete'])) {
		$qt = "SELECT id, title, creator FROM threads WHERE id = ".intval($_GET['thread']);
		$queryt = mysql_query($qt) or die(mysql_error());
		$thread_info = mysql_fetch_assoc($queryt);
		if($thread_info && intval($thread_info['id']) === intval($_GET['thread'])) {
			$q = "DELETE FROM threads WHERE id = ".intval($_GET['thread'])." LIMIT 1";
			$query = mysql_query($q) or die(mysql_error());
			if($query) {
				echo "<h2>Thread deleted successfully</h2>";
			}
			else {
				echo "<h2>This should not happen? Couldn't delete thread</h2>";
			}
		}
		else {
			echo "<h2>Thread does not exist</h2>";
		}
	}
	else {
		
		$qt = "
			SELECT title, creator, created, cat_id, users.permissions
			FROM threads
			JOIN users ON users.uid = threads.creator
			WHERE id = ".intval($_GET['thread'])."
		";
		$queryt = mysql_query($qt) or die(mysql_error());
		$thread_info = mysql_fetch_assoc($queryt);
		
		function printpost($username, $uid, $date, $content, $real_postid, $postid, $isHidden, $permissions) {
			global $loggedIn, $user_info, $rankText, $thread_info;
			$myPost = $loggedIn && intval($_SESSION['uid']) === intval($uid);
			?>
				<a name="<?php echo $real_postid; ?>"></a>
				<table width=100% class="post" cellspacing=0 id="post_<?php echo $real_postid; ?>">
				<tr class="posttop"><td colspan=2>
					<div style="float: right;">
						<?php if($postid > 0) echo "<a href=\"#".$real_postid."\"><strong>#".$postid."</strong></a> - "; ?>
						<?php echo $date; ?>
					</div>
				</td></tr>
				<tr>
				<td width=1 class="postpanel">
					<?php echo linkusername($uid, $username); ?><br>
					<img src="<?php echo avatar_url($uid); ?>" width=80>
					
					<?php if($loggedIn && !$isHidden && ($myPost || (intval($user_info['permissions']) >= $permissions && intval($user_info['permissions']) > 0))) { ?>
						<a href="javascript:" onclick="forum.editPost(<?php echo intval($real_postid); ?>);">Edit</a>
					<?php } ?>
				</td>
				<td class="postcontent">
					<?php
					if($isHidden) {
						echo '<i>This post is hidden.</i>';
						if($loggedIn && $isHidden && intval($user_info['permissions']) >= $permissions && intval($user_info['permissions']) > 0) {
							?> <a href="?post=<?php echo intval($real_postid); ?>&delete=0">Restore</a><hr><?php
						}
					}
					if(!$isHidden || ($loggedIn && intval($user_info['permissions']) >= $permissions && intval($user_info['permissions']) > 0)) {
						echo '<script>window.document.write(forum.bbcode2html('.json_encode($content).'));</script>';/*formatPostContent($content)*/
					}
					
					?>
				</td>
				</tr>
				</table>
			<?php
		}
		
		
		if($thread_info) {
			
			$qcat = "
				SELECT
					categories.name, categories.description
				FROM
					categories
				WHERE
					id = ".$thread_info['cat_id']."
				LIMIT 1
			";
			$querycat = mysql_query($qcat) or die(mysql_error());
			$cat_info = mysql_fetch_assoc($querycat);
			
			?> <script>window.document.title = <?php echo json_encode($thread_info['title']); ?>+SEPARATOR/*+"<?php echo htmlentities($cat_info['name']); ?>"+SEPARATOR*/+TITLE;</script> <?php
			
			$qp = "SELECT id, poster_uid, content, post_date, username, hidden, permissions FROM posts, users WHERE posts.poster_uid=users.uid AND thread_id=".intval($_GET['thread'])." ORDER BY post_date ASC";
			$queryp = mysql_query($qp) or die(mysql_error());
			
			$firstPost = mysql_fetch_assoc($queryp);
			//var_dump($thread_info);
			
			echo "<h2 style=\"float: left\"><a href=\"./\">Start</a> &#187; <a href=\"?category=".intval($thread_info['cat_id'])."\">".htmlspecialchars($cat_info['name'])."</a> &#187; <span id=\"thread_title\">".htmlspecialchars($thread_info['title'])."</span></h2>";
			
			?>
			<div style="float: right"><?php
				
				if($loggedIn && (intval($thread_info['creator']) === intval($user_info['uid']) || (intval($user_info['permissions']) >= intval($thread_info['permissions']) /*creator's permissions*/ && intval($user_info['permissions']) > 0))) {
					echo "<button id=\"thread_rename\">Rename thread</button>";
				}
				
				if($loggedIn && intval($user_info['permissions']) === 2) {
					echo "<button id=\"thread_delete\">Send thread to black hole</button>";
				}
			
			?></div>
			<br clear=all>
			<?php
			
			
			$allposts = array();
			
			printpost($firstPost['username'], $firstPost['poster_uid'], $firstPost['post_date'], $firstPost['content'], $firstPost['id'], '', $firstPost['hidden'], $firstPost['permissions']);
			$allposts[$firstPost['id']] = $firstPost['content'];
			echo "<hr>";
			
			$count = 1;
			
			while($post = mysql_fetch_assoc($queryp)) {
				printpost($post['username'], $post['poster_uid'], $post['post_date'], $post['content'], $post['id'], $count, $post['hidden'], $post['permissions']);
				$allposts[$post['id']] = $post['content'];
				$count++;
			}
			
			
			if($loggedIn) {
?>
<br>


<h3>Reply</h3>

<table width=100% class="post" cellspacing=0 id="post_new">
	<tr class="posttop"><td colspan=2>
		<div style="float: right;">
			<a href="javascript:"><strong>#X</strong></a> -
			<?php echo date('Y-m-d H:i:s'); ?>
		</div>
	</td></tr>
	<tr>
	<td width=1 class="postpanel">
		<?php echo linkusername($user_info['uid'], $user_info['username']); ?><br>
		<img src="<?php echo avatar_url($user_info['uid']); ?>" width=80>
	</td>
	<td class="postcontent">
		<form action="?thread=<?php echo intval($_GET['thread']); ?>" method="post">
			<textarea name="content" style="width: 99.5%;" rows=10 id="newpostcontent" required></textarea>
			<input type=submit value="Post">
			<hr>
			<div id="newpostpreview"></div>
		</form>
	</td>
	</tr>
</table>
<strong>BB-codes</strong><br>
[b][/b] [i][/i] [u][/u] [s][/s] [url=][/url] [img][/img] [code][/code] [color=][/color] [size=][/size]
[h1][/h1]-[h6][/h6] [table=][/table] [table][/table] [tr][/tr] [td][/td] [th][/th]


<?php
			}
		}
		else {
			echo "<h2>Thread don't exist</h2><a href=\"./\">Go back</a>";
		}
	}
}
else if(isset($_GET['category'])) {
	$cat_id = intval($_GET['category']);
	if($cat_id > 0) {
		
		$qcat = "
			SELECT
				categories.name, categories.description
			FROM
				categories
			WHERE
				id = ".$cat_id."
			LIMIT 1
		";
		$querycat = mysql_query($qcat) or die(mysql_error());
		$cat_info = mysql_fetch_assoc($querycat);
		if($cat_info) {
			
			?> <script>window.document.title = <?php echo json_encode($cat_info['name']); ?>+SEPARATOR+TITLE;</script> <?php
			
			echo "<h2><a href=\"./\">Start</a> &#187; ".htmlspecialchars($cat_info['name'])."</h2>";
			
			echo "<table border width=100% cellspacing=0 class='nicetable'>";
			echo "<tr><th>Thread</th><th>Thread starter</th><th>Posts</th><th>Last post</th></tr>";
			
			$page = isset($_GET['page'])? max(intval($_GET['page']), 1) : 1;
			$maxposts = 10;
			$from = $page*$maxposts - $maxposts;
			
			$q = "
				SELECT id
				FROM
					threads
				WHERE
					cat_id = ".$cat_id."
			";
			$query = mysql_query($q) or die(mysql_error());
			$postcount = mysql_num_rows($query);
			$pagecount = ceil($postcount/$maxposts);
			
			$q = "
				SELECT
					threads.*, users.username AS threadusername, COUNT(posts.id) AS postcount, MAX(posts.id) AS lastpostid, MAX(posts.post_date) AS lastpostdate
				FROM
					threads
				LEFT JOIN
					users
					ON
					users.uid=threads.creator
				LEFT JOIN
					posts
					ON
					posts.thread_id=threads.id AND posts.hidden = false
				WHERE
					threads.cat_id = ".$cat_id."
				GROUP BY
					threads.id
				ORDER BY
					lastpostdate
					DESC
			";
			
			
			//$q = "SELECT id, creator, username, created, title FROM threads LEFT JOIN users on threads.creator=users.uid ORDER BY created DESC";
			$query = mysql_query($q) or die(mysql_error());
			$now = time();
			while($row = mysql_fetch_assoc($query)) {
				
				$lastq = "
					SELECT
						posts.id, posts.poster_uid, posts.post_date, UNIX_TIMESTAMP(posts.post_date) as lastposttime, users.uid, users.username
					FROM
						posts
					JOIN
						users ON posts.poster_uid = users.uid
					WHERE
						posts.thread_id = ".$row['id']." AND posts.hidden = false
					ORDER BY posts.id DESC
					LIMIT 1
				";
				/*$query2 = mysql_query($q2) or die(mysql_error());
				$result = mysql_fetch_assoc($query2);
				$lastposteruid = $result['poster_uid'];
				$lastq = "
					SELECT
						users.username
					FROM
						users
					WHERE
						users.uid = ".intval($lastposteruid)."
					LIMIT 1
				";*/
				$lastquery = mysql_query($lastq) or die(mysql_error());
				$lastpost = mysql_fetch_assoc($lastquery);
				$lastposteruid = $lastpost['poster_uid'];
				$lastpostusername = $lastpost['username'];
				
				echo "<tr><td><a href=\"?thread=".intval($row['id'])."\">".htmlspecialchars($row['title'])."</a></td><td>".linkusername($row['creator'], $row['threadusername'])."<br>".$row['created']."</td><td>".intval($row['postcount'])."</td><td>".linkusername(intval($lastposteruid), $lastpostusername)."<br><a href=\"?thread=".intval($row['id'])."#".$lastpost['id']."\">".timeAgo($now - $lastpost['lastposttime'])." ago</a></td></tr>";
			}
			echo "</table>";
			
			if($loggedIn) {
				echo "<button onclick=\"document.location.href = '?newthread&cat=".$cat_id."';\">New thread</button><br>";
			}
			
		}
		else {
			echo "Category #".$cat_id." does not exist";
		}
		
	}
	else {
		echo "Invalid category id";
	}
}
else if(empty($_GET)) {
	
	echo "<h2>Start</h2>";
	
	echo "<table border width=100% cellspacing=0 class='nicetable'>";
	echo "<tr><th>Category</th><th>Stats</th><th>Last post</th></tr>";
	
	$qcat = "
		SELECT
			categories.id, categories.name, categories.description, (SELECT COUNT(threads.id) FROM threads WHERE threads.cat_id = categories.id) as threadcount
		FROM
			categories
		ORDER BY name ASC
	";
	
	$querycat = mysql_query($qcat) or die(mysql_error());
	$now = time();
	while($row = mysql_fetch_assoc($querycat)) {
		$tq = "
			SELECT COUNT(threads.id) as threadcount, threads.id as t_id, threads.title, threads.created, users.uid, users.username, posts.post_date AS lastpostdate, UNIX_TIMESTAMP(posts.post_date) as lastposttime, MAX(posts.id) as post_id
			FROM posts
			JOIN threads ON threads.id = posts.thread_id
			JOIN users ON posts.poster_uid = users.uid
			WHERE threads.cat_id = ".intval($row['id'])." AND posts.hidden = false
			GROUP BY posts.id
			ORDER BY post_id DESC
		";
		$tquery = mysql_query($tq) or die(mysql_error());
		$postcount = mysql_num_rows($tquery);
		$tinfo = mysql_fetch_assoc($tquery);
		
		
		echo "<tr>
			<td><a href=\"?category=".intval($row['id'])."\">".htmlspecialchars($row['name'])."</a><br>".htmlspecialchars($row['description'])."</td>
			<td>".formatS($row['threadcount'], 'thread')."<br>".formatS($postcount,'post')."</td>
			<td>";
		if($tinfo) {
			echo "In <a href=\"?thread=".intval($tinfo['t_id'])."#".$tinfo['post_id']."\">".htmlspecialchars($tinfo['title'])."</a> by ".linkusername(intval($tinfo['uid']), $tinfo['username'])."<br>".timeAgo($now - $tinfo['lastposttime'])." ago";
		}
		echo "</td>
			</tr>";
	}
	echo "</table>";
	
	if($loggedIn) {
		//echo "<button onclick=\"document.location.href = '?newthread';\">New thread</button><br>";
	}
}
else {
	header("Location: ./");
}
?>
	</div>
	
	<footer>
		<table width=100% cellspacing=0 cellpadding=0><tr>
			<td valign=top>
				Created by Daniel J &amp; Jonas S<br>
				Marks Gymnasium &copy; 2012
			</td>
			<td valign=center align=right>
				<a href="http://google.com/chrome" target="_blank"><img src="icons/chrome_logo.png" height=32></a>
				<a href="http://www.html5rocks.com/" target="_blank"><img src="icons/html5.png"></a>
				<a href="http://www.php.net/" target="_blank"><img src="icons/php.png"></a>
				<a href="https://developer.mozilla.org/en/JavaScript" target="_blank"><img src="icons/javascript.png" height=32></a>
				<a href="http://www.mysql.com/" target="_blank"><img src="icons/mysql.png" height=32></a>
				<a href="http://httpd.apache.org/" target="_blank"><img src="icons/apache.png" height=32></a>
			</td>
		</tr></table>
	</footer>
	</div>
</div>
</body>
</html>
