Repositories | Polyback | Log in to see private repositories


polyback-website / f1a491a2b5b7c458dfd8fba776047b1fcb21c456 / api/private/classes/pizzaboxer/ProjectPolygon/Studio.php

5,831 bytes | parent directory

<?php

namespace pizzaboxer\ProjectPolygon;

// Polygon Studio (the editor built into polygon-engine) signs in with a username and password
// (plus a 2FA code when the account has 2FA) and gets a long-lived token, sent as
// "Authorization: Bearer <token>" on every /api/studio call. Only its sha256 is stored.
class Studio
{
	const MAX_PLACE_BYTES = 256 * 1024 * 1024;
	const CHUNK_BYTES = 16 * 1024 * 1024;
	const ERAS = ClientVersions::ALL;

	static function HashToken($token)
	{
		return hash("sha256", $token);
	}

	static function CreateToken($userId, $label = null)
	{
		$token = bin2hex(random_bytes(32));
		Database::singleton()->run(
			"INSERT INTO StudioTokens (TokenHash, UserID, Label, Created, LastUsed) VALUES (:h, :u, :l, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())",
			[":h" => self::HashToken($token), ":u" => $userId, ":l" => $label === null ? null : substr((string) $label, 0, 100)]
		);
		return $token;
	}

	// The user (users row) a token belongs to, or null (unknown, revoked, banned).
	static function TokenUser($token)
	{
		if (!is_string($token) || !preg_match('/^[0-9a-f]{64}$/', $token)) return null;
		$row = Database::singleton()->run(
			"SELECT t.id AS TokenID, t.LastUsed, u.* FROM StudioTokens t JOIN users u ON u.id = t.UserID
			 WHERE t.TokenHash = :h AND t.Revoked = 0",
			[":h" => self::HashToken($token)]
		)->fetch(\PDO::FETCH_OBJ);
		if (!$row || !empty($row->Banned)) return null;
		if ($row->LastUsed + 300 < time())
		{
			Database::singleton()->run("UPDATE StudioTokens SET LastUsed = UNIX_TIMESTAMP() WHERE id = :id", [":id" => $row->TokenID]);
		}
		return $row;
	}

	static function RequestUser()
	{
		return self::TokenUser(ClientContent::RequestToken());
	}

	// The signed-in Studio user, or a 401 JSON answer.
	static function RequireUser()
	{
		$user = self::RequestUser();
		if (!$user) API::respond(401, false, "Your Studio sign-in is no longer valid. Please sign in again.");
		return $user;
	}

	static function RevokeRequestToken()
	{
		$token = ClientContent::RequestToken();
		if (!preg_match('/^[0-9a-f]{64}$/', $token)) return;
		Database::singleton()->run("UPDATE StudioTokens SET Revoked = 1 WHERE TokenHash = :h", [":h" => self::HashToken($token)]);
	}

	// Staff log entry when an admin changes someone else's place from Studio.
	static function LogStaff($user, $place, $action)
	{
		if ((int) $user->id === (int) $place->creator || !self::IsAdmin($user)) return;
		Database::singleton()->run(
			"INSERT INTO stafflogs (time, adminId, action) VALUES (UNIX_TIMESTAMP(), :uid, :action)",
			[":uid" => $user->id, ":action" => "[ Asset Modification ] {$action} \"{$place->name}\" [Place ID {$place->id}] (Studio)"]
		);
	}

	static function IsAdmin($user)
	{
		return (int) ($user->adminlevel ?? 0) > 0;
	}

	// May this user add assets to the shared Roblox archive from Studio's importer?
	// Administrators and super admins with 2FA on (the rule for the site's admin tools);
	// IsAdmin() above is any staff rank, which is too broad for this.
	static function CanArchive($user)
	{
		return in_array((int) ($user->adminlevel ?? 0), [Users::STAFF_ADMINISTRATOR, Users::STAFF_SUPERADMIN], true) && !empty($user->twofa);
	}

	// One staff log entry per admin per import session, not one per asset (a place has thousands).
	static function LogArchiveUse($user)
	{
		$action = "[ Roblox Archive ] Adding assets from a Studio import";
		$recent = Database::singleton()->run(
			"SELECT 1 FROM stafflogs WHERE adminId = :uid AND action = :action AND time > UNIX_TIMESTAMP() - 1800 LIMIT 1",
			[":uid" => $user->id, ":action" => $action]
		)->fetchColumn();
		if ($recent) return;
		Database::singleton()->run(
			"INSERT INTO stafflogs (time, adminId, action) VALUES (UNIX_TIMESTAMP(), :uid, :action)",
			[":uid" => $user->id, ":action" => $action]
		);
	}

	// A place the user may change (owner or site admin), or a JSON error.
	static function RequirePlace($user, $placeId)
	{
		$place = Database::singleton()->run("SELECT * FROM assets WHERE id = :id AND type = 9", [":id" => (int) $placeId])->fetch(\PDO::FETCH_OBJ);
		if (!$place) API::respond(404, false, "That place doesn't exist");
		if ((int) $place->creator !== (int) $user->id && !self::IsAdmin($user)) API::respond(403, false, "Only the place's owner can change it");
		return $place;
	}

	static function PlaceInfo($place)
	{
		return [
			"id" => (int) $place->id,
			"name" => (string) $place->name,
			"description" => (string) ($place->description ?? ""),
			"era" => ClientVersions::Normalize($place->Version) ?? ClientVersions::DEFAULT,
			"maxPlayers" => (int) ($place->MaxPlayers ?: 12),
			"updated" => (int) $place->updated,
			"creator" => (int) $place->creator,
			"thumbnail" => Thumbnails::GetAsset($place, 768, 432),
			"version" => (int) Database::singleton()->run("SELECT COALESCE(MAX(Version), 0) FROM StudioPlaceVersions WHERE PlaceID = :p", [":p" => $place->id])->fetchColumn(),
		];
	}

	// JSON request body as an array (empty when missing or not JSON).
	static function Body()
	{
		$data = json_decode(file_get_contents("php://input"), true);
		return is_array($data) ? $data : [];
	}

	static function ValidateName($name)
	{
		if (!strlen($name)) return "The place needs a name";
		if (strlen($name) > 50) return "Place names can be at most 50 characters";
		if (Polygon::IsExplicitlyFiltered($name)) return "The place name contains inappropriate text";
		return null;
	}

	static function ValidateDescription($text)
	{
		if (strlen($text) > 1000) return "Descriptions can be at most 1000 characters";
		if (Polygon::IsExplicitlyFiltered($text)) return "The description contains inappropriate text";
		return null;
	}

	static function UploadDirectory()
	{
		$dir = Polygon::GetSharedResource("assets/studio-uploads");
		if (!is_dir($dir)) mkdir($dir, 0770, true);
		return $dir;
	}
}