Repositories | Polyback | Log in to see private repositories


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

11,672 bytes | parent directory

<?php

namespace pizzaboxer\ProjectPolygon;

// Catalog items made from the Roblox archive. Only administrators make them; their files stay in
// the archive and are served from there (rbxclient/asset/fetch.php), so a newer archived version
// applies by itself. Everybody else uploads their own items on the Develop page.
class Archive
{
	// archive type => how its picture is made
	const SELLABLE = [8 => "Model", 19 => "Model", 11 => "Clothing", 12 => "Clothing", 17 => "Head", 2 => "Clothing"];
	const MAX_PRICE = 1000000;

	static function Info($robloxId)
	{
		return Database::singleton()->run(
			"SELECT r.id, r.asset_type_id, r.sha256, r.kind, r.source, a.id AS CatalogID FROM roblox_assets r LEFT JOIN assets a ON a.RobloxID = r.id WHERE r.id = :id",
			[":id" => (int) $robloxId]
		)->fetch(\PDO::FETCH_OBJ);
	}

	static function File($row)
	{
		if (!$row || !preg_match('/^[0-9a-f]{64}$/', (string) $row->sha256)) return false;
		$path = Polygon::GetSharedResource("assets/rbxdump/" . substr($row->sha256, 0, 2) . "/{$row->sha256}");
		if (!file_exists($path)) return false;
		$data = file_get_contents($path);
		return Gzip::IsGzEncoded($data) ? gzdecode($data) : $data;
	}

	// Lists an archived item in the catalog. Returns the new catalog id, or an error text.
	static function Sell($robloxId, $name, $description, $price, $creatorId)
	{
		$row = self::Info($robloxId);
		if (!$row) return "That id isn't in the Roblox archive yet";
		if ($row->CatalogID) return "It's in the catalog already";
		if (!isset(self::SELLABLE[(int) $row->asset_type_id])) return "Only hats, gear, shirts, pants, T-shirts and heads can be sold from the archive";
		$name = trim((string) $name);
		if ($name === "" || mb_strlen($name) > 50) return "The name has to be 1 to 50 characters";
		if (mb_strlen((string) $description) > 1000) return "The description can't be longer than 1000 characters";
		if (!preg_match('/^[0-9]{1,7}$/', (string) $price) || (int) $price > self::MAX_PRICE) return "The price has to be from 0 to " . number_format(self::MAX_PRICE) . " Pizzas";
		$data = self::File($row);
		if ($data === false || strncmp($data, "<roblox", 7) !== 0) return "The archived file isn't a ROBLOX model";

		$type = (int) $row->asset_type_id;
		$options = ["type" => $type, "creator" => (int) $creatorId, "name" => $name, "description" => (string) $description,
			"approved" => 1, "sale" => 1, "price" => (int) $price, "RobloxID" => (int) $row->id];
		if ($type == 19) $options["gear_attributes"] = '{"melee":false,"powerup":false,"ranged":false,"navigation":false,"explosive":false,"musical":false,"social":false,"transport":false,"building":false}';
		$id = Catalog::CreateAsset($options);

		Polygon::RequestRender(self::SELLABLE[$type], $id);
		Users::LogStaffAction("[ Archive ] Put Roblox asset {$row->id} in the catalog as \"$name\" [ID $id] for $price Pizzas");
		return (int) $id;
	}

	// The .ROBLOSECURITY token a super admin stored for fetching item details (null if none).
	static function RobloxToken()
	{
		$v = Database::singleton()->run("SELECT Value FROM SiteSecrets WHERE Name = 'RobloxToken'")->fetchColumn();
		return $v === false ? null : $v;
	}

	static function RobloxTokenInfo()
	{
		return Database::singleton()->run(
			"SELECT s.SetAt, u.username FROM SiteSecrets s LEFT JOIN users u ON u.id = s.SetBy WHERE s.Name = 'RobloxToken'"
		)->fetch(\PDO::FETCH_OBJ);
	}

	// An item's name and description from ROBLOX (with the stored token, if there is one).
	// Returns an array, or an error text.
	static function RobloxDetails($robloxId)
	{
		if (!ctype_digit((string) $robloxId) || strlen((string) $robloxId) > 19) return "That isn't a ROBLOX id";
		$headers = ["User-Agent: Mozilla/5.0", "Accept: application/json"];
		if ($token = self::RobloxToken()) $headers[] = "Cookie: .ROBLOSECURITY=$token";
		$curl = curl_init("https://economy.roblox.com/v2/assets/" . (int) $robloxId . "/details");
		curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
		$body = curl_exec($curl);
		$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		curl_close($curl);
		if ($code == 429) return "ROBLOX says to slow down: try again in a moment";
		$d = $code == 200 ? json_decode((string) $body, true) : null;
		if (!is_array($d) || !isset($d["Name"])) return "ROBLOX has no details for $robloxId" . ($code ? " ($code)" : "");
		return ["name" => mb_substr((string) $d["Name"], 0, 50), "description" => mb_substr((string) ($d["Description"] ?? ""), 0, 1000),
			"type" => (int) ($d["AssetTypeId"] ?? 0), "creator" => (string) ($d["Creator"]["Name"] ?? "")];
	}

	const FETCH_AT_ONCE = 25;     // ids an administrator asks for in one go
	const FETCH_MOST_FILES = 200; // with what they use (meshes, textures, sounds...)
	const FETCH_SECONDS = 240;

	private static function roblox($url, $token)
	{
		$curl = curl_init($url);
		curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTPHEADER => ["User-Agent: Roblox/WinInet", "Cookie: .ROBLOSECURITY=$token"]]);
		$body = curl_exec($curl);
		$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		curl_close($curl);
		return [$code, $body === false ? "" : $body];
	}

	private static function format($data, $type)
	{
		return match (true) {
			str_starts_with($data, "\x89PNG") => "png",
			str_starts_with($data, "\xff\xd8\xff") => "jpeg",
			str_starts_with($data, "GIF8") => "gif",
			str_starts_with($data, "OggS") => "ogg",
			str_starts_with($data, "ID3") || str_starts_with($data, "\xff\xfb") => "mp3",
			str_starts_with($data, "RIFF") => "wav",
			str_starts_with($data, "version ") => "mesh",
			str_starts_with($data, "<roblox!") => "rbxbin",
			str_starts_with($data, "<roblox") => "rbxxml",
			$type == 5 => "lua",
			default => "bin",
		};
	}

	// Fetches ROBLOX assets straight into the archive with the stored token, and what they use
	// (meshes, textures, sounds) too. What's archived already is left alone. Returns one row per
	// asset: [id, name, what happened], and the ids there was no time for.
	static function FetchFromRoblox($ids, $withDependencies)
	{
		$token = self::RobloxToken();
		if (!$token) return [[], $ids, "No ROBLOX token is stored: a super admin can add one on the ROBLOX token page"];
		$db = Database::singleton();
		$started = time();
		$queue = [];
		foreach ($ids as $id) $queue[] = [(string) $id, 0];
		$seen = [];
		$rows = [];
		$files = 0;
		while ($queue)
		{
			[$id, $depth] = array_shift($queue);
			if (isset($seen[$id])) continue;
			$seen[$id] = true;
			if (time() - $started > self::FETCH_SECONDS || $files >= self::FETCH_MOST_FILES)
			{
				$left = array_values(array_unique(array_merge([$id], array_column(array_filter($queue, fn($q) => $q[1] == 0), 0))));
				return [$rows, $left, null];
			}
			$have = $db->run("SELECT name FROM roblox_assets WHERE id = :id AND sha256 IS NOT NULL", [":id" => $id])->fetch(\PDO::FETCH_OBJ);
			if ($have)
			{
				if ($depth == 0) $rows[] = [$id, (string) $have->name, "in the archive already"];
				continue;
			}
			$details = self::RobloxDetails($id);
			[$code, $meta] = self::roblox("https://assetdelivery.roblox.com/v2/assetId/" . (int) $id, $token);
			$location = $code == 200 ? (json_decode($meta, true)["locations"][0]["location"] ?? null) : null;
			if (!$location)
			{
				$rows[] = [$id, is_array($details) ? $details["name"] : "", $code == 401 || $code == 403 ? "ROBLOX won't give it out (private or the token isn't allowed)" : "ROBLOX doesn't have it ($code)"];
				continue;
			}
			[$code, $data] = self::roblox($location, $token);
			if ($code != 200 || $data === "")
			{
				$rows[] = [$id, is_array($details) ? $details["name"] : "", "the download failed ($code)"];
				continue;
			}
			if (Gzip::IsGzEncoded($data)) $data = gzdecode($data);
			$type = is_array($details) ? $details["type"] : 0;
			$kind = self::format($data, $type);
			$sha = hash("sha256", $data);
			$target = Polygon::GetSharedResource("assets/rbxdump/" . substr($sha, 0, 2) . "/$sha");
			if (!is_dir(dirname($target))) mkdir(dirname($target), 0775, true);
			if (!file_exists($target)) file_put_contents($target, $data);
			$db->run(
				"INSERT IGNORE INTO roblox_assets (id, name, description, asset_type_id, type_inferred, owner_id, for_sale, price, latest_version, sha256, size, kind, source, imported)
				 VALUES (:id, :n, :d, :t, 0, :o, 0, NULL, NULL, :h, :s, :k, 'import', UNIX_TIMESTAMP())",
				[":id" => $id, ":n" => is_array($details) ? $details["name"] : null, ":d" => is_array($details) ? $details["description"] : null,
				 ":t" => $type ?: null, ":o" => (int) (\SITE_CONFIG["AssetImportCreator"] ?? 1), ":h" => $sha, ":s" => strlen($data), ":k" => $kind]
			);
			$files++;
			$rows[] = [$id, is_array($details) ? $details["name"] : "", $depth ? "archived (used by another)" : "archived"];
			// what it uses: asset ids in models and scripts
			if ($withDependencies && $depth < 3 && in_array($kind, ["rbxxml", "rbxbin", "lua"]))
			{
				preg_match_all('/(?:rbxassetid:\/\/|asset\/?\?(?:[a-z]+=[^&<"\s]*&(?:amp;)?)*id=)([0-9]{1,19})/i', $data, $m);
				foreach (array_unique($m[1]) as $dep) if (!isset($seen[$dep])) $queue[] = [$dep, $depth + 1];
			}
		}
		return [$rows, [], null];
	}

	const BROWSE_TYPES = [8 => "Hats", 19 => "Gear", 11 => "Shirts", 12 => "Pants", 2 => "T-Shirts", 17 => "Heads"];
	const PER_PAGE = 24;

	// A page of the archive's items of one kind, newest ids first. $search: an id, or part of a
	// name (most archived items have none). Returns [items, total].
	static function Browse($type, $search, $page)
	{
		$where = "r.asset_type_id = :t AND r.sha256 IS NOT NULL";
		$args = [":t" => (int) $type];
		$search = trim((string) $search);
		if ($search !== "")
		{
			if (ctype_digit($search)) { $where .= " AND r.id = :id"; $args[":id"] = $search; }
			else { $where .= " AND r.name LIKE :q"; $args[":q"] = "%" . addcslashes($search, "%_\\") . "%"; }
		}
		$db = Database::singleton();
		$total = (int) $db->run("SELECT COUNT(*) FROM roblox_assets r WHERE $where", $args)->fetchColumn();
		$offset = max(0, ((int) $page - 1) * self::PER_PAGE);
		$items = $db->run(
			"SELECT r.id, r.name, r.thumbnail_sha256 IS NOT NULL AS HasPicture, a.id AS CatalogID, a.name AS CatalogName, a.price FROM roblox_assets r
			 LEFT JOIN assets a ON a.RobloxID = r.id WHERE $where ORDER BY r.id DESC LIMIT " . self::PER_PAGE . " OFFSET $offset", $args
		)->fetchAll(\PDO::FETCH_OBJ);
		return [$items, $total];
	}

	// What's been put in the catalog from the archive, newest first.
	static function Sold($limit = 100)
	{
		return Database::singleton()->run(
			"SELECT a.id, a.name, a.type, a.price, a.sale, a.RobloxID, a.created, u.username FROM assets a LEFT JOIN users u ON u.id = a.creator
			 WHERE a.RobloxID IS NOT NULL ORDER BY a.id DESC LIMIT " . (int) $limit
		)->fetchAll(\PDO::FETCH_OBJ);
	}

	// A model file listing ROBLOX ids, to import in Studio with "Add to the ROBLOX archive": the
	// importer fetches each from live ROBLOX (and what they use, like meshes and textures).
	static function ImportFile($ids)
	{
		$items = "";
		foreach ($ids as $i => $id)
			$items .= "\t\t<Item class=\"StringValue\" referent=\"R" . ($i + 1) . "\"><Properties><string name=\"Name\">$id</string><string name=\"Value\">rbxassetid://$id</string></Properties></Item>\n";
		return "<roblox xmlns:xmime=\"http://www.w3.org/2005/05/xmlmime\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"4\">\n"
			. "\t<Item class=\"Model\" referent=\"R0\"><Properties><string name=\"Name\">Archive request</string></Properties>\n$items\t</Item>\n</roblox>\n";
	}
}