function registerPlayer($xml)
{
    global $sqlhost, $sqlusername, $sqlpassword;
    #Check if registration credentials are valid.
    if ($xml->username == null or $xml->password == null) {
        error_log("registerPlayer.php - Registration rejected");
        return false;
    } else {
        #Clean up registration credentials.
        $tempUsername = preg_replace("/[^A-Za-z0-9]/", '', $xml->username);
        $tempPassword = preg_replace("/[^A-Za-z0-9]/", '', $xml->password);
        #Validate that username and password are legal.
        if (strlen($xml->username) == 0) {
            return false;
        } else {
            if (strlen($xml->password) == 0) {
                return false;
            } else {
                if ($tempUsername !== (string) $xml->username) {
                    return false;
                } else {
                    if ($tempPassword !== (string) $xml->password) {
                        return false;
                    } else {
                        $conn = new mysqli($sqlhost, $sqlusername, $sqlpassword);
                        if ($conn->connect_error) {
                            error_log("registerPlayer.php - Connection failed: " . $conn->connect_error);
                            return false;
                        }
                        #Check if username already taken
                        if ($checkStmt = $conn->prepare("SELECT COUNT(*) FROM sweepelite.players WHERE username=?")) {
                            $checkStmt->bind_param("s", $xml->username);
                            $checkStmt->execute();
                            $checkStmt->bind_result($count);
                            $checkStmt->close();
                            if ($count == 0) {
                                #Register the player in the MySQL database.
                                if ($registerStmt = $conn->prepare("INSERT INTO sweepelite.players (username, password, salt) VALUES (?,?,?)")) {
                                    $salt = sec_getNewSalt();
                                    $saltedPW = sec_getHashedValue($xml->password, $salt);
                                    $registerStmt->bind_param("sss", $xml->username, $saltedPW, $salt);
                                    $registerStmt->execute();
                                    if ($registerStmt->affected_rows > 0) {
                                        return true;
                                    } else {
                                        error_log("registerPlayer.php - Unable to register player.");
                                    }
                                }
                            }
                        } else {
                            error_log("registerPlayer.php - Unable to prepare statement for checking registration.");
                        }
                    }
                }
            }
        }
    }
    return false;
}
function initMySQL()
{
    global $sqlhost, $sqlusername, $sqlpassword;
    $conn = new mysqli($sqlhost, $sqlusername, $sqlpassword);
    if ($conn->connect_error) {
        die("initMySQL.php - Connection failed: " . $conn->connect_error);
    }
    $actionTableStatement = "CREATE TABLE IF NOT EXISTS sweepelite.actionqueue (\r\n\t\t`gameID` int(11) NOT NULL, \r\n\t\t`playerID` int(11) NOT NULL, \r\n\t\t`actionType` int(2) NOT NULL, \r\n\t\t`xCoord` int(11) NOT NULL, \r\n\t\t`yCoord` int(11) NOT NULL, \r\n\t\tKEY `gameID_idx` (`gameID`), \r\n\t\tKEY `playerID_idx` (`playerID`), \r\n\t\tCONSTRAINT `gameIDx` FOREIGN KEY (`gameID`) REFERENCES `games` (`gameID`) ON DELETE NO ACTION ON UPDATE NO ACTION, \r\n\t\tCONSTRAINT `playerIDx` FOREIGN KEY (`playerID`) REFERENCES `players` (`playerID`) ON DELETE CASCADE ON UPDATE CASCADE\r\n\t)";
    $chatTableStatement = "CREATE TABLE IF NOT EXISTS sweepelite.chatmessages (\r\n\t\t`playerID` int(11) NOT NULL, \r\n\t\t`message` varchar(500) NOT NULL DEFAULT 'ERROR', \r\n\t\t`time` datetime NOT NULL, \r\n\t\t`forCurrentGame` tinyint(1) NOT NULL DEFAULT '1', \r\n\t\tKEY `playerID_idx` (`playerID`), CONSTRAINT `chatPlayerID` FOREIGN KEY (`playerID`) REFERENCES `players` (`playerID`) ON DELETE CASCADE ON UPDATE CASCADE\r\n\t)";
    $gameTableStatement = "CREATE TABLE sweepelite.games (\r\n\t  \t`gameID` int(11) NOT NULL AUTO_INCREMENT,\r\n  \t\t`map` varchar(20000) NOT NULL,\r\n  \t\t`visibility` varchar(20000) NOT NULL,\r\n  \t\t`height` int(11) NOT NULL,\r\n  \t\t`width` int(11) NOT NULL,\r\n  \t\t`status` varchar(45) NOT NULL,\r\n  \t\t`friendlyTankCountdown` int(4) NOT NULL DEFAULT '3',\r\n  \t\t`friendlyTanks` varchar(2000) NOT NULL,\r\n  \t\t`enemyTankCountdown` int(6) NOT NULL DEFAULT '15',\r\n  \t\t`enemyTankCountdownReset` int(6) NOT NULL DEFAULT '15',\r\n  \t\t`enemyTanks` varchar(2000) NOT NULL,\r\n  \t\t`wrecks` varchar(2000) NOT NULL,\r\n  \t\t`traps` varchar(2000) NOT NULL,\r\n  \t\t`lastUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\r\n  \t\t`fullUpdate` tinyint(1) NOT NULL DEFAULT '1',\r\n\t  \tPRIMARY KEY (`gameID`)\r\n\t)";
    $globalTableStatement = "CREATE TABLE IF NOT EXISTS sweepelite.globalvars (\r\n\t\t`k` varchar(60) NOT NULL, \r\n\t\t`v` varchar(60) NOT NULL, \r\n\t\tUNIQUE KEY `key_UNIQUE` (`k`)\r\n\t)";
    $playerTableStatement = "CREATE TABLE IF NOT EXISTS sweepelite.players (\r\n\t\t`playerID` INT(11) NOT NULL AUTO_INCREMENT, \r\n\t\t`username` VARCHAR(45) NOT NULL, \r\n\t\t`password` varchar(128) NOT NULL,\r\n\t\t`salt` varchar(32) NOT NULL, \r\n\t\t`totalScore` int(11) NOT NULL DEFAULT '0',\r\n\t\tPRIMARY KEY (`playerID`), \r\n\t\tUNIQUE KEY `username_UNIQUE` (`username`)\r\n\t)";
    $fakePassword = bin2hex(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM));
    $fakeSalt = sec_getNewSalt();
    $highestScoreStatement = "INSERT INTO sweepelite.players (username, password, salt, totalScore) VALUES ('highestScore', " . sec_getHashedValue($fakePassword, $fakeSalt) . ", " . $fakeSalt . ", 1000)";
    $signupTableStatement = "CREATE TABLE IF NOT EXISTS sweepelite.upcomingsignup (\r\n\t\t`playerID` int(11) NOT NULL,\r\n \t\tUNIQUE KEY `playerID_UNIQUE` (`playerID`),\r\n  \t\tKEY `playerIDy_idx` (`playerID`),\r\n  \t\tCONSTRAINT `playerIDy` FOREIGN KEY (`playerID`) REFERENCES `players` (`playerID`) ON DELETE CASCADE ON UPDATE CASCADE\r\n\t)";
    $statusTableStatement = "CREATE TABLE sweepelite.playerstatus (\r\n\t\t`status` int(2) NOT NULL DEFAULT '1',\r\n\t\t`awaitingAction` bit(1) NOT NULL,\r\n\t\t`gameID` int(11) NOT NULL,\r\n\t\t`playerID` int(11) NOT NULL,\r\n\t\t`afkCount` int(4) NOT NULL DEFAULT '0',\r\n\t\t`trapType` int(4) NOT NULL DEFAULT '0',\r\n\t\t`trapCooldown` int(6) NOT NULL DEFAULT '0',\r\n\t\t`digNumber` int(11) NOT NULL DEFAULT '0',\r\n\t\t`correctFlags` int(11) NOT NULL DEFAULT '0',\r\n\t\tKEY `gameID_idx` (`gameID`),\r\n\t\tKEY `playerID_idx` (`playerID`),\r\n\t\tCONSTRAINT `gameID` FOREIGN KEY (`gameID`) REFERENCES `games` (`gameID`) ON DELETE NO ACTION ON UPDATE NO ACTION,\r\n\t\tCONSTRAINT `playerID` FOREIGN KEY (`playerID`) REFERENCES `players` (`playerID`) ON DELETE CASCADE ON UPDATE CASCADE\r\n\t)";
    $gameTableCreated = false;
    $playerTableCreated = false;
    $noErrors = true;
    if ($query = $conn->prepare($playerTableStatement)) {
        if ($query->execute()) {
            $playerTableCreated = true;
            error_log("initMySQL.php - Player table successfully created.");
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Player table not created. " . $query->errno . ": " . $query->error);
            error_log("Please run the following MySQL query manually:");
            error_log($playerTableStatement);
        }
        $query->close();
    } else {
        $noErrors = false;
        error_log("initMySQL.php - Failed to prepare player table statement. " . $conn->errno . ": " . $conn->error);
        error_log("Please run the following MySQL query manually:");
        error_log($playerTableStatement);
    }
    if ($query = $conn->prepare($gameTableStatement)) {
        if ($query->execute()) {
            $gameTableCreated = true;
            error_log("initMySQL.php - Game table successfully created.");
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Game table not created. " . $query->errno . ": " . $query->error);
            error_log("Please run the following MySQL query manually:");
            error_log($gameTableStatement);
        }
        $query->close();
    } else {
        $noErrors = false;
        error_log("initMySQL.php - Failed to prepare game table statement. " . $conn->errno . ": " . $conn->error);
        error_log("Please run the following MySQL query manually:");
        error_log($gameTableStatement);
    }
    if ($query = $conn->prepare($globalTableStatement)) {
        if ($query->execute()) {
            error_log("initMySQL.php - Global variables table successfully created.");
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Global variables table not created. " . $query->errno . ": " . $query->error);
            error_log("Please run the following MySQL query manually:");
            error_log($globalTableStatement);
        }
        $query->close();
    } else {
        $noErrors = false;
        error_log("initMySQL.php - Failed to prepare global variables table statement. " . $conn->errno . ": " . $conn->error);
        error_log("Please run the following MySQL query manually:");
        error_log($globalTableStatement);
    }
    if ($playerTableCreated) {
        if ($query = $conn->prepare($highestScoreStatement)) {
            if ($query->execute()) {
                error_log("initMySQL.php - Highest score implemented.");
            } else {
                $noErrors = false;
                error_log("initMySQL.php - Highest score not implemented.");
                error_log("Please run the following MySQL query manually:");
                error_log($highestScoreStatement);
            }
            $query->close();
        }
        if ($query = $conn->prepare($signupTableStatement)) {
            if ($query->execute()) {
                error_log("initMySQL.php - Upcoming sign-up table successfully created.");
            } else {
                $noErrors = false;
                error_log("initMySQL.php - Upcoming sign-up table not created. " . $query->errno . ": " . $query->error);
                error_log("Please run the following MySQL query manually:");
                error_log($signupTableStatement);
            }
            $query->close();
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Failed to prepare Upcoming sign-up table statement. " . $conn->errno . ": " . $conn->error);
            error_log("Please run the following MySQL query manually:");
            error_log($signupTableStatement);
        }
        if ($query = $conn->prepare($chatTableStatement)) {
            if ($query->execute()) {
                error_log("initMySQL.php - Chat table successfully created.");
            } else {
                $noErrors = false;
                error_log("initMySQL.php - Chat table not created. " . $query->errno . ": " . $query->error);
                error_log("Please run the following MySQL query manually:");
                error_log($chatTableStatement);
            }
            $query->close();
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Failed to prepare Upcoming sign-up table statement. " . $conn->errno . ": " . $conn->error);
            error_log("Please run the following MySQL query manually:");
            error_log($chatTableStatement);
        }
    } else {
        $noErrors = false;
        error_log("initMySQL.php - Due to player table creation failure, several important tables were not created.");
        error_log("Player run the following MySQL queries manually:");
        error_log($signupTableStatement);
        error_log($chatTableStatement);
    }
    if ($gameTableCreated && $playerTableCreated) {
        if ($query = $conn->prepare($actionTableStatement)) {
            if ($query->execute()) {
                error_log("initMySQL.php - Action table successfully created.");
            } else {
                $noErrors = false;
                error_log("initMySQL.php - Action table not created. " . $query->errno . ": " . $query->error);
                error_log("Please run the following MySQL query manually:");
                error_log($actionTableStatement);
            }
            $query->close();
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Failed to prepare action table statement. " . $conn->errno . ": " . $conn->error);
            error_log("Please run the following MySQL query manually:");
            error_log($actionTableStatement);
        }
        if ($query = $conn->prepare($statusTableStatement)) {
            if ($query->execute()) {
                error_log("initMySQL.php - Player status table successfully created.");
            } else {
                $noErrors = false;
                error_log("initMySQL.php - Player status table not created. " . $query->errno . ": " . $query->error);
                error_log("Please run the following MySQL query manually:");
                error_log($statusTableStatement);
            }
            $query->close();
        } else {
            $noErrors = false;
            error_log("initMySQL.php - Failed to prepare player status table statement. " . $conn->errno . ": " . $conn->error);
            error_log("Please run the following MySQL query manually:");
            error_log($statusTableStatement);
        }
    } else {
        $noErrors = false;
        error_log("initMySQL.php - Due to failure to create both player and game tables, several important tables were not created.");
        error_log("Player run the following MySQL queries manually:");
        error_log($actionTableStatement);
        error_log($statusTableStatement);
    }
    if ($noErrors) {
        if ($query = $conn->prepare("INSERT INTO `sweepelite`.`globalvars` (k, v) VALUES (?, ?)")) {
            $str_one = "mysqlInitialized";
            $str_two = "true";
            $query->bind_param("ss", $str_one, $str_two);
            $query->execute();
        } else {
            error_log("initMySQL.php - Failed to prepare final insertion statement. " . $conn->errno . ": " . $conn->error);
        }
    }
}
Example #3
0
function logInPlayer($xml, $fullLogInProcess)
{
    global $sqlhost, $sqlusername, $sqlpassword;
    global $numTraps;
    if ($xml->username == null || $xml->password == null) {
        error_log("logInPlayer.php - Login rejected.");
        return -1;
    } else {
        $conn = new mysqli($sqlhost, $sqlusername, $sqlpassword);
        if ($conn->connect_error) {
            error_log("logInPlayer.php - Connection failed: " . $conn->connect_error);
            return -1;
        }
        #Check if user exists.
        if ($stmt = $conn->prepare("SELECT playerID, password, salt FROM sweepelite.players WHERE username=?")) {
            $playerID = null;
            $stmt->bind_param("s", $xml->username);
            $stmt->execute();
            $stmt->bind_result($id, $controlPW, $salt);
            while ($stmt->fetch()) {
                $playerID = $id;
            }
            $stmt->close();
            #Check that the password is correct.
            $clientPW = sec_getHashedValue($xml->password, $salt);
            if ($clientPW !== $controlPW) {
                error_log("logInPlayer.php - Password failed the potato test.");
                return -1;
            }
            if ($playerID != null) {
                if ($fullLogInProcess) {
                    #Check if player is currently a part of the most recent game.
                    if ($statusStmt = $conn->prepare("SELECT g.gameID FROM sweepelite.playerstatus AS p INNER JOIN (SELECT gameID FROM sweepelite.games ORDER BY gameID DESC LIMIT 1) as g ON p.gameID = g.gameID WHERE playerID=?")) {
                        $gameID = null;
                        $statusStmt->bind_param("i", $playerID);
                        $statusStmt->execute();
                        $statusStmt->bind_result($gid);
                        while ($statusStmt->fetch()) {
                            $gameID = $gid;
                        }
                        $statusStmt->close();
                        if ($gameID === null) {
                            #Sign player up for game.
                            if ($gameIDStmt = $conn->prepare("SELECT gameID FROM sweepelite.games ORDER BY gameID DESC LIMIT 1")) {
                                $gameIDStmt->execute();
                                $gameIDStmt->bind_result($gid);
                                while ($gameIDStmt->fetch()) {
                                    $gameID = $gid;
                                }
                                $gameIDStmt->close();
                                if ($gameID !== null) {
                                    if ($signupStmt = $conn->prepare("INSERT INTO sweepelite.playerstatus (gameID, playerID, trapType, awaitingAction) VALUES (?, ?, ?, 1)")) {
                                        $trapID = ($gameID + $playerID) % $numTraps;
                                        $signupStmt->bind_param("iii", $gameID, $playerID, $trapID);
                                        $signupStmt->execute();
                                        $signupStmt->close();
                                    } else {
                                        error_log("loginPlayer.php - Unable to prepare sign up statement after logging in. " . $conn->errno . ": " . $conn->error);
                                    }
                                } else {
                                    error_log("loginPlayer.php - Unable to retrieve latest game ID. " . $conn->errno . ": " . $conn->error);
                                }
                            } else {
                                error_log("loginPlayer.php - Unable to prepare game ID retrieval statement after logging in. " . $conn->errno . ": " . $conn->error);
                            }
                        }
                    } else {
                        error_log("loginPlayer.php - Unable to prepare checking statement after logging in. " . $conn->errno . ": " . $conn->error);
                    }
                }
                signUpForNextGame($playerID);
                return $playerID;
            } else {
                error_log("logInPlayer.php - Unable to log in.");
            }
        } else {
            error_log("loginPlayer.php - Unable to prepare statement for logging in.");
        }
    }
    return -1;
}