<?php

$database_file = './data/global_highscore.db';

$submission_salt = hash ("sha256", "asteroids rule");
$player_name = "";
$score_value = 0;
$key = "";
$valid_name_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-_!. ";

$raw_format = false;
if (isset ($_REQUEST["format"])) {
	if ($_REQUEST["format"] == "raw") {
		$raw_format = true;
	}
}

function print_raw_scores () {
	global $database_file;

	try {
		$db = new SQlite3($database_file);
	} catch (Exception $e) {
		print ("<h3>[Error] " . $e->getMessage() . "</h3>\n");
		die();
	}

	$query = $db->query('SELECT * FROM submissions ORDER BY score_value DESC LIMIT 10');

	while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
		print ($row['player_name'] . "\t" . $row['score_value'] . "\n");
	}
	$db->close();

	die();
}

function print_scores () {
	global $database_file;

	try {
		$db = new SQlite3($database_file);
	} catch (Exception $e) {
		print ("<h3>[Error] " . $e->getMessage() . "</h3>\n");
		die();
	}

	$query = $db->query('SELECT * FROM submissions ORDER BY score_value DESC');

	print ("<table border=1>\n");
	print ("<tr><td>id</td><td>playername</td><td>score</td><td>date</td><td>ip</td></tr>\n"); 

	while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
		print ("<tr>");

		print ("<td>" . $row['id'] . "</td>");
		print ("<td>" . $row['player_name'] . "</td>");
		print ("<td>" . $row['score_value'] . "</td>");
		print ("<td>" . $row['date'] . "</td>");
		print ("<td>" . $row['source_ip'] . "</td>");

		print ("</tr>\n");
	}
	print ("</table>\n");
	print ("</br>\n");

	$db->close();
}

function check_is_submission () {
	global $player_name, $score_value, $key, $valid_name_characters, $raw_format;

	if (isset ($_REQUEST["player_name"])
		&& isset ($_REQUEST["score_value"])
		&& isset ($_REQUEST["key"]	)) {
			$player_name = $_REQUEST["player_name"];

			// check whether the name only contains valid characters
			foreach (str_split ($player_name) as $c) {
				if (strpos ($valid_name_characters, $c) === FALSE) {
					if ($raw_format) {
						print ("ERROR: Invalid characters found in name!");
						die();
					}
					print ("<h3>ERROR: Invalid characters found in name!</h3>");

					return false;
				}
			}

			$score_value = (int) $_REQUEST["score_value"];
			$key = $_REQUEST["key"];

			return true;
		}
	return false;
}

function validate_submission () {
	if (!check_is_submission()) {
		return false;
	}
	global $player_name, $score_value, $key, $submission_salt, $raw_format;

	$verification_string = $player_name . ":" . (int) $score_value . ":" . $submission_salt;
	$verification_hash = hash ("sha256", $verification_string);

	if ($verification_hash == $key) {
		return true;
	}

	if (!$raw_format)
		print ("verification_hash = " . $verification_hash . "</br>\n");

	return false;
}

function dispatch_submission () {
	if (!validate_submission()) {
		die ("This is not a valid submission!");
	}

	global $database_file, $player_name, $score_value, $raw_format;

	try {
		$db = new SQlite3($database_file, SQLITE3_OPEN_READWRITE);
	} catch (Exception $e) {
		print ("ERROR: " . $e->getMessage() . "</h3>\n");
		die();
	}

	// check whether we already have an entry with the same data
	$query = $db->query('SELECT * FROM submissions WHERE player_name="' . $player_name . '" AND score_value=' . $score_value . ';');

	// if it already exists we just return as if it was accepted
	if ($query->fetchArray()) {
		if ($raw_format) {
			print ("OK\n");
			die();
		}	else {
			print ("<h3>OK</h3>\n");
			return;
		}
	}

	while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
		print ($row['player_name'] . "\t" . $row['score_value'] . "\n");
	}

	$submit_statement = 'INSERT INTO submissions (player_name, score_value, date, source_ip)
		VALUES (\'' . $player_name . '\', ' . (int) $score_value . ', DATETIME(\'NOW\'), \'' . $_SERVER['REMOTE_ADDR'] . '\');';

	$result = $db->exec($submit_statement);

	if ($result) {
		if ($raw_format)
			print ("OK\n");
		else
			print ("<h3>OK</h3>\n");
	} else {
		if ($raw_format)
			print ("ERROR: Database error when submitting value\n");
		else
			print ("<h3>ERROR: Database error when submitting value</h3>\n");
	}

	$db->close();
}

if ($raw_format) {
	if (check_is_submission()) {
		if (validate_submission()) {
			dispatch_submission();
		} else {
			print ("ERROR: invalid submission!");
		}	
	} else {
		print_raw_scores();
	}
	die();
}

print ("<h1>Asteroids Highscores</h1>\n");

print_scores();

if (check_is_submission()) {
	print ("player_name = " . $player_name . "</br>\n");
	print ("score_value = " . $score_value . "</br>\n");
	print ("key = " . $key . "</br>\n");

	dispatch_submission();
}

?>
<h2>Submit Entry</h2>
<form action="highscore.php" method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="player_name" /></td></tr>
<tr><td>Score:</td><td><input type="text" name="score_value" /></td></tr>
<tr><td>Key:</td><td><input type="text" name="key" /></td></tr>
</table>
<input type="submit" />
</form>
