Repositories | Polyback | Log in to see private repositories


polyback-website / 32de824ed1c6d1185126d78087d2c781572f8c28 / api/gameserver/redeem-ticket.php

2,737 bytes | parent directory

<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';

// The game (headless engine) checks a joining player's ticket. Single use, valid for
// 5 minutes, and only for the job it was issued for.
//   {"ticket":"...","jobId":"..."} -> {"success":true,"userId":1,"username":"...","chatType":"Classic"}
// chatType: the place's Chat Type setting (Classic, Bubble or Both)

use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Gameservers;
use pizzaboxer\ProjectPolygon\Games;

Gameservers::RequireAuthorized();
$body = Gameservers::Body();
$ticket = (string) ($body["ticket"] ?? "");
$jobId = (string) ($body["jobId"] ?? "");
if (!preg_match('/^[0-9a-f]{48}$/', $ticket)) { http_response_code(400); die(json_encode(["success" => false, "message" => "Bad ticket"])); }

$row = Database::singleton()->run(
	"SELECT t.*, u.username FROM JoinTickets t JOIN users u ON u.id = t.UserID
	 WHERE t.Ticket = :t AND t.Used = 0 AND t.Created + 300 > UNIX_TIMESTAMP()",
	[":t" => $ticket]
)->fetch(PDO::FETCH_OBJ);
if (!$row || ($jobId !== "" && !hash_equals($row->JobID, $jobId)))
{
	http_response_code(403);
	die(json_encode(["success" => false, "message" => "Invalid or expired ticket"]));
}
// private servers: the ticket's user must still be allowed in (e.g. not unfriended since)
$job = Database::singleton()->run("SELECT * FROM GameJobs WHERE JobID = :j", [":j" => $row->JobID])->fetch(PDO::FETCH_OBJ);
if (!$job || !Games::CanJoinJob($job, (int) $row->UserID))
{
	http_response_code(403);
	die(json_encode(["success" => false, "message" => "You can't join this private server"]));
}
$claimed = Database::singleton()->run("UPDATE JoinTickets SET Used = 1 WHERE Ticket = :t AND Used = 0", [":t" => $ticket])->rowCount();
if (!$claimed) { http_response_code(403); die(json_encode(["success" => false, "message" => "Ticket already used"])); }
// the player is in this game now (and so no longer in any other)
Database::singleton()->run(
	"UPDATE GameJobPlayers SET Active = 0 WHERE UserID = :u AND JobID != :j AND Active",
	[":u" => $row->UserID, ":j" => $row->JobID]
);
Database::singleton()->run(
	"INSERT INTO GameJobPlayers (JobID, UserID, Joined, Active) VALUES (:j, :u, UNIX_TIMESTAMP(), 1)
	 ON DUPLICATE KEY UPDATE Joined = UNIX_TIMESTAMP(), Active = 1",
	[":j" => $row->JobID, ":u" => $row->UserID]
);

Database::singleton()->run("UPDATE assets SET Visits = Visits + 1 WHERE id = :p", [":p" => $job->PlaceID]);
$chatType = Database::singleton()->run("SELECT ChatType FROM assets WHERE id = :p", [":p" => $job->PlaceID])->fetchColumn();

die(json_encode(["success" => true, "userId" => (int) $row->UserID, "username" => $row->username, "jobId" => $row->JobID, "chatType" => (string) ($chatType ?: "Classic")]));