123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532 |
- <?php
- require_once("config.php");
- $nickname = $discordUsername = $username = $birthDate = $submitTime = "";
- $success = false;
- $errors = array();
- session_start();
- class db {
- // db class originally written by David Adams at https://codeshack.io/
- protected $connection;
- protected $query;
- protected $show_errors = TRUE;
- protected $query_closed = TRUE;
- public $query_count = 0;
- public function __construct($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase) {
- $this->connection = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase);
- if ($this->connection->connect_error) {
- $this->error("Failed to connect to MySQL - " . $this->connection->connect_error);
- }
- $this->connection->set_charset("utf8mb4");
- $this->query("SET collation_connection = utf8mb4_unicode_ci");
- $this->query("CREATE TABLE IF NOT EXISTS empyreanrealm (
- id INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY,
- nickname VARCHAR(32) NOT NULL,
- discord VARCHAR(32) NOT NULL,
- username VARCHAR(32) NOT NULL,
- birthdate DATE NOT NULL,
- reference VARCHAR(32) NULL,
- submittime VARCHAR(20) NOT NULL
- ) COLLATE utf8mb4_unicode_ci
- ");
- }
- public function query($query) {
- if (!$this->query_closed) {
- $this->query->close();
- }
- if ($this->query = $this->connection->prepare($query)) {
- if (func_num_args() > 1) {
- $x = func_get_args();
- $args = array_slice($x, 1);
- $types = "";
- $args_ref = array();
- foreach ($args as $k => &$arg) {
- if (is_array($args[$k])) {
- foreach ($args[$k] as $j => &$a) {
- $types .= $this->_gettype($args[$k][$j]);
- $args_ref[] = &$a;
- }
- } else {
- $types .= $this->_gettype($args[$k]);
- $args_ref[] = &$arg;
- }
- }
- array_unshift($args_ref, $types);
- call_user_func_array(array($this->query, "bind_param"), $args_ref);
- }
- $this->query->execute();
- if ($this->query->errno) {
- $this->error("Unable to process MySQL query (check your params) - " . $this->query->error);
- }
- $this->query_closed = FALSE;
- $this->query_count++;
- } else {
- $this->error("Unable to prepare MySQL statement (check your syntax) - " . $this->connection->error);
- }
- return $this;
- }
- public function fetchAll($callback = null) {
- $params = array();
- $row = array();
- $meta = $this->query->result_metadata();
- while ($field = $meta->fetch_field()) {
- $params[] = &$row[$field->name];
- }
- call_user_func_array(array($this->query, "bind_result"), $params);
- $result = array();
- while ($this->query->fetch()) {
- $r = array();
- foreach ($row as $key => $val) {
- $r[$key] = $val;
- }
- if ($callback != null && is_callable($callback)) {
- $value = call_user_func($callback, $r);
- if ($value == "break") break;
- } else {
- $result[] = $r;
- }
- }
- $this->query->close();
- $this->query_closed = TRUE;
- return $result;
- }
- public function fetchArray() {
- $params = array();
- $row = array();
- $meta = $this->query->result_metadata();
- while ($field = $meta->fetch_field()) {
- $params[] = &$row[$field->name];
- }
- call_user_func_array(array($this->query, "bind_result"), $params);
- $result = array();
- while ($this->query->fetch()) {
- foreach ($row as $key => $val) {
- $result[$key] = $val;
- }
- }
- $this->query->close();
- $this->query_closed = TRUE;
- return $result;
- }
- public function close() {
- return $this->connection->close();
- }
- public function affectedRows() {
- return $this->query->affected_rows;
- }
- public function error($error) {
- if ($this->show_errors) {
- exit($error);
- }
- }
- private function _gettype($var) {
- if (is_string($var)) return "s";
- if (is_float($var)) return "d";
- if (is_int($var)) return "i";
- return "b";
- }
-
- public function escapeString($string) {
- return $this->connection->real_escape_string($string);
- }
- }
- function cleanInput($value) {
- $value = trim($value);
- $value = stripslashes($value);
- $value = htmlspecialchars($value);
- return $value;
- }
- function verifyInput($type, $value) {
- $value = cleanInput($value);
- if (!is_string($value) || strlen($value) == 0) {
- return false;
- }
- $data = false;
- switch ($type) {
- case "username":
- $data = preg_match("/(?=.*[a-zA-Z0-9])^[a-zA-Z0-9-_ ]{3,32}$/", $value);
- break;
- case "date":
- if (false === strtotime($value)) {
- $data = false;
- } else {
- $td = explode('-', $value);
- if (count($td) !== 3) {
- $td = explode('/', $value);
- }
- if (count($td) === 3) {
- $data = checkdate($td[1], $td[2], $td[0]);
- } else {
- $data = false;
- }
- }
- break;
- case "discordUsername":
- $data = preg_match("/.+#[0-9]{4}(?<!0000)/", $value);
- break;
- }
- if ($data === false || $data === 0) {
- return false;
- }
- return $value;
- }
- function getDiscordAuthInfoFromCode($code)
- {
- global $config;
- $url = 'https://discordapp.com/api/oauth2/token';
- $data = array(
- 'client_id' => $config["discord"]["clientId"],
- 'client_secret' => $config["discord"]["clientSecret"],
- 'grant_type' => 'authorization_code',
- 'code' => $code,
- 'redirect_uri' => $config["siteUrl"]."/login/redirect",
- 'scope' => 'identify%20guilds'
- );
- $options = array(
- 'http' => array(
- 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
- 'method' => 'POST',
- 'content' => http_build_query($data),
- 'ignore_errors' => true
- )
- );
- $context = stream_context_create($options);
- $result = file_get_contents($url, false, $context);
- $status_line = $http_response_header[0];
- preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
- $status = $match[1];
- $result = json_decode($result);
- if ($status != 200) {
- echo("ERROR! " . $status . " " . $result->error_description);
- var_dump($result);
- return false;
- } else {
- return $result;
- }
- }
- function getDiscordUserInfo($access_token)
- {
- $url = 'https://discordapp.com/api/users/@me';
- $options = array(
- 'http' => array(
- 'header' => "Authorization: Bearer $access_token\r\n",
- 'method' => 'GET',
- 'ignore_errors' => true
- )
- );
- $context = stream_context_create($options);
- $result = file_get_contents($url, false, $context);
- $status_line = $http_response_header[0];
- preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
- $status = $match[1];
- if ($status != 200) {
- echo("ERROR 2! " . $status);
- return false;
- } else {
- $result = json_decode($result);
- return $result;
- }
- }
- function getDiscordUserGuilds($access_token)
- {
- $url = 'https://discordapp.com/api/users/@me/guilds';
- $options = array(
- 'http' => array(
- 'header' => "Authorization: Bearer $access_token\r\n",
- 'method' => 'GET',
- 'ignore_errors' => true
- )
- );
- $context = stream_context_create($options);
- $result = file_get_contents($url, false, $context);
- $status_line = $http_response_header[0];
- preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
- $status = $match[1];
- if ($status != 200) {
- echo("ERROR 2! " . $status);
- return false;
- } else {
- $result = json_decode($result);
- return $result;
- }
- }
- function sendDcMessage($webhook, $message)
- {
- $ch = curl_init();
- curl_setopt_array($ch, [
- CURLOPT_URL => $webhook,
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => $message,
- CURLOPT_HTTPHEADER => [
- "Content-Type: application/json"
- ]
- ]);
- $response = curl_exec($ch);
- curl_close($ch);
- if ($response == 1) {
- return $response;
- }
- return "Error: Issue sending message";
- }
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- if (isset($_POST["delete"])) {
- print_r($_POST["delete"]);
- $conn = new db($config["mysql"]["host"], $config["mysql"]["user"], $config["mysql"]["password"], $config["mysql"]["database"]);
- if ($conn->query("DELETE FROM empyreanrealm WHERE id = ?", $conn->escapeString(cleanInput($_POST["delete"])))->affectedRows() === 1) {
- $success = true;
- } else {
- $errors[] = "Error deleting application.";
- }
- }
- $nickname = verifyInput("username", $_POST["nickname"]);
- if ($nickname === false) {
- $errors[] = "Invalid nickname.";
- }
- $discordUsername = verifyInput("discordUsername", $_POST["discordUsername"]);
- if ($discordUsername === false) {
- $errors[] = "Invalid discord username.";
- }
- $username = verifyInput("username", $_POST["username"]);
- if ($username === false) {
- $errors[] = "Invalid username.";
- }
- $birthDate = verifyInput("date", $_POST["birthDate"]);
- if ($birthDate === false) {
- $errors[] = "Invalid birthDate.";
- }
- if ($birthDate !== false) {
- $dobDateTime = new DateTime($birthDate);
- $currentDateTime = new DateTime(date("Y-m-d"));
- $difference = $dobDateTime->diff($currentDateTime);
- if ($difference->y < 13) {
- $errors[] = "You must be 13 years or older in order to register.";
- $birthDate = false;
- }
- if ($difference->y > 110) {
- $errors[] = "Age valid up to 110.";
- $birthDate = false;
- }
- } else {
- $errors[] = "Invalid date of birth. Format must be YYYY-MM-DD.";
- $birthDate = false;
- }
- $reference = verifyInput("username", $_POST["reference"]);
- if ($reference === false) {
- $errors[] = "Invalid reference.";
- }
- if (empty($errors)) {
- $conn = new db($config["mysql"]["host"], $config["mysql"]["user"], $config["mysql"]["password"], $config["mysql"]["database"]);
- $nickname = $conn->escapeString($nickname);
- $discordUsername = $conn->escapeString($discordUsername);
- $username = $conn->escapeString($username);
- $birthDate = $conn->escapeString($birthDate);
- $reference = $conn->escapeString($reference);
- $submitTime = $conn->escapeString(date("Y-m-d\TH:i:s"));
- if ($conn->query("INSERT INTO empyreanrealm (nickname, discord, username, birthdate, reference, submittime) VALUES (?,?,?,?,?,?)", $nickname, $discordUsername, $username, $birthDate, $reference, $submitTime)->affectedRows() === 1) {
- $message = json_encode([
- "username" => "Bedrock Applications",
- "avatar_url" => $config["siteUrl"]."/source/logo.png",
- "content" => "<@&724644194135834727> New Bedrock Application!",
- "embeds" => [
- [
- "title" => "New Bedrock Application",
- "type" => "rich",
- "description" => "$nickname has applied to the bedrock server.",
- "timestamp" => date("Y-m-d\TH:i:s"),
- "url" => $config["siteUrl"]."/applications",
- "color" => hexdec("55C9F6"),
- "fields" => [
- [
- "name" => "Nickname",
- "value" => "$nickname",
- "inline" => false
- ],
- [
- "name" => "Bedrock Username",
- "value" => "$username",
- "inline" => false
- ],
- [
- "name" => "Discord Username",
- "value" => "$discordUsername",
- "inline" => false
- ],
- [
- "name" => "Birth Date",
- "value" => "$birthDate",
- "inline" => false
- ],
- [
- "name" => "Reference",
- "value" => "$reference",
- "inline" => false
- ]
- ]
- ]
- ]
-
- ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
- sendDcMessage($config["discord"]["webhook"], $message);
- $success = true;
- } else {
- $errors[] = "Error submitting form.";
- }
- }
- }
- $url = parse_url($config["siteUrl"].$_SERVER["REQUEST_URI"]);
- $page = $url["path"];
- $page = strtolower($page);
- $page = str_replace(" ", "-", $page);
- $page = preg_replace("/\?.+/", "", $page);
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Empyrean Realm - Bedrock Server Application</title>
- <meta name="description" content="Apply to be whitelisted on the Empyrean Realm' bedrock server">
- <meta name="author" content="Empyrean Realm">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="/source/style.css">
- </head>
- <body>
- <?php if ($success && !isset($_POST["delete"])) { ?>
- <div>
- <img src="source/logo.png" alt="logo" id="logo">
- <h1>Bedrock Server Application</h1>
- <p>Hurray! We recived your submission and we will review it as soon as possible, hold on tight!</p>
- </div>
- <?php } else if (!isset($_SESSION["loggedIn"],$_GET["code"]) && stristr($page, "/login/redirect")) {
- $authResult = getDiscordAuthInfoFromCode($_GET["code"]);
- if ($authResult !== false) {
- $discordInfo = getDiscordUserInfo($authResult->access_token);
- $_SESSION["discordId"] = $discordInfo->id;
- $_SESSION["discordName"] = $discordInfo->username;
- $_SESSION["loggedIn"] = true;
- header("Location: /applications");
- }
- } else if (stristr($page, "/logout")) {
- session_destroy();
- header("Location: /");
- } else if (!isset($_SESSION["loggedIn"]) && stristr($page, "/login")) {
- $redirectUri = urlencode($config["siteUrl"]."/login/redirect");
- header("Location: ". "https://discordapp.com/api/oauth2/authorize?client_id=" . $config["discord"]["clientId"] . "&redirect_uri=" . $redirectUri . "&response_type=code&scope=identify%20guilds");
- } else if (isset($_SESSION["loggedIn"]) && stristr($page, "/login")) {
- header("Location: /applications");
- } else if (isset($_SESSION["loggedIn"]) && in_array($_SESSION["discordId"], $config["allowedUsers"]) && stristr($page, "/applications")) { ?>
- <div>
- <h1>Bedrock Server Applications</h1>
- <div class="tableContainer">
- <table>
- <thead>
- <tr>
- <td>Nickname</td>
- <td>Discord</td>
- <td>Username</td>
- <td>Birth Date</td>
- <td>Reference</td>
- <td>Submission Date</td>
- <td>Delete</td>
- </tr>
- </thead>
- <tbody>
- <?php
- $conn = new db($config["mysql"]["host"], $config["mysql"]["user"], $config["mysql"]["password"], $config["mysql"]["database"]);
- $conn->query('SELECT * FROM empyreanrealm')->fetchAll(function($player) { ?>
- <tr>
- <td><?= $player["nickname"] ?></td>
- <td><?= $player["discord"] ?></td>
- <td><?= $player["username"] ?></td>
- <td><?= $player["birthdate"] ?></td>
- <td><?= $player["reference"] ?></td>
- <td><?= $player["submittime"] ?></td>
- <td>
- <form action="" method="post" onsubmit="return confirm('Irreversible action! Are you sure you want to delete this application?');">
- <button class="delete" type="submit" name="form" value="delete" title="Irreversible action, take caution.">
- <i class="fas fa-exclamation-triangle"></i> Delete
- </button>
- <input type="hidden" name="delete" value="<?= $player["id"] ?>">
- </form>
- </td>
- </tr>
- <?php });
- $conn->close(); ?>
- </tbody>
- </table>
- </div>
- </div>
- <?php } else if (!isset($_SESSION["loggedIn"]) && stristr($page, "/applications")) {
- header("Location: /login");
- } else if (stristr($page, "/bedrock")) { ?>
- <div>
- <img src="source/logo.png" alt="logo" id="logo">
- <h1>Bedrock Server Application</h1>
- <p>Please ask a Bedrock Moderator for assistance on Discord if required.</p>
- <p>Please only apply once, multiple applications or requests to add you to the server will result in your application being removed.</p>
- <p><a href="https://empyreanrealm.com/discord">Discord link</a></p>
- <p>This information can be seen by the moderation team. Please contact the Discord Admins if you wish this data to be removed, please note that removal of this information will require removing you from the bedrock server whitelist. Falsifying this information will result in an immediate ban on all platforms. We ask for players date of birth to ensure all users are over 13 years of age, the minimum required to join our Discord and Minecraft servers.</p>
- <p><i>* Required questions</i></p>
- <form action="" method="post">
- <label for="nickname">Name/nickname: *</label><br>
- <input type="text" id="nickname" name="nickname" placeholder="Name" pattern="(?=.*[a-zA-Z0-9])^[a-zA-Z0-9-_ ]{3,32}$" title="How you wish to be called." <?= ($nickname != "" && $nickname != false) ? "value=\"$nickname\"" : "" ?> required>
- <br>
- <label for="discordUsername">Discord username: *</label><br>
- <input type="text" id="discordUsername" name="discordUsername" placeholder="You#0001" pattern=".+#[0-9]{4}(?<!0000)" title="A discord username and tag Eg. You#0001" <?= ($discordUsername != "" && $discordUsername != false) ? "value=\"$discordUsername\"" : "" ?> required>
- <br>
- <label for="username">Minecraft bedrock username (make sure to check the capitalization otherwise it won't work): *</label><br>
- <input type="text" id="username" name="username" placeholder="EmpyreanRealm" pattern="(?=.*[a-zA-Z0-9])^[a-zA-Z0-9-_ ]{3,32}$" title="Your ingame name. Pay close attenction to the capitalization of the name otherwise we won't be able to whitelist you!" <?= ($username != "" && $username != false) ? "value=\"$username\"" : "" ?> required>
- <br>
- <label for="birthDate" required>Date of birth: *</label><br>
- <input type="date" id="birthDate" name="birthDate" title="Your date of birth. Will be used to to check if you are over 13 to comply with our rules." <?= ($birthDate != "" && $birthDate != false) ? "value=\"$birthDate\"" : "" ?> required>
- <br>
- <label for="reference">Reference: *</label><br>
- <input type="text" id="reference" name="reference" placeholder="Your reference" pattern="(?=.*[a-zA-Z0-9])^[a-zA-Z0-9-_ ]{3,32}$" title="Your reference, a player currently on the whitelist that invited you to apply." <?= ($reference != "" && $reference != false) ? "value=\"$reference\"" : "" ?> required>
- <br>
- <br>
- <input type="submit" value="Submit">
- </form>
- <?php if (!empty($errors)) { ?>
- <div class="errors">
- <?php foreach ($errors as $error) { ?>
- <p><?= $error ?></p>
- <?php } ?>
- </div>
- <?php } ?>
- </div>
- <?php } else if (stristr($page, "/store")) {
- header("Location: https://empyrean.craftingstore.net/");
- } else {
- header("Location: https://discord.gg/yPbwmXM");
- } ?>
- </body>
- </html>
|