This repository has been archived on 2023-10-27. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-wip-uploader/upload.php
2023-04-15 19:47:36 +01:00

88 lines
2.5 KiB
PHP

<?php
header('Content-type:application/json;charset=utf-8'); // Set the response content type to JSON
$target_dir = "/home/beatsaber-wip-uploader/maps/";
/**
* Generates a random map id
*/
function generateMapId()
{
$mapId = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($i = 0; $i < 4; $i++) {
$mapId .= $characters[rand(0, strlen($characters) - 1)];
}
return $mapId;
}
/**
* Checks if the file is a valid beatsaber map
*/
function isValidBeatSaberMap($file)
{
$zip = new ZipArchive();
if ($zip->open($file) === true) {
if ($zip->locateName("info.dat", ZipArchive::FL_NOCASE) === false) {
return false;
}
$zip->close();
return true;
}
return false;
}
try {
$map = $_FILES["map"]; // the file to upload
if (!isset($map)) { // if the file is not set
header("Location: /?map=" . urlencode("No file was uploaded"));
die();
}
$mapId = generateMapId(); // the id of the map
$file = $map["tmp_name"]; // the temporary file path
$size = $map["size"]; // the size of the file
if ($size > 100000000) { // if the file is larger than 100MB
header("Location: /?map=" . urlencode("File is too large. Max file size is 100MB"));
die();
}
if (!isValidBeatSaberMap($file)) {
header("Location: /?map=" . urlencode("File is not a valid BeatSaber map. Please make sure you are uploading a .zip file"));
die();
}
$fileHash = hash_file("sha256", $file); // the hash of the file
$exists = false;
foreach (scandir($target_dir) as $scannedFile) { // scan the maps directory for a file with the same hash
if ($scannedFile == "." || $scannedFile == "..") { // ignore the . and .. files
continue;
}
if (hash_file("sha256", $target_dir . $scannedFile) == $fileHash) {
$mapId = pathinfo($scannedFile, PATHINFO_FILENAME);
$exists = true;
break;
}
}
if ($exists) { // if the file already exists, redirect to the existing file
header("Location: /?map=https://wip.fascinated.cc/maps/" . $mapId . ".zip");
die();
}
$target_file = $target_dir . $mapId . ".zip"; // the output file path
if (!move_uploaded_file($file, $target_file)) {
error_log("Error: Failed to move uploaded file from $file to $target_file");
header("Location: /?map=" . urlencode("Failed to upload file. If this error persists, please contact me on Discord: Fascinated#7668"));
die();
}
header("Location: /?map=https://wip.fascinated.cc/maps/" . $mapId . ".zip");
} catch (Exception $e) {
echo "There was an error uploading the file. Error: " . $e->getMessage();
die();
}