Repositories | Polyback | Log in to see private repositories


polyback-website / 32de824ed1c6d1185126d78087d2c781572f8c28 / api/studio/import-upload.php

5,026 bytes | parent directory

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

// Studio's importer: a signed-in user uploads an asset (fetched from live Roblox) that the
// server's Roblox archive doesn't have. It becomes a Polyback asset owned by that user
// (polyasset://<id>); the archive itself is never written here.
//   POST multipart: file, sha256, kind (image|audio|mesh), source (the original reference)
//   Auth: the Studio token (Authorization: Bearer).
// -> {"success", "assetId", "existing"}
//
// Moderation: new assets are pending (approved = 0) and listed in the asset moderation
// queue; game servers and players can load them meanwhile. A declined asset stops loading,
// and the same content can't be uploaded again.
// Storage: each user may hold up to a cap of imported bytes (users.ImportQuotaMB when an
// admin set one, else SITE_CONFIG["StudioImportQuotaMB"], default 1024). Content already on
// the server (by sha256) is reused and costs nothing.

use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Studio;

API::initialize(["method" => "POST"]);
$user = Studio::RequireUser();
$db = Database::singleton();

$MAX_FILE = 20 * 1024 * 1024;

$file = $_FILES["file"] ?? null;
$sha256 = strtolower($_POST["sha256"] ?? "");
$kind = $_POST["kind"] ?? "";
$source = substr($_POST["source"] ?? "", 0, 255);

if (!$file || $file["error"] !== UPLOAD_ERR_OK) API::respond(400, false, "Missing file");
if ($file["size"] > $MAX_FILE) API::respond(413, false, "The file is larger than 20 MB");
if (!preg_match('/^[0-9a-f]{64}$/', $sha256)) API::respond(400, false, "Bad sha256");
if (!hash_equals($sha256, hash_file("sha256", $file["tmp_name"]))) API::respond(400, false, "sha256 does not match the uploaded data");

// only plain media: models and scripts stay embedded in the place file
$types = ["image" => 1, "audio" => 3, "mesh" => 4];
if (!isset($types[$kind])) API::respond(400, false, "Only images, audio and meshes can be uploaded");

// the bytes must really be that kind
$head = file_get_contents($file["tmp_name"], false, null, 0, 16);
$format = match (true) {
	str_starts_with($head, "\x89PNG") => "png",
	str_starts_with($head, "\xff\xd8\xff") => "jpeg",
	str_starts_with($head, "GIF8") => "gif",
	str_starts_with($head, "OggS") => "ogg",
	str_starts_with($head, "ID3") || (strlen($head) > 1 && ord($head[0]) === 0xFF && (ord($head[1]) & 0xE0) === 0xE0) => "mp3",
	str_starts_with($head, "RIFF") => "wav",
	str_starts_with($head, "version ") => "mesh",
	default => "",
};
$formatKind = ["png" => "image", "jpeg" => "image", "gif" => "image", "ogg" => "audio", "mp3" => "audio", "wav" => "audio", "mesh" => "mesh"];
if (($formatKind[$format] ?? "") !== $kind) API::respond(400, false, "The file isn't a supported $kind");

// already on the server: reuse it (unless a moderator declined it)
$existing = $db->run(
	"SELECT i.assetId, a.approved FROM import_assets i JOIN assets a ON a.id = i.assetId WHERE i.sha256 = :h",
	[":h" => $sha256]
)->fetch(PDO::FETCH_ASSOC);
if ($existing)
{
	if ((int) $existing["approved"] === 2) API::respond(403, false, "This content was declined by a moderator");
	die(json_encode(["status" => 200, "success" => true, "message" => "OK", "assetId" => (int) $existing["assetId"], "existing" => true]));
}

// storage cap
$quotaMB = $db->run("SELECT ImportQuotaMB FROM users WHERE id = :id", [":id" => $user->id])->fetchColumn();
if ($quotaMB === null || $quotaMB === false) $quotaMB = (int) (SITE_CONFIG["StudioImportQuotaMB"] ?? 1024);
$used = (int) $db->run(
	"SELECT COALESCE(SUM(i.size), 0) FROM import_assets i JOIN assets a ON a.id = i.assetId WHERE i.uploader = :id AND a.approved != 2",
	[":id" => $user->id]
)->fetchColumn();
if ($used + $file["size"] > (int) $quotaMB * 1024 * 1024)
	API::respond(403, false, sprintf("Your imported assets would exceed your %d MB storage limit (%.1f MB used)", $quotaMB, $used / 1048576));

$assetId = Catalog::CreateAsset([
	"type" => $types[$kind],
	"creator" => $user->id,
	"name" => "Imported " . ($source !== "" ? $source : substr($sha256, 0, 12)),
	"description" => "Imported in Polyback Studio from $source",
	"approved" => 0,
]);

$target = Polygon::GetSharedResource("assets/$assetId");
if (!is_dir(dirname($target))) mkdir(dirname($target), 0775, true);
if (!move_uploaded_file($file["tmp_name"], $target))
{
	$db->run("DELETE FROM assets WHERE id = :id", [":id" => $assetId]);
	$db->run("DELETE FROM ownedAssets WHERE assetId = :id", [":id" => $assetId]);
	API::respond(500, false, "Could not store the asset");
}

$db->run(
	"INSERT INTO import_assets (sha256, assetId, source, created, uploader, size) VALUES (:h, :id, :src, UNIX_TIMESTAMP(), :uid, :size)",
	[":h" => $sha256, ":id" => $assetId, ":src" => $source, ":uid" => $user->id, ":size" => $file["size"]]
);

die(json_encode(["status" => 200, "success" => true, "message" => "OK", "assetId" => (int) $assetId, "existing" => false]));