Compare commits

..

1 Commits

Author SHA1 Message Date
pizzaboxer 43a8a20a6e code 2022-12-31 16:11:25 +00:00
388 changed files with 3724 additions and 83613 deletions

4
.gitignore vendored
View File

@ -1,4 +0,0 @@
thumbs/assets/*
thumbs/avatars/*
asset/files/*
api/private/config.php

View File

@ -1,11 +0,0 @@
*
{
font-size: 12px;
font-family: 'Comic Sans MS', Verdana, Arial, Helvetica, sans-serif;
}
H1
{
font-weight: bold;
font-size: larger;
}

142
admin.php
View File

@ -1,138 +1,72 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
if(!SESSION || SESSION && !SESSION["adminLevel"]){ pageBuilder::errorCode(404); }
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\System;
use pizzaboxer\ProjectPolygon\PageBuilder;
$servermemory = general::getServerMemoryUsage();
$usersOnline = users::getUsersOnline();
Users::RequireAdmin();
$roles =
[
Users::STAFF_MODERATOR => "Moderator",
Users::STAFF_ADMINISTRATOR => "Administrator",
Users::STAFF_CATALOG => "Catalog Manager"
];
$servermemory = System::GetMemoryUsage();
$usersOnline = Users::GetUsersOnline();
$pendingRenders = Polygon::GetPendingRenders();
$usage = (object)
[
"Memory" => (object)
[
"Total" => System::GetFileSize($servermemory->total),
"SytemUsage" => System::GetFileSize($servermemory->total-$servermemory->free),
"PHPUsage" => System::GetFileSize(memory_get_usage(true))
],
"Disk" => (object)
[
"Total" => System::GetFileSize(disk_total_space("/")),
"SystemUsage" => System::GetFileSize(disk_total_space("/")-disk_free_space("/")),
"PolygonUsage" => System::GetFolderSize("/var/www/pizzaboxer.xyz/polygon/"),
"PolygonSharedUsage" => System::GetFolderSize("/var/www/pizzaboxer.xyz/polygonshared/"),
"ThumbnailUsage" => System::GetFolderSize("/var/www/pizzaboxer.xyz/polygoncdn/"),
]
];
$pageBuilder = new PageBuilder(["title" => SITE_CONFIG["site"]["name"]." Administration"]);
$pageBuilder->buildHeader();
pageBuilder::$pageConfig["title"] = SITE_CONFIG["site"]["name"]." Administration";
pageBuilder::buildHeader();
?>
<!--h1 style="position:absolute;opacity:0.5;font-size:10rem;z-index:10000000">THIS IS NOT <br> MULTAKOS SCREENSHOT LOL</h1-->
<h2 class="font-weight-normal"><?=SITE_CONFIG["site"]["name"]?> Administration</h2>
<h1 class="font-weight-normal"><?=SITE_CONFIG["site"]["name"]?> Administration</h1>
<div class="row">
<div class="col-md-7 divider-right">
<h3 class="pb-2 font-weight-normal">You are <?=vowel($roles[SESSION["user"]["adminlevel"]])?></h3>
<div class="row px-3 mb-2">
<?php if(Users::IsAdmin([Users::STAFF_MODERATOR, Users::STAFF_ADMINISTRATOR, Users::STAFF_CATALOG])) { ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-danger btn-lg btn-block px-0" href="/admin/moderate-user"><i class="fal fa-gavel"></i> Moderate user</a>
<div class="col-md-7 p-0 divider-right">
<div class="px-4 pr-4">
<h3 class="pb-2 font-weight-normal">Choose an action</h3>
<div class="row">
<div class="col-sm-4">
<!--a class="btn btn-outline-danger btn-lg w-100 px-0" href="moderate-user"><h2><i class="fal fa-gavel"></i></h2> User Moderation</a-->
</div>
<?php } ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-danger btn-lg btn-block px-0" href="/admin/moderate-assets"><i class="fal fa-file-exclamation"></i> Moderate assets</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/render-queue"><i class="fal fa-images"></i> Render queue</a>
</div>
<?php if(Users::IsAdmin(Users::STAFF_ADMINISTRATOR)) { ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/site-banners"><i class="fal fa-bullhorn"></i> Site banners</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/newsfeed"><i class="fal fa-rss-square"></i> Newsfeed</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/staff-audit"><i class="fal fa-book"></i> Audit log</a>
</div>
<div class="row">
<div class="col-md-4 py-2">
<a class="btn btn-outline-danger btn-lg w-100 px-0" href="/admin/moderate-user"><i class="fal fa-gavel"></i> User Moderation</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/error-log"><i class="fal fa-exclamation-triangle"></i> Error log</a>
<div class="col-md-4 py-2">
<a class="btn btn-outline-primary btn-lg w-100 px-0" href="/admin/staff-logs"><i class="fal fa-book"></i> Staff Logs</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-primary btn-lg btn-block px-0" href="/admin/manage-gameservers"><i class="fal fa-server"></i> Gameservers</a>
</div>
<?php } if(Users::IsAdmin([Users::STAFF_CATALOG, Users::STAFF_ADMINISTRATOR])) { ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-success btn-lg btn-block px-0" href="/admin/create-asset"><i class="fal fa-file-plus"></i> Create asset</a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-success btn-lg btn-block px-0" href="/admin/give-asset"><i class="fal fa-gift"></i> Give asset</a>
</div>
<?php } if(Users::IsAdmin(Users::STAFF_ADMINISTRATOR)) { ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-success btn-lg btn-block px-0" href="/admin/give-currency"><i class="fal fa-pizza-slice"></i> Give <?=SITE_CONFIG["site"]["currency"]?></a>
</div>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-success btn-lg btn-block px-0" href="#" onclick="polygon.buildModal({header: 'Credentials', body: '<span>You\'ll have to enter these yourself!</span> <br> Username: <code>ProjectPolygon</code> <br> Password: <code>962e8f89341b4e5f208076b5d06fb1b6</code>', buttons: [{class:'btn btn-primary px-4', attributes: {'onclick':'window.location = \'https://stats.pizzaboxer.xyz\''}, text:'Continue'}]})"><i class="fal fa-chart-pie"></i> Statistics</a>
<div class="col-md-4 py-2">
<a class="btn btn-outline-primary btn-lg w-100 px-0" href="/admin/site-banners"><i class="fal fa-bullhorn"></i> Site banners</a>
</div>
<?php if(SESSION["userId"] == 1){ ?>
<div class="col-md-4 py-2">
<a class="btn btn-outline-warning btn-lg w-100 px-0" href="/admin/give-currency"><i class="fal fa-pizza-slice"></i> Give <?=SITE_CONFIG["site"]["currencyName"]?></a>
</div>
<?php } ?>
<div class="col-md-4 py-2 px-1">
<a class="btn btn-outline-success btn-lg btn-block px-0" href="/admin/invites"><i class="fal fa-ticket-alt"></i> Invite Tickets</a>
</div>
</div>
</div>
</div>
<div class="col-md-5">
<h3 class="pb-3 font-weight-normal">Website / Server Info</h3>
<div class="col-md-5 p-0">
<div class="px-4 pr-4">
<h3 class="pb-3 font-weight-normal">Website / Server Info and Status</h3>
<div class="card w-100 mt-2">
<div class="card-body text-center">
<h3 class="font-weight-normal"><i class="fal fa-server"></i> <?=gethostname()?></h3>
<h3 class="font-weight-normal"><i class="fal fa-server"></i> <!--?=PHP_OS?> /--> <?=gethostname()?></h3>
<small><?=php_uname()?></small>
</div>
</div>
<div class="card w-100 mt-2">
<div class="card-body text-center">
<h3 class="font-weight-normal"><i class="fal fa-memory"></i> <?=$usage->Memory->SytemUsage?> / <?=$usage->Memory->Total?> In Use</h3>
<small><?=$usage->Memory->PHPUsage?> is being used by PHP</small>
<h3 class="font-weight-normal"><i class="fal fa-memory"></i> <?=general::getNiceFileSize($servermemory->total-$servermemory->free)?> / <?=general::getNiceFileSize($servermemory->total)?> In Use</h3>
<small><?=general::getNiceFileSize(memory_get_usage(true))?> is being used by PHP</small>
</div>
</div>
<div class="card w-100 mt-2">
<div class="card-body text-center">
<h3 class="font-weight-normal"><i class="fal fa-hdd"></i> <?=$usage->Disk->SystemUsage?> / <?=$usage->Disk->Total?> Used</h3>
<small>/polygon/ is using <?=$usage->Disk->PolygonUsage?></small><br>
<small>/polygonshared/ is using <?=$usage->Disk->PolygonSharedUsage?></small><br>
<small>/polygoncdn/ is using <?=$usage->Disk->ThumbnailUsage?></small><br>
<h3 class="font-weight-normal"><i class="fal fa-hdd"></i> <?=general::getNiceFileSize(disk_total_space("/")-disk_free_space("/"))?> / <?=general::getNiceFileSize(disk_total_space("/"))?> Used</h3>
<small><?=SITE_CONFIG["site"]["name"]?> is using <?=general::getNiceFileSize(general::getFolderSize("B:\\nginx\\www\\pizzaboxer.ml\\polygon"))?></small>
</div>
</div>
<div class="card w-100 mt-2">
<div class="card-body text-center">
<?php if(SITE_CONFIG["site"]["thumbserver"]) { ?>
<h3 class="font-weight-normal"><i class="fal fa-images"></i> <?=$pendingRenders?> asset renders pending</h3>
<?php } else { ?>
<h3 class="font-weight-normal"><i class="fal fa-images"></i> Thumbserver is disabled</h3>
<small>The thumbnail server has been manually disabled. <br> Go to /api/private/config.php to re-enable it.</small>
<?php } ?>
</div>
</div>
<div class="card w-100 mt-2">
<div class="card-body text-center">
<h3 class="font-weight-normal"><i class="fal fa-user"></i> <?=$usersOnline?> user<?=$usersOnline>1?'s':''?> currently online</h3>
<?php if($usersOnline == 1) { ?><small>dead much?</small><?php } ?>
</div>
</div>
</div>
</div>
</div>
<?php $pageBuilder->buildFooter(); ?>
<?php pageBuilder::buildFooter(); ?>

View File

@ -1 +0,0 @@
google.com, pub-3972374207754919, DIRECT, f08c47fec0942fa0

View File

@ -1,23 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$AssetID = API::GetParameter("POST", "AssetID", "int", false);
$DeleteQuery = Database::singleton()->run(
"DELETE FROM ownedAssets WHERE assetId = :AssetID AND userId = :UserID",
[":AssetID" => $AssetID, ":UserID" => SESSION["user"]["id"]]
);
if (!$DeleteQuery->rowCount())
API::respond(200, false, "You do not own this asset");
$assetCreatorId = Database::singleton()->run("SELECT creator FROM assets WHERE id = :assetId", [":assetId" => $AssetID])->fetchColumn();
if ($assetCreatorId != SESSION["user"]["id"])
Database::singleton()->run("UPDATE assets SET Sales = Sales - 1 WHERE id = :AssetID", [":AssetID" => $AssetID]);
API::respond(200, true, "OK");

View File

@ -1,72 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$page = API::GetParameter("POST", "page", "int", 1);
$wearing = API::GetParameter("POST", "wearing", "bool", false);
$type = API::GetParameter("POST", "type", "int", false);
if ($wearing)
{
$assetCount = Database::singleton()->run(
"SELECT COUNT(*) FROM ownedAssets WHERE userId = :userId AND wearing = 1",
[":userId" => SESSION["user"]["id"]]
)->fetchColumn();
}
else
{
$typeString = Catalog::GetTypeByNum($type);
if(!Catalog::GetTypeByNum($type)) API::respond(400, false, "Invalid asset type");
$assetCount = Database::singleton()->run(
"SELECT COUNT(*) FROM ownedAssets INNER JOIN assets ON assets.id = assetId WHERE userId = :userId AND assets.type = :assetType AND wearing = 0",
[":userId" => SESSION["user"]["id"], ":assetType" => $type]
)->fetchColumn();
}
$pagination = Pagination($page, $assetCount, 8);
if($pagination->Pages == 0)
{
API::respond(200, true, $wearing ? "You are not currently wearing anything" : "You don't currently have any unequipped " . plural($typeString) . " to wear. You can find more items over at the Catalog.");
}
if ($wearing)
{
$assets = Database::singleton()->run(
"SELECT assets.* FROM ownedAssets
INNER JOIN assets ON assets.id = assetId
WHERE userId = :userId AND wearing
ORDER BY last_toggle DESC LIMIT 8 OFFSET :offset",
[":userId" => SESSION["user"]["id"], ":offset" => $pagination->Offset]
);
}
else
{
$assets = Database::singleton()->run(
"SELECT assets.* FROM ownedAssets
INNER JOIN assets ON assets.id = assetId
WHERE userId = :userId AND assets.type = :assetType AND NOT wearing
ORDER BY timestamp DESC LIMIT 8 OFFSET :offset",
[":userId" => SESSION["user"]["id"], ":assetType" => $type, ":offset" => $pagination->Offset]
);
}
$items = [];
while ($asset = $assets->fetch(\PDO::FETCH_OBJ))
{
$items[] =
[
"url" => "/".encode_asset_name($asset->name)."-item?id=".$asset->id,
"item_id" => $asset->id,
"item_name" => htmlspecialchars($asset->name),
"item_thumbnail" => Thumbnails::GetAsset($asset)
];
}
die(json_encode(["success" => true, "message" => "OK", "pages" => $pagination->Pages, "items" => $items]));

View File

@ -1,25 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\RBXClient;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$bodyPart = API::GetParameter("POST", "bodyPart", ["Head", "Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg"]);
$color = API::GetParameter("POST", "color", "string");
$bodyColors = json_decode(SESSION["user"]["bodycolors"], true);
$brickcolor = RBXClient::HexToBrickColor(rgbtohex($color));
if(!$brickcolor) API::respond(200, false, "Invalid body color #".rgbtohex($color));
$bodyColors[$bodyPart] = $brickcolor;
$bodyColors = json_encode($bodyColors);
Database::singleton()->run(
"UPDATE users SET bodycolors = :bodycolors WHERE id = :userId",
[":bodycolors" => $bodyColors, ":userId" => SESSION["user"]["id"]]
);
API::respond(200, true, "OK");

View File

@ -1,11 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
Polygon::RequestRender("Avatar", SESSION["user"]["id"]);
API::respond(200, true, "OK");

View File

@ -1,65 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$assetId = API::GetParameter("POST", "assetId", "int");
$asset = Database::singleton()->run(
"SELECT wearing, assets.* FROM ownedAssets
INNER JOIN assets ON assets.id = assetId
WHERE userId = :userId AND assetId = :assetId",
[":userId" => SESSION["user"]["id"], ":assetId" => $assetId]
)->fetch();
if (!$asset) API::respond(200, false, "You do not own this asset");
if (in_array($asset["type"], [2, 11, 12, 17, 18])) // asset types that can only have one worn at a time
{
Database::singleton()->run(
"UPDATE ownedAssets
INNER JOIN assets ON assets.id = assetId
SET wearing = 0
WHERE userId = :userId AND type = :type",
[":userId" => SESSION["user"]["id"], ":type" => $asset["type"]]
);
if (!$asset["wearing"])
{
Database::singleton()->run(
"UPDATE ownedAssets
SET wearing = 1, last_toggle = UNIX_TIMESTAMP()
WHERE userId = :userId AND assetId = :assetId",
[":userId" => SESSION["user"]["id"], ":assetId" => $assetId]
);
}
}
else if (in_array($asset["type"], [8, 19]))
{
if ($asset["type"] == 8 && !$asset["wearing"]) // up to 3 hats can be worn at the same time
{
$equippedHats = Database::singleton()->run(
"SELECT COUNT(*) FROM ownedAssets
INNER JOIN assets ON assets.id = assetId
WHERE userId = :userId AND type = 8 AND wearing",
[":userId" => SESSION["user"]["id"]]
)->fetchColumn();
if ($equippedHats >= 5) API::respond(200, false, "You cannot wear more than 5 hats at a time");
}
Database::singleton()->run(
"UPDATE ownedAssets
SET wearing = NOT wearing, last_toggle = UNIX_TIMESTAMP()
WHERE userId = :userId AND assetId = :assetId",
[":userId" => SESSION["user"]["id"], ":assetId" => $assetId]
);
}
else
{
API::respond(200, false, "You cannot wear this asset!");
}
API::respond(200, true, "OK");

View File

@ -1,28 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "GET", "logged_in" => true]);
$items = [];
$friends = Database::singleton()->run(
"SELECT friends.*, users.username, users.id AS userId FROM friends
INNER JOIN users ON users.id = (CASE WHEN requesterId = :uid THEN receiverId ELSE requesterId END)
WHERE :uid IN (requesterId, receiverId) AND friends.status = 1",
[":uid" => SESSION["user"]["id"]]
);
while ($friend = $friends->fetch())
{
$items[] = [
"UserID" => (int)$friend["userId"],
"Username" => $friend["username"],
"TimeRequested" => date('c', $friend["timeSent"])
];
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . SESSION["user"]["id"] . '-friends.json"');
echo json_encode($items, JSON_PRETTY_PRINT);

View File

@ -1,137 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "GET", "logged_in" => true]);
$items = [];
$groups = Database::singleton()->run(
"SELECT * FROM groups WHERE creator = :uid",
[":uid" => SESSION["user"]["id"]]
);
while ($group = $groups->fetch())
{
// relationships
$relationships = Database::singleton()->run(
"SELECT groups_relationships.*, groups.id AS RelatingGroupID, groups.name AS RelatingGroupName FROM groups_relationships
INNER JOIN groups ON groups.id = (CASE WHEN Declarer = :groupId THEN Recipient ELSE Declarer END)
WHERE :groupId IN (Declarer, Recipient) AND Established IS NOT NULL",
[":groupId" => $group["id"]]
);
$groupRelationships = [];
while ($relationship = $relationships->fetch())
{
$groupRelationships[] = [
"Type" => $relationship["Type"],
"RelatingGroupID" => (int)$relationship["RelatingGroupID"],
"RelatingGroupName" => $relationship["RelatingGroupName"],
"TimeDeclared" => date('c', $relationship["Declared"]),
"TimeEstablished" => date('c', $relationship["Established"]),
"TimeBroken" => $relationship["Broken"] > 0 ? date('c', $relationship["Broken"]) : null,
];
}
// ranks
$ranks = Database::singleton()->run(
"SELECT * FROM groups_ranks WHERE GroupID = :groupId
ORDER BY rank ASC",
[":groupId" => $group["id"]]
);
$groupRanks = [];
while ($rank = $ranks->fetch())
{
$groupRanks[] = [
"Rank" => (int)$rank["Rank"],
"Name" => $rank["Name"],
"Description" => $rank["Description"],
"TimeCreated" => date('c', $rank["Created"]),
"Permissions" => json_decode($rank["Permissions"])
];
}
// members
$members = Database::singleton()->run(
"SELECT groups_members.*, users.username AS UserName FROM groups_members
INNER JOIN users ON users.id = UserID WHERE GroupID = :groupId",
[":groupId" => $group["id"]]
);
$groupMembers = [];
while ($member = $members->fetch())
{
$groupMembers[] = [
"UserID" => (int)$member["UserID"],
"UserName" => $member["UserName"],
"Rank" => (int)$member["Rank"],
"TimeJoined" => date('c', $member["Joined"])
];
}
// wall
$wallPosts = Database::singleton()->run(
"SELECT groups_wall.*, users.username AS PosterName FROM groups_wall
INNER JOIN users ON users.id = PosterID WHERE GroupID = :groupId",
[":groupId" => $group["id"]]
);
$groupWall = [];
while ($wallPost = $wallPosts->fetch())
{
$groupWall[] = [
"UserID" => (int)$wallPost["PosterID"],
"UserName" => $wallPost["PosterName"],
"Content" => $wallPost["Content"],
"TimePosted" => date('c', $wallPost["TimePosted"])
];
}
// audit
$auditLogs = Database::singleton()->run(
"SELECT groups_audit.*, users.username AS UserName FROM groups_audit
INNER JOIN users ON users.id = UserID WHERE GroupID = :groupId",
[":groupId" => $group["id"]]
);
$groupAudit = [];
while ($auditLog = $auditLogs->fetch())
{
$groupAudit[] = [
"UserID" => (int)$auditLog["UserID"],
"UserName" => $auditLog["UserName"],
"Category" => $auditLog["Category"],
"Description" => $auditLog["Description"],
"TimeCreated" => date('c', $auditLog["Time"])
];
}
$items[] = [
"ID" => (int)$group["id"],
"Name" => $group["name"],
"Description" => $group["description"],
"TimeCreated" => date('c', $group["created"]),
"Relationships" => $groupRelationships,
"Ranks" => $groupRanks,
"Members" => $groupMembers,
"Wall" => $groupWall,
"Audit" => $groupAudit
];
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . SESSION["user"]["id"] . '-groups.json"');
echo json_encode($items, JSON_PRETTY_PRINT);

View File

@ -1,45 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Catalog;
API::initialize(["method" => "GET", "logged_in" => true]);
$items = [];
$assets = Database::singleton()->run(
"SELECT assets.*, users.username,
ownedAssets.wearing, ownedAssets.last_toggle, ownedAssets.timestamp FROM ownedAssets
INNER JOIN assets ON assets.id = assetId
INNER JOIN users ON creator = users.id
WHERE userId = :uid",
[":uid" => SESSION["user"]["id"]]
);
while ($asset = $assets->fetch())
{
$items[] = [
"AssetID" => (int)$asset["id"],
"AssetName" => $asset["name"],
"AssetDescription" => $asset["description"],
"AssetType" => Catalog::GetTypeByNum($asset["type"]),
"AssetTypeID" => (int)$asset["type"],
"AssetSales" => (int)$asset["Sales"],
"AssetPrice" => (bool)$asset["sale"] ? (int)$asset["price"] : null,
"AssetIsForSale" => (bool)$asset["sale"],
"AssetIsCopylocked" => (bool)!$asset["publicDomain"],
"AssetCreatorID" => (int)$asset["creator"],
"AssetCreatorName" => $asset["username"],
"TimeAssetCreated" => date('c', $asset["created"]),
"TimeAssetUpdated" => date('c', $asset["updated"]),
"Wearing" => (bool)$asset["wearing"],
"TimeLastWorn" => $asset["last_toggle"] > 0 ? date('c', $asset["last_toggle"]) : null,
"TimeObtained" => date('c', $asset["timestamp"])
];
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . SESSION["user"]["id"] . '-inventory.json"');
echo json_encode($items, JSON_PRETTY_PRINT);

View File

@ -1,36 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Catalog;
API::initialize(["method" => "GET", "logged_in" => true]);
$items = [];
$transactions = Database::singleton()->run(
"SELECT transactions.*, users.username, users.id AS userId, assets.name, assets.type FROM transactions
INNER JOIN users ON users.id = (CASE WHEN seller = :UserID THEN purchaser ELSE seller END)
INNER JOIN assets ON assets.id = transactions.assetId
WHERE :UserID IN (seller, purchaser)",
[":UserID" => SESSION["user"]["id"]]
);
while ($transaction = $transactions->fetch())
{
$items[] = [
"TransactionType" => $transaction["seller"] == SESSION["user"]["id"] ? "Sale" : "Purchase",
"TransactionAmount" => (int)$transaction["amount"],
"TransactionUserID" => (int)$transaction["userId"],
"TransactionUsername" => $transaction["username"],
"AssetID" => (int)$transaction["assetId"],
"AssetName" => $transaction["name"],
"AssetType" => Catalog::GetTypeByNum($transaction["type"]),
"AssetTypeID" => (int)$transaction["type"],
"TimeTransacted" => date('c', $transaction["timestamp"])
];
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . SESSION["user"]["id"] . '-transactions.json"');
echo json_encode($items, JSON_PRETTY_PRINT);

View File

@ -1,20 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "secure" => true, "logged_in" => true]);
$sessionCount = Database::singleton()->run(
"SELECT COUNT(*) FROM sessions WHERE userId = :userId AND valid AND NOT sessionKey = :sessionKey",
[":userId" => SESSION["user"]["id"], ":sessionKey" => SESSION["sessionKey"]]
)->fetchColumn();
if (!$sessionCount) API::respond(200, false, "You currently only have one active session");
Database::singleton()->run(
"UPDATE sessions SET valid = 0 WHERE userId = :userId AND valid AND NOT sessionKey = :sessionKey",
[":userId" => SESSION["user"]["id"], ":sessionKey" => SESSION["sessionKey"]]
);
API::respond(200, true, "All of your other sessions have been invalidated");

View File

@ -0,0 +1,24 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
header("referrer-policy: same-origin");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
$userid = SESSION["userId"];
$sessionkey = $_COOKIE['polygon_session'];
$sesscount = $pdo->prepare("SELECT COUNT(*) FROM sessions WHERE userId = :uid AND valid AND NOT sessionKey = :key");
$sesscount->bindParam(":uid", $userid, PDO::PARAM_INT);
$sesscount->bindParam(":key", $sessionkey, PDO::PARAM_STR);
$sesscount->execute();
if(!$sesscount->fetchColumn()){ api::respond(400, false, "There are no other sessions to log out of!"); }
$query = $pdo->prepare("UPDATE sessions SET valid = 0 WHERE userId = :uid AND valid AND NOT sessionKey = :key");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":key", $sessionkey, PDO::PARAM_STR);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -1,125 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true]);
$FeedResults = Database::singleton()->run(
"SELECT feed.*, users.username FROM feed
INNER JOIN users ON users.id = feed.userId WHERE userId = :uid
OR groupId IS NULL AND userId IN
(
SELECT (CASE WHEN requesterId = :uid THEN receiverId ELSE requesterId END) FROM friends
WHERE :uid IN (requesterId, receiverId) AND status = 1
)
OR groupId IN
(
SELECT groups_members.GroupID FROM groups_members
INNER JOIN groups_ranks ON groups_ranks.GroupID = groups_members.GroupID AND groups_ranks.Rank = groups_members.Rank
WHERE groups_members.UserID = :uid AND groups_ranks.permissions LIKE '%\"CanViewGroupStatus\":true%'
)
ORDER BY feed.id DESC LIMIT 15",
[":uid" => SESSION["user"]["id"]]
);
/* $NewsResults = Database::singleton()->run(
"SELECT * FROM feed_news WHERE time_deleted IS NULL ORDER BY id DESC LIMIT 1"
);
$FetchNews = $NewsResults->fetch(PDO::FETCH_OBJ); */
$feed = [];
$news = [];
/* $news[] =
[
"header" => '<h4 class="font-weight-normal">'.$FetchNews->title.'</h4>',
"message" => Polygon::FilterText($markdown->setEmbedsEnabled(true)->text($FetchNews->body),false)
]; */
/*$news[] =
[
"header" => '<h4 class="font-weight-normal">this isn\'t dead!!!! (probably)</h4>',
"message" => "ive been more inclined to work on polygon now after like 4 months, so i guess development has resumed <br><br> 2fa has been implemented, and next on the roadmap is the catalog system. so yeah, stay tuned for that"
];*/
/* $news[] =
[
"header" => "",
"img" => "https://media.discordapp.net/attachments/745025397749448814/835635922590629888/HDKolobok-256px-3.gif",
// "message" => "What you know about KOLONBOK. ™ "
"message" => "KOLONBOK. ™ Has fix 2009"
]; */
/* $news[] =
[
"header" => "Groups have been released!",
"img" => "/img/ProjectPolygon.png",
"message" => "Groups have now been fully released, with more functionality than you could ever imagine. Groups don't cost anything to make, and you can join up to 20 of them. <br> If you haven't yet, come join the <a href=\"/groups?gid=1\">official group</a>!"
]; */
/* $news[] =
[
"header" => "",
"img" => "https://media.discordapp.net/attachments/745025397749448814/835635922590629888/HDKolobok-256px-3.gif",
"message" => "What you know about KOLONBOK. ™ "
]; */
while($row = $FeedResults->fetch(\PDO::FETCH_OBJ))
{
$timestamp = timeSince($row->timestamp);
if($row->groupId == NULL)
{
$feed[] =
[
"userName" => $row->username,
"img" => Thumbnails::GetAvatar($row->userId),
"header" => "<p class=\"m-0\"><a href=\"/user?ID={$row->userId}\">{$row->username}</a> - <small>{$timestamp}</small></p>",
"message" => Polygon::FilterText($row->text)
];
}
else
{
$GroupInfo = Groups::GetGroupInfo($row->groupId, true, true);
$GroupInfo->name = htmlspecialchars($GroupInfo->name);
$feed[] =
[
"userName" => $GroupInfo->name,
"img" => Thumbnails::GetAssetFromID($GroupInfo->emblem),
"header" => "<p class=\"m-0\"><a href=\"/groups?gid={$GroupInfo->id}\">{$GroupInfo->name}</a> - <small>posted by <a href=\"/user?ID={$row->userId}\">{$row->username}</a></small> - <small>{$timestamp}</small></p>",
"message" => Polygon::FilterText($row->text)
];
}
}
$FeedCount = $FeedResults->rowCount();
if($FeedCount < 15)
{
$feed[] =
[
"userName" => "Your feed is currently empty!",
"img" => "/img/feed/friends.png",
"header" => "<h4 class=\"font-weight-normal\">Looks like your feed's empty</h4>",
"message" => "If you haven't made any friends yet, <a href='/browse'>go make some</a>! <br> If you already have some, why don't you kick off the discussion?"
];
if($FeedCount < 14)
{
$feed[] =
[
"userName" => "Customize your character",
"img" => "/img/feed/cart.png",
"header" => "<h4 class=\"font-weight-normal\">Customize your character</h4>",
"message" => "Log in every day and earn 10 pizzas. Pizzas can be used to buy clothing in our <a href=\"/catalog\">catalog</a>. You can also create your own clothing on the <a href=\"/develop\">Build page</a>."
];
}
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "feed" => $feed, "news" => $news]);

View File

@ -1,35 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true]);
$userid = SESSION["user"]["id"];
$items = [];
$Places = Database::singleton()->run(
"SELECT assets.* FROM GameJobSessions
INNER JOIN GameJobs ON GameJobSessions.JobID = GameJobs.JobID
INNER JOIN assets ON assets.id = GameJobs.PlaceID
WHERE UserID = :UserID AND Verified
ORDER BY GameJobSessions.TimeCreated DESC LIMIT 12",
[":UserID" => SESSION["user"]["id"]]
);
while($Place = $Places->fetch(\PDO::FETCH_OBJ))
{
$items[] =
[
"PlaceID" => $Place->id,
"Name" => Polygon::FilterText($Place->name),
"Location" => "/" . encode_asset_name($Place->name) . "-place?id={$Place->id}",
"Thumbnail" => Thumbnails::GetAsset($Place, 768, 432),
"OnlinePlayers" => $Place->ActivePlayers
];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "items" => $items]);

View File

@ -1,62 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$userid = SESSION["user"]["id"];
$type = $_POST["type"] ?? false;
$Items = [];
if (!in_array($type, ["Purchases", "Sales"])) API::respond(400, false, "Bad Request");
if ($type == "Sales")
{
$SelfIdentifier = "seller";
$MemberIdentifier = "purchaser";
$Action = "sold";
}
else
{
$SelfIdentifier = "purchaser";
$MemberIdentifier = "seller";
$Action = "purchased";
}
$TransactionCount = Database::singleton()->run(
"SELECT COUNT(*) FROM transactions WHERE {$SelfIdentifier} = :UserID",
[":UserID" => SESSION["user"]["id"]]
)->fetchColumn();
$Pagination = Pagination($_POST["page"] ?? 1, $TransactionCount, 15);
if($Pagination->Pages == 0) API::respond(200, true, "You have not {$Action} any items!");
$Transactions = Database::singleton()->run(
"SELECT transactions.*, users.username, assets.name FROM transactions
INNER JOIN users ON users.id = {$MemberIdentifier} INNER JOIN assets ON assets.id = transactions.assetId
WHERE {$SelfIdentifier} = :UserID ORDER BY id DESC LIMIT 15 OFFSET :Offset",
[":UserID" => SESSION["user"]["id"], ":Offset" => $Pagination->Offset]
);
while($Transaction = $Transactions->fetch(\PDO::FETCH_OBJ))
{
$MemberID = $type == "Sales" ? $Transaction->purchaser : $Transaction->seller;
$Items[] =
[
"type" => $type == "Sales" ? "Sold" : "Purchased",
"date" => date('j/n/y', $Transaction->timestamp),
"member_name" => $Transaction->username,
"member_id" => $MemberID,
"member_avatar" => Thumbnails::GetAvatar($MemberID),
"asset_name" => Polygon::FilterText($Transaction->name),
"asset_id" => $Transaction->assetId,
"amount" => $Transaction->amount
];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "items" => $Items, "pages" => $Pagination->Pages]);

49
api/account/getFeed.php Normal file
View File

@ -0,0 +1,49 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
$userid = SESSION["userId"];
$query = $pdo->prepare("
SELECT * FROM feed
WHERE userId = :uid
OR userId IN (SELECT receiverId FROM friends WHERE requesterId = :uid AND status = 1)
OR userId IN (SELECT requesterId FROM friends WHERE receiverId = :uid AND status = 1)
ORDER BY id DESC LIMIT 15");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->execute();
$feed = [];
$news = [];
$news[] =
[
"header" => '<h4 class="font-weight-normal">lol</h4>',
"message" => 'fucked your mom'
];
while($row = $query->fetch(PDO::FETCH_OBJ))
{
$feed[] =
[
"userName" => users::getUserNameFromUid($row->userId),
"img" => "/thumbs/avatar?id=".$row->userId."&x=100&y=100",
"header" => '<p class="m-0"><a href="/user?ID='.$row->userId.'">'.users::getUserNameFromUid($row->userId).'</a> - <small>'.general::time_elapsed('@'.$row->timestamp).'</small></p>',
"message" => general::filterText($row->text)
];
}
if($query->rowCount() < 15)
{
$feed[] =
[
"userName" => "Your feed is currently empty!",
"img" => "/img/feed-starter.png",
"header" => '<h4 class="font-weight-normal">Looks like your feed\'s empty</h4>',
"message" => "If you haven't made any friends yet, <a href='/browse'>go make some</a>! <br> If you already have some, why don't you kick off the discussion?"
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "feed" => $feed, "news" => $news]));

View File

@ -1,23 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Password;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST['currentpwd']) || !isset($_POST['newpwd']) || !isset($_POST['confnewpwd'])) API::respond(400, false, "Bad Request");
$userid = SESSION["user"]["id"];
$row = (object)SESSION["user"];
$currentpwd = new Password($_POST['currentpwd']);
$newpwd = new Password($_POST['newpwd']);
if($row->lastpwdchange+1800 > time()) API::respond(200, false, "Please wait ".ceil((($row->lastpwdchange+1800)-time())/60)." minutes before attempting to change your password again");
if(!$currentpwd->verify($row->password)) API::respond(200, false, "Your current password does not match");
if($_POST['currentpwd'] == $_POST['newpwd']) API::respond(200, false, "Your new password cannot be the same as your current one");
if(strlen(preg_replace('/[0-9]/', "", $_POST['newpwd'])) < 6) API::respond(200, false, "Your new password is too weak. Make sure it contains at least six non-numeric characters");
if(strlen(preg_replace('/[^0-9]/', "", $_POST['newpwd'])) < 2) API::respond(200, false, "Your new password is too weak. Make sure it contains at least two numbers");
if($_POST['newpwd'] != $_POST['confnewpwd']) API::respond(200, false, "Confirmation password does not match");
$newpwd->update($userid);
API::respond(200, true, "OK");

View File

@ -1,8 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
Users::UpdatePing();
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "friendRequests" => (int)SESSION["user"]["PendingFriendRequests"]]);

View File

@ -1,25 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "secure" => true, "logged_in" => true]);
if(!isset($_POST['blurb']) || !isset($_POST['theme']) || !isset($_POST['filter'])) API::respond(400, false, "Bad Request");
$userid = SESSION["user"]["id"];
$filter = (int)($_POST['filter'] == 'enabled');
if(!in_array($_POST['theme'], ["light", "dark", "hitius", "2014"])) API::respond(200, false, "Invalid theme");
if(!strlen($_POST['blurb'])) API::respond(200, false, "Your blurb can't be empty");
if(strlen($_POST['blurb']) > 1000) API::respond(200, false, "Your blurb is too large");
if(Polygon::IsExplicitlyFiltered($_POST["blurb"])) API::respond(200, false, "Your blurb contains inappropriate text");
Database::singleton()->run(
"UPDATE users SET blurb = :blurb, filter = :filter, theme = :theme WHERE id = :uid",
[":uid" => $userid, ":blurb" => $_POST['blurb'], ":filter" => $filter, ":theme" => $_POST['theme']]
);
API::respond(200, true, "Your settings have been updated");

View File

@ -1,38 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\Discord;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$userId = SESSION["user"]["id"];
$status = $_POST['status'] ?? false;
if(!strlen($status)) API::respond(200, false, "Your status cannot be empty");
if(strlen($status) > 140) API::respond(200, false, "Your status cannot be more than 140 characters");
//ratelimit
$query = Database::singleton()->run(
"SELECT timestamp FROM feed WHERE userId = :uid AND groupID IS NULL AND timestamp+300 > UNIX_TIMESTAMP()",
[":uid" => $userId]
);
if($query->rowCount())
API::respond(200, false, "Please wait ".GetReadableTime($query->fetchColumn(), ["RelativeTime" => "5 minutes"])." before updating your status");
Database::singleton()->run("INSERT INTO feed (userId, timestamp, text) VALUES (:uid, UNIX_TIMESTAMP(), :status)", [":uid" => $userId, ":status" => $status]);
Database::singleton()->run("UPDATE users SET status = :status WHERE id = :uid", [":uid" => $userId, ":status" => $status]);
Discord::SendToWebhook(
[
"username" => SESSION["user"]["username"],
"content" => $status,
"avatar_url" => Thumbnails::GetAvatar(SESSION["user"]["id"])
],
Discord::WEBHOOK_KUSH
);
API::respond(200, true, "OK");

View File

@ -0,0 +1,56 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
header("referrer-policy: same-origin");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!isset($_POST['currentpwd'])){ api::respond(400, false, "Invalid Request"); }
if(!isset($_POST['newpwd'])){ api::respond(400, false, "Invalid Request"); }
if(!isset($_POST['confnewpwd'])){ api::respond(400, false, "Invalid Request"); }
$userid = SESSION["userId"];
$query = $pdo->prepare("SELECT * FROM users WHERE id = :uid");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
if($row->lastpwdchange+1800 > time())
{
api::respond(400, false, "Please wait ".ceil((($row->lastpwdchange+1800)-time())/60)." minutes before attempting to change your password again");
}
if(!password_verify($_POST['currentpwd'], $row->password))
{
api::respond(400, false, "Your current password does not match");
}
if($_POST['currentpwd'] == $_POST['newpwd'])
{
api::respond(400, false, "Your new password cannot be the same as your current one");
}
if(strlen(preg_replace('/[0-9]/', "", $_POST['newpwd'])) < 6)
{
api::respond(400, false, "Your new password is too weak. Make sure it contains at least six non-numeric characters");
}
if(strlen(preg_replace('/[^0-9]/', "", $_POST['newpwd'])) < 2)
{
api::respond(400, false, "Your new password is too weak. Make sure it contains at least two numbers");
}
if($_POST['newpwd'] != $_POST['confnewpwd'])
{
api::respond(400, false, "Confirmation password does not match");
}
$pwhash = password_hash($_POST['newpwd'], PASSWORD_BCRYPT);
$query = $pdo->prepare("UPDATE users SET password = :pwd, lastpwdchange = UNIX_TIMESTAMP() WHERE id = :uid");
$query->bindParam(":pwd", $pwhash, PDO::PARAM_STR);
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -0,0 +1,10 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
header("referrer-policy: same-origin");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(users::updatePing() && users::updateCurrencyStipend()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -0,0 +1,26 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
header("referrer-policy: same-origin");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!isset($_POST['blurb'])){ api::respond(400, false, "Invalid Request"); }
if(!isset($_POST['pageanimations'])){ api::respond(400, false, "Invalid Request"); }
if(!isset($_POST['filter'])){ api::respond(400, false, "Invalid Request"); }
$userid = SESSION["userId"];
$filter = $_POST['filter'] == 'false' ? false : true;
$pageanim = $_POST['pageanimations'] == 'false' ? false : true;
if(!strlen($_POST['blurb'])){ api::respond(400, false, "Your blurb can't be empty!"); }
if(strlen($_POST['blurb']) > 1000){ api::respond(400, false, "Your blurb is too large!"); }
$query = $pdo->prepare("UPDATE users SET blurb = :blurb, filter = :filter, pageanim = :pageanim WHERE id = :uid");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":blurb", $_POST['blurb'], PDO::PARAM_STR);
$query->bindParam(":pageanim", $pageanim, PDO::PARAM_INT);
$query->bindParam(":filter", $filter, PDO::PARAM_INT);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -0,0 +1,33 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
header("referrer-policy: same-origin");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!isset($_POST['status'])){ api::respond(405, false, "Method Not Allowed"); }
$userId = SESSION["userId"];
$status = trim($_POST['status']);
if(!$status){ api::respond(405, false, "Your status cannot be empty"); }
if(strlen($status) > 140){ api::respond(405, false, "Your status cannot be more than 140 characters"); }
//ratelimit
$query = $pdo->prepare("SELECT timestamp FROM feed WHERE userId = :uid AND timestamp+60 > UNIX_TIMESTAMP()");
$query->bindParam(":uid", $userId, PDO::PARAM_INT);
$query->execute();
if($query->rowCount()){ api::respond(400, false, "Please wait ".(($query->fetchColumn()+60)-time())." seconds before updating your status"); }
$query = $pdo->prepare("INSERT INTO feed (userId, timestamp, text) VALUES (:uid, UNIX_TIMESTAMP(), :status)");
$query->bindParam(":uid", $userId, PDO::PARAM_INT);
$query->bindParam(":status", $status, PDO::PARAM_STR);
$query->execute();
$query = $pdo->prepare("UPDATE users SET status = :status WHERE id = :uid");
$query->bindParam(":uid", $userId, PDO::PARAM_INT);
$query->bindParam(":status", $status, PDO::PARAM_STR);
$query->execute();
api::respond(200, true, "OK");

31
api/admin/addBanner.php Normal file
View File

@ -0,0 +1,31 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!SESSION["adminLevel"]){ api::respond(400, false, "Not an administrator"); }
api::lastAdminAction();
if(!isset($_POST["text"]) || !isset($_POST["bg-color"]) || !isset($_POST["text-color"])){ api::respond(400, false, "Invalid Request"); }
if($_POST["text-color"] != "dark" && $_POST["text-color"] != "light"){ api::respond(400, false, "Invalid Request"); }
if(!trim($_POST["text"])){ api::respond(400, false, "You haven't set the banner text"); }
if(strlen($_POST["text"]) > 128){ api::respond(400, false, "The banner text must be less than 128 characters"); }
if(!trim($_POST["bg-color"])){ api::respond(400, false, "You haven't set a background color"); }
if(!ctype_xdigit(ltrim($_POST["bg-color"], "#")) || strlen($_POST["bg-color"]) != 7){ api::respond(400, false, "That doesn't appear to be a valid hex color"); }
if($pdo->query("SELECT COUNT(*) FROM announcements WHERE activated")->fetchColumn() > 5){ api::respond(400, false, "There's too many banners currently active!"); }
$userId = SESSION["userId"];
$text = trim($_POST["text"]);
$color = trim($_POST["bg-color"]);
$textcolor = "text-".trim($_POST["text-color"]);
$query = $pdo->prepare("INSERT INTO announcements (createdBy, text, bgcolor, textcolor) VALUES (:uid, :text, :bgc, :tc)");
$query->bindParam(":uid", $userId, PDO::PARAM_INT);
$query->bindParam(":text", $text, PDO::PARAM_STR);
$query->bindParam(":bgc", $color, PDO::PARAM_STR);
$query->bindParam(":tc", $textcolor, PDO::PARAM_STR);
$query->execute();
users::logStaffAction("[ Banners ] Created site banner with text: ".$text);
api::respond(200, true, "Banner has been created");

View File

@ -1,103 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Gzip;
if (!isset($_GET["mode"]) || !in_array($_GET["mode"], ["versions", "data"])) die(http_response_code(400));
if (!isset($_GET["id"]) || !is_numeric($_GET["id"])) die(http_response_code(400));
if ($_GET["mode"] == "data")
{
header("content-type: text/plain");
if (isset($_GET["version"]) && !is_numeric($_GET["version"])) die(http_response_code(400));
/* $curl = curl_init();
curl_setopt_array($curl,
[
CURLOPT_URL => "https://assetdelivery.roblox.com/v1/asset/?id=".$_GET["id"].(isset($_GET["version"]) ? "&version=".$_GET["version"] : ""),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPHEADER => ["User-Agent: Roblox/WinInet"]
]);
$Data = curl_exec($curl);
$StatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
http_response_code($StatusCode);
die($Data); */
$context = stream_context_create(
[
'http' =>
[
'method' => 'GET',
'header' => 'User-Agent: Roblox/WinInet',
'ignore_errors' => true
]
]);
$response = file_get_contents("https://assetdelivery.roblox.com/v1/asset/?id=".$_GET["id"].(isset($_GET["version"]) ? "&version=".$_GET["version"] : ""), false, $context);
if ($http_response_header[0] == "HTTP/1.1 302 Found")
{
$http_response_header[0] = "HTTP/1.0 200 OK";
}
header($http_response_header[0]);
if (Gzip::IsGzEncoded($response))
die(gzdecode($response));
else
die($response);
}
else
{
header("content-type: application/json");
$Versions = [];
$Version = 0;
while (true)
{
$Version++;
$curl = curl_init();
curl_setopt_array($curl,
[
CURLOPT_URL => "https://assetdelivery.roblox.com/v1/asset/?id=".$_GET["id"]."&version=".$Version,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => ["User-Agent: Roblox/WinInet"]
]);
$Data = curl_exec($curl);
$StatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($StatusCode == 500) continue;
if ($StatusCode != 200) break;
$HeaderSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$HeadersText = substr($Data, 0, $HeaderSize);
$CDNHeadersText = explode("\r\n\r\n", $HeadersText)[1];
$CDNHeadersArray = [];
foreach (explode("\r\n", $CDNHeadersText) as $i => $line)
{
if ($i === 0)
{
$CDNHeadersArray['http_code'] = $line;
}
else
{
list ($key, $value) = explode(': ', $line);
$CDNHeadersArray[$key] = $value;
}
}
$Versions[$Version] = $CDNHeadersArray["last-modified"];
}
die(json_encode($Versions));
}

View File

@ -1,25 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Polygon;
API::initialize(["method" => "POST", "admin" => Users::STAFF_ADMINISTRATOR, "admin_ratelimit" => true, "secure" => true]);
if(!isset($_POST["id"])){ API::respond(400, false, "Invalid Request"); }
$postID = $_POST["id"];
$query = Database::singleton()->run("SELECT * FROM feed_news WHERE time_deleted IS NOT NULL AND id = :id", [":id" => $postID]);
$postInfo = $query->fetch(PDO::FETCH_OBJ);
if(!$postInfo) { API::respond(400, false, "Bad Request"); }
Database::singleton()->run(
"UPDATE feed_news SET time_deleted = UNIX_TIMESTAMP() WHERE id = :id)",
[":id" => $id]
);
Users::LogStaffAction("[ Feed ] ".SESSION["user"]["username"]." deleted a post titled ".Polygon::FilterText($postInfo->title).". ( user ID ".SESSION["user"]["id"]." ) ( Reason: N/A )");
API::respond(200, true, "Deleted successfully.");

View File

@ -1,31 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Forum;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => [Users::STAFF_MODERATOR, Users::STAFF_ADMINISTRATOR], "admin_ratelimit" => true, "secure" => true]);
$postType = API::GetParameter("POST", "postType", ["thread", "reply"]);
$postId = API::GetParameter("POST", "postId", "int");
$isThread = ($postType == "thread");
$post = $isThread ? Forum::GetThreadInfo($postId) : Forum::GetReplyInfo($postId);
if (!$post) API::respond(200, false, "Post does not exist");
if ($isThread)
{
Database::singleton()->run("UPDATE forum_threads SET deleted = 1 WHERE id = :postId", [":postId" => $postId]);
Database::singleton()->run("UPDATE users SET ForumThreads = ForumThreads - 1 WHERE id = :userId", [":userId" => $post->author]);
Users::LogStaffAction("[ Forums ] Deleted forum thread ID {$postId}");
}
else
{
Database::singleton()->run("UPDATE forum_replies SET deleted = 1 WHERE id = :postId", [":postId" => $postId]);
Database::singleton()->run("UPDATE users SET ForumReplies = ForumReplies - 1 WHERE id = :userId", [":userId" => $post->author]);
Users::LogStaffAction("[ Forums ] Deleted forum reply ID {$postId}");
}
API::respond(200, true, "OK");

View File

@ -0,0 +1,25 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!SESSION["adminLevel"]){ api::respond(400, false, "Not an administrator"); }
if(!isset($_POST['postType'])){ api::respond(400, false, "Invalid Request"); }
if(!in_array($_POST['postType'], ["thread", "reply"])){ api::respond(400, false, "Invalid Request"); }
if(!isset($_POST['postId'])){ api::respond(400, false, "Invalid Request"); }
if(!is_numeric($_POST['postId'])){ api::respond(400, false, "Invalid Request"); }
$userid = SESSION["userId"];
$isThread = $_POST['postType'] == "thread";
$threadInfo = $isThread ? forum::getThreadInfo($_POST['postId']) : forum::getReplyInfo($_POST['postId']);
if(!$threadInfo){ api::respond(400, false, "Post does not exist"); }
api::lastAdminAction();
$query = $isThread ? $pdo->prepare("UPDATE forum_threads SET deleted = 1 WHERE id = :id") : $pdo->prepare("UPDATE forum_replies SET deleted = 1 WHERE id = :id");
$query->bindParam(":id", $_POST['postId'], PDO::PARAM_INT);
if($query->execute()){ users::logStaffAction("[ Forums ] Deleted forum ".($isThread?"thread":"reply")." ID ".$_POST['postId']); api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -1,7 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Password;
$password = $_GET["password"] ?? "";
$auth = new Password($password);
echo $auth->create();

View File

@ -1,46 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => [Users::STAFF_CATALOG, Users::STAFF_ADMINISTRATOR], "logged_in" => true, "secure" => true]);
$page = API::GetParameter("POST", "page", "int", 1);
$type = API::GetParameter("POST", "type", "int");
if (!Catalog::GetTypeByNum($type)) API::respond(200, false, "Invalid asset type");
$assetCount = Database::singleton()->run(
"SELECT COUNT(*) FROM assets WHERE creator = 2 AND type = :type ORDER BY id DESC",
[":type" => $type]
)->fetchColumn();
$pagination = Pagination($page, $assetCount, 15);
$assets = Database::singleton()->run(
"SELECT * FROM assets WHERE creator = 2 AND type = :type ORDER BY id DESC LIMIT 15 OFFSET :offset",
[":type" => $type, ":offset" => $pagination->Offset]
);
$items = [];
while ($asset = $assets->fetch(\PDO::FETCH_OBJ))
{
$info = Catalog::GetAssetInfo($asset->id);
$items[] =
[
"name" => htmlspecialchars($asset->name),
"id" => $asset->id,
"thumbnail" => Thumbnails::GetAsset($asset),
"item_url" => "/".encode_asset_name($asset->name)."-item?id=".$asset->id,
"config_url" => "/my/item?ID=".$asset->id,
"created" => date("j/n/Y", $asset->created),
"sales-total" => $info->Sales,
"sales-week" => 0 //$info->sales_week
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $pagination->Pages, "assets" => $items]));

View File

@ -1,64 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => Users::STAFF, "secure" => true]);
$id = $_POST["id"];
$category = $_POST["category"];
$type = $_POST["type"] ?? false;
$page = $_POST["page"] ?? 1;
$result = [];
if(!in_array($category, ["User", "Asset"])) API::respond(400, false, "Bad Request");
if(!in_array($type, ["Purchases", "Sales"])) API::respond(400, false, "Bad Request");
if ($category == "User")
{
$selector = $type == "Sales" ? "seller" : "purchaser";
$member = $type == "Sales" ? "purchaser" : "seller";
}
else if ($category == "Asset")
{
$selector = "assetId";
$member = "purchaser";
}
$count = Database::singleton()->run("SELECT COUNT(*) FROM transactions WHERE $selector = :id", [":id" => $id])->fetchColumn();
$pages = ceil($count/15);
$offset = ($page - 1)*15;
$transactions = Database::singleton()->run(
"SELECT transactions.*, users.username, assets.name FROM transactions
INNER JOIN users ON $member = users.id
INNER JOIN assets ON transactions.assetId = assets.id
WHERE $selector = :id ORDER BY id DESC LIMIT 15 OFFSET $offset",
[":id" => $id]
);
if(!$transactions->rowCount()) API::respond(200, true, "No transactions have been logged");
while($transaction = $transactions->fetch(\PDO::FETCH_OBJ))
{
$memberID = $member == "purchaser" ? $transaction->purchaser : $transaction->seller;
$result[] =
[
"type" => $type == "Sales" ? "Sold" : "Purchased",
"date" => date('j/n/y', $transaction->timestamp),
"member_name" => $transaction->username,
"member_id" => $memberID,
"member_avatar" => Thumbnails::GetAvatar($memberID),
"asset_name" => htmlspecialchars($transaction->name),
"asset_id" => $transaction->assetId,
"amount" => $transaction->amount,
"flagged" => (bool) $transaction->flagged
];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "transactions" => $result, "pages" => $pages]);

View File

@ -1,47 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Database;
API::initialize(["method" => "POST", "admin" => Users::STAFF, "secure" => true]);
$page = $_POST["page"] ?? 1;
$assets = [];
$assetCount = Database::singleton()->run("SELECT COUNT(*) FROM assets WHERE NOT approved AND type != 1")->fetchColumn();
$pagination = Pagination($page, $assetCount, 18);
if(!$pagination->Pages) API::respond(200, true, "There are no assets to approve");
$assets = Database::singleton()->run(
"SELECT assets.*, users.username FROM assets
INNER JOIN users ON creator = users.id
WHERE NOT approved AND type != 1
LIMIT 18 OFFSET :offset",
[":offset" => $pagination->Offset]
);
$items = [];
while ($asset = $assets->fetch(\PDO::FETCH_OBJ))
{
$items[] =
[
"url" => "item?ID=".$asset->id,
"item_id" => $asset->id,
"item_name" => htmlspecialchars($asset->name),
"item_thumbnail" => Thumbnails::GetAsset($asset, 420, 420, true),
"texture_id" => $asset->type == 22 ? $asset->id : $asset->imageID,
"creator_id" => $asset->creator,
"creator_name" => $asset->username,
"type" => Catalog::GetTypeByNum($asset->type),
"created" => date("j/n/y G:i A", $asset->created),
"price" => $asset->sale ? $asset->price ? '<i class="fal fa-pizza-slice"></i> '.$asset->price : "Free" : "Off-Sale"
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $pagination->Pages, "assets" => $items]));

View File

@ -1,39 +0,0 @@
<?php
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Discord;
header("content-type: text/plain");
// this should only be used if core.php does not work
$emergency = ($_GET["key"] ?? false) == "D5F6E2EAA6C07C991CA2895920A8BBA8BB66CA16";
$output = "";
$webhook = "";
$output_array = [];
if($emergency)
{
require $_SERVER["DOCUMENT_ROOT"]."/api/private/classes/pizzaboxer/ProjectPolygon/Discord.php";
$webhook .= sprintf("[%s] Git Pull intiated by %s on %s\n", date('d/m/Y h:i:s A'), "[[[OVERRIDE]]]", $_SERVER["HTTP_HOST"]);
}
else
{
require $_SERVER["DOCUMENT_ROOT"]."/api/private/core.php";
if(!Users::IsAdmin(Users::STAFF_ADMINISTRATOR)) die(http_response_code(404));
$webhook .= sprintf("[%s] Git Pull executed by %s on %s\n", date('d/m/Y h:i:s A'), SESSION["user"]["username"], $_SERVER["HTTP_HOST"]);
}
exec("git pull 2>&1", $output_array, $exitcode);
foreach($output_array as $line) $output .= "$line\n";
if($exitcode != 0) $output .= "\n\nGit exited with code $exitcode";
echo $output;
$webhook .= "```yaml\n";
$webhook .= $output;
$webhook .= "```";
Discord::SendToWebhook(["content" => $webhook], Discord::WEBHOOK_POLYGON_GITPULL, false);

View File

@ -1,30 +1,30 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!SESSION["adminLevel"]){ api::respond(400, false, "Not an administrator"); }
if(SESSION["userId"] != 1){ api::respond(400, false, "Insufficient admin level"); }
api::lastAdminAction();
if(!isset($_POST["username"]) || !isset($_POST["amount"]) || !isset($_POST["reason"])){ api::respond(400, false, "Invalid Request"); }
if(!trim($_POST["username"])){ api::respond(400, false, "You haven't set a username"); }
API::initialize(["method" => "POST", "admin" => Users::STAFF_ADMINISTRATOR, "admin_ratelimit" => true, "secure" => true]);
if(!$_POST["amount"]){ api::respond(400, false, "You haven't set the amount of ".SITE_CONFIG["site"]["currencyName"]." to give"); }
if(!is_numeric($_POST["amount"])){ api::respond(400, false, "The amount of ".SITE_CONFIG["site"]["currencyName"]." to give must be numerical"); }
if($_POST["amount"] > 500 || $_POST["amount"] < -500){ api::respond(400, false, "Maximum amount of ".SITE_CONFIG["site"]["currencyName"]." you can give/take is 500 at a time"); }
if(SESSION["user"]["id"] != 6){ API::respond(400, false, "Insufficient admin level"); }
if(!isset($_POST["username"]) || !isset($_POST["amount"]) || !isset($_POST["reason"])){ API::respond(400, false, "Invalid Request"); }
if(!trim($_POST["username"])){ API::respond(400, false, "You haven't set a username"); }
if(!$_POST["amount"]){ API::respond(400, false, "You haven't set the amount of ".SITE_CONFIG["site"]["currency"]." to give"); }
if(!is_numeric($_POST["amount"])){ API::respond(400, false, "The amount of ".SITE_CONFIG["site"]["currency"]." to give must be numerical"); }
if($_POST["amount"] > 20000 || $_POST["amount"] < -500){ API::respond(400, false, "Maximum amount of ".SITE_CONFIG["site"]["currency"]." you can give/take is 500 at a time"); }
if(!trim($_POST["reason"])){ API::respond(400, false, "You must set a reason"); }
if(!trim($_POST["reason"])){ api::respond(400, false, "You must set a reason"); }
$amount = $_POST["amount"];
$userInfo = Users::GetInfoFromName($_POST["username"]);
if(!$userInfo){ API::respond(400, false, "That user doesn't exist"); }
if(($userInfo->currency + $_POST["amount"]) < 0){ API::respond(400, false, "That'll make the user go bankrupt!"); }
$userInfo = users::getUserInfoFromUserName($_POST["username"]);
if(!$userInfo){ api::respond(400, false, "That user doesn't exist"); }
if(($userInfo->currency + $_POST["amount"]) < 0){ api::respond(400, false, "That'll make the user go bankrupt!"); }
Database::singleton()->run(
"UPDATE users SET currency = currency+:amount WHERE id = :uid",
[":amount" => $amount, ":uid" => $userInfo->id]
);
$query = $pdo->prepare("UPDATE users SET currency = currency+:amount WHERE id = :uid");
$query->bindParam(":amount", $amount, PDO::PARAM_INT);
$query->bindParam(":uid", $userInfo->id, PDO::PARAM_INT);
$query->execute();
Users::LogStaffAction("[ Currency ] Gave ".$_POST["amount"]." ".SITE_CONFIG["site"]["currency"]." to ".$userInfo->username." ( user ID ".$userInfo->id." ) ( Reason: ".$_POST["reason"]." )");
API::respond(200, true, "Gave ".$_POST["amount"]." ".SITE_CONFIG["site"]["currency"]." to ".$userInfo->username);
users::logStaffAction("[ Currency ] Gave ".$_POST["amount"]." ".SITE_CONFIG["site"]["currencyName"]." to ".$userInfo->username." ( user ID ".$userInfo->id." ) ( Reason: ".$_POST["reason"]." )");
api::respond(200, true, "Gave ".$_POST["amount"]." ".SITE_CONFIG["site"]["currencyName"]." to ".$userInfo->username);

View File

@ -1,41 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => Users::STAFF, "admin_ratelimit" => true, "secure" => true]);
$assetId = $_POST['assetID'] ?? false;
$action = $_POST['action'] ?? false;
$action_sql = $action == "approve" ?: 2;
$reason = $_POST['reason'] ?? false;
$asset = Catalog::GetAssetInfo($assetId);
if (!in_array($action, ["approve", "decline"])) API::respond(400, false, "Invalid request");
if (!$asset) API::respond(200, false, "Asset does not exist");
if ($action == "approve" && $asset->approved == 1) API::respond(200, false, "This asset has already been approved");
if ($action == "disapprove" && $asset->approved == 2) API::respond(200, false, "This asset has already been disapproved");
if ($action == "approve" && $asset->approved == 2) API::respond(200, false, "Disapproved assets cannot be reapproved");
Database::singleton()->run(
"UPDATE assets SET approved = :action WHERE id IN (:id, :image)",
[":action" => $action_sql, ":id" => $asset->id, ":image" => $asset->imageID]
);
if ($action == "decline")
{
Thumbnails::DeleteAsset($asset->id);
Catalog::DeleteAsset($asset->id);
if ($asset->imageID != NULL)
{
Catalog::DeleteAsset($asset->imageID);
Thumbnails::DeleteAsset($asset->imageID);
}
}
Users::LogStaffAction('[ Asset Moderation ] '.ucfirst($action).'d "'.$asset->name.'" [ID '.$asset->id.']'.($reason ? ' with reason: '.$reason : ''));
API::respond(200, true, '"'.htmlspecialchars($asset->name).'" has been '.$action.'d');

View File

@ -1,90 +1,64 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => [Users::STAFF_MODERATOR, Users::STAFF_CATALOG, Users::STAFF_ADMINISTRATOR], "admin_ratelimit" => true, "secure" => true]);
if(!isset($_POST["username"]) || !isset($_POST["banType"]) || !isset($_POST["moderationNote"]) || !isset($_POST["until"]) || !isset($_POST["deleteUsername"])) API::respond(400, false, "Bad Request");
if($_POST["banType"] < 1 || $_POST["banType"] > 4) API::respond(400, false, "Bad Request");
if($_POST["banType"] != 4 && empty($_POST["moderationNote"])) API::respond(200, false, "You must supply a reason");
if(!trim($_POST["username"])) API::respond(200, false, "You haven't set the username to ban");
if($_POST["banType"] == 2 && empty($_POST["until"])) API::respond(200, false, "Ban time not set");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!SESSION["adminLevel"]){ api::respond(400, false, "Not an administrator"); }
if(!isset($_POST["username"]) || !isset($_POST["banType"]) || !isset($_POST["moderationNote"]) || !isset($_POST["until"])){ api::respond(400, false, "Invalid Request"); }
if($_POST["banType"] < 1 || $_POST["banType"] > 4){ api::respond(400, false, "Invalid Request"); }
if($_POST["banType"] != 4 && !trim($_POST["moderationNote"])){ api::respond(400, false, "You must supply a reason"); }
if(!trim($_POST["username"])){ api::respond(400, false, "You haven't set the username to ban"); }
if($_POST["banType"] == 2 && !trim($_POST["until"])){ api::respond(400, false, "Ban time not set"); }
$banType = $_POST["banType"];
$staffNote = isset($_POST["staffNote"]) && $_POST["staffNote"] ? $_POST["staffNote"] : "";
$userId = SESSION["user"]["id"];
$reason = $_POST["moderationNote"];
$staffNote = isset($_POST["staffNote"]) && trim($_POST["staffNote"]) ? trim($_POST["staffNote"]) : "";
$userId = SESSION["userId"];
$bannerInfo = users::getUserInfoFromUserName($_POST["username"]);
$reason = trim($_POST["moderationNote"]);
$bannedUntil = $_POST["banType"] == 2 ? strtotime($_POST["until"]." ".date('G:i:s')) : 0;
$deleteUsername = (int)($_POST["deleteUsername"] == "true");
if (strpos($_POST["username"], ",") === false)
if(!$bannerInfo){ api::respond(400, false, "User does not exist"); }
api::lastAdminAction();
if($banType == 4)
{
$result = BanUser(Users::GetInfoFromName($_POST["username"]));
if($result !== true) API::respond(200, false, $result);
if(!users::getUserModeration($bannerInfo->id)){ api::respond(400, false, "That user isn't banned!"); }
users::undoUserModeration($bannerInfo->id, true);
}
else
{
foreach (explode(",", $_POST["username"]) as $BannerID)
{
BanUser(Users::GetInfoFromID($BannerID));
}
}
if($bannerInfo->id == $userId){ api::respond(400, false, "You cannot moderate yourself!"); }
if($bannerInfo->adminlevel){ api::respond(400, false, "You cannot moderate a staff member"); }
if(users::getUserModeration($bannerInfo->id)){ api::respond(400, false, "That user is already banned!"); }
if($banType == 2 && $bannedUntil < strtotime('tomorrow')){ api::respond(400, false, "Ban time must be at least 1 day long"); }
function BanUser($bannerInfo)
{
global $banType, $staffNote, $userId, $reason, $bannedUntil, $deleteUsername;
if(!$bannerInfo) return "User does not exist";
if($banType == 4)
{
if(!Users::GetUserModeration($bannerInfo->id)) return "That user isn't banned!";
Users::UndoUserModeration($bannerInfo->id, true);
}
else
{
if($bannerInfo->id == $userId) return "You cannot moderate yourself";
if($bannerInfo->adminlevel > 0) return "You cannot moderate a staff member";
if(Users::GetUserModeration($bannerInfo->id)) return "That user is already banned!";
if($banType == 2 && $bannedUntil < strtotime('tomorrow')) return "Ban time must be at least 1 day long";
Database::singleton()->run(
"INSERT INTO bans (userId, bannerId, timeStarted, timeEnds, reason, banType, note)
VALUES (:bid, :uid, UNIX_TIMESTAMP(), :ends, :reason, :type, :note);
UPDATE users SET Banned = 1 WHERE id = :bid;",
[":bid" => $bannerInfo->id, ":uid" => $userId, ":ends" => $bannedUntil, ":reason" => $reason, ":type" => $banType, ":note" => $staffNote]
);
}
if ($deleteUsername && $banType != 4)
{
Database::singleton()->run(
"UPDATE users SET username = :Username WHERE id = :UserID",
[":Username" => "[ Content Deleted {$bannerInfo->id} ]", ":UserID" => $bannerInfo->id]
);
}
$staff =
[
1 => "Warned " . $bannerInfo->username,
2 => "Banned " . $bannerInfo->username . " for " . GetReadableTime($bannedUntil, ["Ending" => false]),
3 => "Permanently banned " . $bannerInfo->username,
4 => "Unbanned " . $bannerInfo->username
];
Users::LogStaffAction("[ User Moderation ] ".$staff[$banType]." ( user ID ".$bannerInfo->id." )");
return true;
$query = $pdo->prepare("INSERT INTO bans (userId, bannerId, timeStarted, timeEnds, reason, banType, note) VALUES (:bid, :uid, UNIX_TIMESTAMP(), :ends, :reason, :type, :note)");
$query->bindParam(":bid", $bannerInfo->id, PDO::PARAM_INT);
$query->bindParam(":uid", $userId, PDO::PARAM_INT);
$query->bindParam(":ends", $bannedUntil, PDO::PARAM_INT);
$query->bindParam(":reason", $reason, PDO::PARAM_STR);
$query->bindParam(":type", $banType, PDO::PARAM_INT);
$query->bindParam(":note", $staffNote, PDO::PARAM_STR);
$query->execute();
}
$text =
[
1 => "warned",
2 => "banned for " . GetReadableTime($bannedUntil, ["Ending" => false]),
2 => "banned for ".general::time_elapsed("@".($bannedUntil+1), false, false),
3 => "permanently banned",
4 => "unbanned"
];
API::respond(200, true, $_POST["username"]." has been ".$text[$banType]);
$staff =
[
1 => "Warned ".$bannerInfo->username,
2 => "Banned ".$bannerInfo->username." for ".general::time_elapsed("@".($bannedUntil+1), false, false),
3 => "Permanently banned ".$bannerInfo->username,
4 => "Unbanned ".$bannerInfo->username
];
users::logStaffAction("[ User Moderation ] ".$staff[$banType]." ( user ID ".$bannerInfo->id." )");
api::respond(200, true, $bannerInfo->username." has been ".$text[$banType]);

View File

@ -1,27 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Polygon;
API::initialize(["method" => "POST", "admin" => Users::STAFF_ADMINISTRATOR, "admin_ratelimit" => true, "secure" => true]);
if(!isset($_POST["title"]) || !isset($_POST["body"])){ API::respond(400, false, "Invalid Request"); }
if(!trim($_POST["title"])){ API::respond(400, false, "You haven't set a title."); }
if(!trim($_POST["body"])){ API::respond(400, false, "You haven't set a body."); }
if(strlen($_POST["title"]) < 3 || strlen($_POST["title"]) > 64){ API::respond(400, false, "The title should be less than 64 characters and greater than 3."); }
if(strlen($_POST["body"]) < 3 || strlen($_POST["body"] > 1024)){ API::respond(400, false, "The body should be less than 1024 characters and greater than 3."); }
$title = $_POST["title"];
$body = $_POST["body"];
Database::singleton()->run(
"INSERT INTO feed_news (title, body, user_id, time_created) VALUES (:title, :body, :user_id, UNIX_TIMESTAMP())",
[":title" => $title, ":body" => $body, ":user_id" => SESSION["user"]["id"]]
);
Users::LogStaffAction("[ Feed ] ".SESSION["user"]["username"]." published a new post titled ".Polygon::FilterText($title).". ( user ID ".SESSION["user"]["id"]." ) ( Reason: N/A )");
API::respond(200, true, "Posted successfully.");

View File

@ -1,26 +1,33 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "admin" => [Users::STAFF_MODERATOR, Users::STAFF_CATALOG, Users::STAFF_ADMINISTRATOR], "secure" => true]);
if(!isset($_POST["banType"]) || !isset($_POST["moderationNote"]) || !isset($_POST["until"])){ API::respond(400, false, "Invalid Request"); }
if($_POST["banType"] < 1 || $_POST["banType"] > 3){ API::respond(400, false, "Invalid Request"); }
if(!trim($_POST["moderationNote"])){ API::respond(400, false, "You must supply a reason"); }
if($_POST["banType"] == 2 && !trim($_POST["until"])){ API::respond(400, false, "Ban time not set"); }
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!SESSION["adminLevel"]){ api::respond(400, false, "Not an administrator"); }
if(!isset($_POST["banType"]) || !isset($_POST["moderationNote"]) || !isset($_POST["until"])){ api::respond(400, false, "Invalid Request"); }
if($_POST["banType"] < 1 || $_POST["banType"] > 3){ api::respond(400, false, "Invalid Request"); }
if(!trim($_POST["moderationNote"])){ api::respond(400, false, "You must supply a reason"); }
if($_POST["banType"] == 2 && !trim($_POST["until"])){ api::respond(400, false, "Ban time not set"); }
$banType = $_POST["banType"];
$bannedUntil = strtotime($_POST["until"]." ".date('G:i:s'));
if($bannedUntil < strtotime('tomorrow')){ API::respond(400, false, "Ban time must be at least 1 day long"); }
if($bannedUntil < strtotime('tomorrow')){ api::respond(400, false, "Ban time must be at least 1 day long"); }
//markdown
$markdown = new Parsedown();
$markdown->setMarkupEscaped(true);
$markdown->setBreaksEnabled(true);
$markdown->setSafeMode(true);
$markdown->setUrlsLinked(true);
$text =
[
"title" =>
[
1 => "Warning",
2 => "Banned for ".timeSince("@".($bannedUntil+1), false, false),
2 => "Banned for ".general::time_elapsed("@".($bannedUntil+1), false, false),
3 => "Account Deleted"
],
@ -34,7 +41,7 @@ $text =
"footer" =>
[
1 => "Please re-read the <a href='/info/rules'>rules</a> and abide by them to prevent yourself from facing a ban",
2 => "Your ban ends at ".date('j/n/Y g:i:s A \G\M\T', $bannedUntil).", or in ".timeSince("@".($bannedUntil+1), true, false)." <br><br> Circumventing your ban on an alternate account while it is active may cause your ban time to be extended",
2 => "Your ban ends at ".date('j/n/Y g:i:s A \G\M\T', $bannedUntil).", or in ".general::time_elapsed("@".($bannedUntil+1), true, false)." <br><br> Circumventing your ban on an alternate account while it is active may cause your ban time to be extended",
3 => "Circumventing your ban by using an alternate account will lower your chance of appeal (if your ban was appealable) and potentially warrant you an IP ban"
]
];
@ -46,11 +53,11 @@ ob_start(); ?>
<p class="card-text mb-0">Reason:</p>
<div class="card">
<div class="card-body p-2">
<?=str_replace('<p>', '<p class="mb-0">', $markdown->setEmbedsEnabled(true)->text($_POST["moderationNote"]))?>
<?=str_replace('<p>', '<p class="mb-0">', $markdown->text(trim($_POST["moderationNote"])))?>
</div>
</div>
<br>
<p class="card-text"><?=$text["footer"][$banType]?></p>
<?php if($banType == 1) { ?>
<a href="#" class="btn btn-primary disabled">Reactivate</a>
<?php } API::respond(200, true, ob_get_clean());
<?php } api::respond(200, true, ob_get_clean());

View File

@ -1,68 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\Image;
use pizzaboxer\ProjectPolygon\API;
use Verot\Upload\Upload;
API::initialize(["method" => "POST", "admin" => Users::STAFF, "secure" => true]);
$renderType = $_POST['renderType'] ?? false;
$assetID = $_POST['assetID'] ?? false;
if(!$renderType) API::respond(400, false, "Bad Request");
if(!in_array($renderType, ["Avatar", "Asset"])) API::respond(400, false, "Invalid render type");
if(!$assetID || !is_numeric($assetID)) API::respond(400, false, "Bad Request");
if($renderType == "Asset")
{
$asset = Catalog::GetAssetInfo($assetID);
if(!$asset) API::respond(200, false, "The asset you requested does not exist");
switch($asset->type)
{
case 9: Polygon::RequestRender("Place", $assetID); break; //place
case 4: Polygon::RequestRender("Mesh", $assetID); break; // mesh
case 8: case 19: Polygon::RequestRender("Model", $assetID); break; // hat/gear
case 11: case 12: Polygon::RequestRender("Clothing", $assetID); break; // shirt/pants
case 17: Polygon::RequestRender("Head", $assetID); break; // head
case 10: Polygon::RequestRender("UserModel", $assetID); break; // user generated model
case 2: // t-shirt
$image = new Upload(SITE_CONFIG['paths']['assets'].$asset->imageID);
Thumbnails::UploadAsset($image, $asset->imageID, 420, 420, ["keepRatio" => true, "align" => "T"]);
//process initial tshirt thumbnail
$template = imagecreatefrompng($_SERVER['DOCUMENT_ROOT']."/img/tshirt-template.png");
$shirtdecal = Image::Resize(SITE_CONFIG['paths']['thumbs_assets']."{$asset->imageID}-420x420.png", 250, 250);
imagesavealpha($template, true);
imagesavealpha($shirtdecal, true);
Image::MergeLayers($template, $shirtdecal, 85, 85, 0, 0, 250, 250, 100);
imagepng($template, SITE_CONFIG['paths']['thumbs_assets']."$assetID-420x420.png");
Thumbnails::UploadToCDN(SITE_CONFIG['paths']['thumbs_assets']."$assetID-420x420.png");
break;
case 13: // decal
$image = new Upload(SITE_CONFIG['paths']['assets'].$asset->imageID);
Thumbnails::UploadAsset($image, $asset->imageID, 420, 420, ["keepRatio" => true, "align" => "C"]);
Thumbnails::UploadAsset($image, $assetID, 420, 420);
break;
case 3: // audio
Image::RenderFromStaticImage("audio", $assetID);
break;
default: API::respond(200, false, "This asset cannot be re-rendered");
}
}
else if($renderType == "Avatar")
{
$user = Users::GetInfoFromID($assetID);
if(!$user) API::respond(200, false, "The user you requested does not exist");
Polygon::RequestRender("Avatar", $assetID);
}
Users::LogStaffAction("[ Render ] Re-rendered $renderType ID $assetID");
API::respond(200, true, "Render request has been successfully submitted! See render status <a href='/admin/render-queue'>here</a>");

View File

@ -1,119 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Image;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
use Verot\Upload\Upload;
API::initialize(["method" => "POST", "admin" => [Users::STAFF_CATALOG, Users::STAFF_ADMINISTRATOR], "secure" => true]);
$file = $_FILES["file"] ?? false;
$name = $_POST["name"] ?? "";
$description = $_POST["description"] ?? "";
$type = $_POST["type"] ?? false;
$uploadas = $_POST["creator"] ?? "Polygon";
$creator = Users::GetIDFromName($uploadas);
if(!$file) API::respond(200, false, "You must select a file");
if(strlen($name) == 0) API::respond(200, false, "You must specify a name");
if(strlen($name) > 50) API::respond(200, false, "Name cannot be longer than 50 characters");
if(!$creator) API::respond(400, false, "The user you're trying to create as does not exist");
if(Polygon::FilterText($name, false, false, true) != $name) API::respond(400, false, "The name contains inappropriate text");
//$lastCreation = $pdo->query("SELECT created FROM assets WHERE creator = 2 ORDER BY id DESC")->fetchColumn();
//if($lastCreation+60 > time()) API::respond(400, false, "Please wait ".(60-(time()-$lastCreation))." seconds before creating a new asset");
if($type == 1) //image - this is for textures and stuff
{
if(!in_array($file["type"], ["image/png", "image/jpg", "image/jpeg"])) API::respond(400, false, "Must be a png or jpg file");
$image = new Upload($file);
if(!$image->uploaded) API::respond(500, false, "Failed to process image - please contact an admin");
$image->allowed = ['image/png', 'image/jpg', 'image/jpeg'];
$image->image_convert = 'png';
$imageId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
Image::Process($image, ["name" => "$imageId", "resize" => false, "dir" => "assets/"]);
Thumbnails::UploadAsset($image, $imageId, 420, 420, ["keepRatio" => true, "align" => "C"]);
}
elseif($type == 3) // audio
{
if(!in_array($file["type"], ["audio/mpeg", "audio/ogg", "video/ogg", "audio/mid", "audio/wav"])) API::respond(400, false, "Must be an mpeg, wav, ogg or midi audio. - ".$file["type"]);
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "audioType" => $file["type"], "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Image::RenderFromStaticImage("audio", $assetId);
}
elseif($type == 4) //mesh
{
if(!str_ends_with($file["name"], ".mesh")) API::respond(400, false, "Must be a .mesh file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Polygon::RequestRender("Mesh", $assetId);
}
elseif($type == 5) //lua
{
if(!str_ends_with($file["name"], ".lua")) API::respond(400, false, "Must be a .lua file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Image::RenderFromStaticImage("Script", $assetId);
}
elseif($type == 8) //hat
{
if(!str_ends_with($file["name"], ".xml") && !str_ends_with($file["name"], ".rbxm")) API::respond(400, false, "Must be an rbxm or xml file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Polygon::RequestRender("Model", $assetId);
}
elseif($type == 17) //head
{
if(!str_ends_with($file["name"], ".xml") && !str_ends_with($file["name"], ".rbxm")) API::respond(400, false, "Must be an rbxm or xml file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Polygon::RequestRender("Head", $assetId);
}
elseif($type == 18) //faces are literally just decals lmao (with a minor alteration to the xml)
{
if(!in_array($file["type"], ["image/png", "image/jpg", "image/jpeg"])) API::respond(400, false, "Must be a png or jpg file");
$image = new Upload($file);
if(!$image->uploaded) API::respond(500, false, "Failed to process image - please contact an admin");
$image->allowed = ['image/png', 'image/jpg', 'image/jpeg'];
$image->image_convert = 'png';
$imageId = Catalog::CreateAsset(["type" => 1, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
Image::Process($image, ["name" => "$imageId", "resize" => false, "dir" => "assets/"]);
Thumbnails::UploadAsset($image, $imageId, 420, 420, ["keepRatio" => true, "align" => "C"]);
$itemId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "imageID" => $imageId, "approved" => 1]);
file_put_contents(SITE_CONFIG['paths']['assets'].$itemId, Catalog::GenerateGraphicXML("Face", $imageId));
Thumbnails::UploadAsset($image, $itemId, 420, 420);
}
elseif($type == 19) //gear
{
if(!str_ends_with($file["name"], ".xml") && !str_ends_with($file["name"], ".rbxm")) API::respond(400, false, "Must be an rbxm or xml file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1, "gear_attributes" => '{"melee":false,"powerup":false,"ranged":false,"navigation":false,"explosive":false,"musical":false,"social":false,"transport":false,"building":false}']);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Polygon::RequestRender("Model", $assetId);
}
else if ($type == 24) // animation
{
if(!str_ends_with($file["name"], ".xml") && !str_ends_with($file["name"], ".rbxm")) API::respond(400, false, "Must be an rbxm or xml file");
$assetId = Catalog::CreateAsset(["type" => $type, "creator" => $creator, "name" => $name, "description" => $description, "approved" => 1]);
copy($file["tmp_name"], SITE_CONFIG["paths"]["assets"] . $assetId);
Image::RenderFromStaticImage("Animation", $assetId);
}
Users::LogStaffAction("[ Asset creation ] Created \"$name\" [ID ".($itemId ?? $assetId ?? $imageId)."]");
API::respondCustom([
"status" => 200,
"success" => true,
"message" => "<a href='/item?ID=".($itemId ?? $assetId ?? $imageId)."'>".Catalog::GetTypeByNum($type)."</a> successfully created!",
"assetID" => ($itemId ?? $assetId ?? $imageId)
]);

View File

@ -1,40 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize();
$AssetID = API::GetParameter("GET", "assetID", "int");
$Page = API::GetParameter("GET", "page", "int", 1);
$CommentsCount = Database::singleton()->run("SELECT COUNT(*) FROM asset_comments WHERE assetID = :AssetID", [":AssetID" => $AssetID])->fetchColumn();
if($CommentsCount == 0) API::respond(200, true, "This item does not have any comments");
$Pagination = Pagination($Page, $CommentsCount, 15);
$Comments = Database::singleton()->run(
"SELECT asset_comments.*, users.username FROM asset_comments
INNER JOIN users ON users.id = asset_comments.author
WHERE assetID = :AssetID
ORDER BY id DESC LIMIT 15 OFFSET :Offset",
[":AssetID" => $AssetID, ":Offset" => $Pagination->Offset]
);
$Items = [];
while($Comment = $Comments->fetch(\PDO::FETCH_OBJ))
{
$Items[] =
[
"time" => strtolower(timeSince($Comment->time)),
"commenter_name" => $Comment->username,
"commenter_id" => $Comment->author,
"commenter_avatar" => Thumbnails::GetAvatar($Comment->author),
"content" => nl2br(Polygon::FilterText($Comment->content))
];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "items" => $Items, "pages" => $Pagination->Pages]);

View File

@ -1,34 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST['assetID']) || !isset($_POST['content']));
$uid = SESSION["user"]["id"];
$id = $_POST['assetID'];
$content = $_POST['content'];
$item = Catalog::GetAssetInfo($id);
if(!$item) API::respond(400, false, "Asset does not exist");
if(!$item->comments) API::respond(400, false, "Comments are unavailable for this asset");
if(!strlen($content)) API::respond(400, false, "Comment cannot be empty");
if(strlen($content) > 100) API::respond(400, false, "Comment cannot be longer than 128 characters");
$lastComment = Database::singleton()->run(
"SELECT time FROM asset_comments WHERE time+60 > UNIX_TIMESTAMP() AND author = :uid",
[":uid" => $uid]
);
if($lastComment->rowCount()) API::respond(400, false, "Please wait ".GetReadableTime($lastComment->fetchColumn(), ["RelativeTime" => "1 minute"])." before posting a new comment");
Database::singleton()->run(
"INSERT INTO asset_comments (author, content, assetID, time)
VALUES (:uid, :content, :aid, UNIX_TIMESTAMP())",
[":uid" => $uid, ":content" => $content, ":aid" => $id]
);
API::respond(200, true, "OK");

View File

@ -1,82 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
function getPrice($price)
{
return $price ? '<span class="text-success"><i class="fal fa-pizza-slice"></i> '.$price.'</span>' : '<span class="text-success">Free</span>';
}
$uid = SESSION["user"]["id"];
$id = $_POST['id'] ?? false;
$price = $_POST['price'] ?? 0;
$item = Catalog::GetAssetInfo($id);
if(!$item) API::respond(400, false, "Asset does not exist");
if(Catalog::OwnsAsset($uid, $id)) API::respond(400, false, "User already owns asset");
if(!$item->sale) API::respond(400, false, "Asset is off-sale");
if(SESSION["user"]["currency"] - $item->price < 0) API::respond(400, false, "User cannot afford asset");
if($item->price != $price)
{
die(json_encode(
[
"status" => 200,
"success" => true,
"message" => "Item price changed",
"header" => "Item Price Has Changed",
"text" => 'While you were shopping, the price of this item changed from '.getPrice($price).' to '.getPrice($item->price).'.',
"buttons" => [['class'=>'btn btn-success btn-confirm-purchase', 'text'=>'Buy Now'], ['class'=>'btn btn-secondary', 'dismiss'=>true, 'text'=>'Cancel']],
"footer" => 'Your balance after this transaction will be <i class="fal fa-pizza-slice"></i> '.(SESSION["user"]["currency"] - $item->price),
"newprice" => $item->price
]));
}
$IsAlt = false;
foreach(Users::GetAlternateAccounts($item->creator) as $alt)
{
if($alt["userid"] == $uid) $IsAlt = true;
}
if (!$IsAlt)
{
Database::singleton()->run(
"UPDATE users SET currency = currency - :price WHERE id = :uid;
UPDATE users SET currency = currency + :price WHERE id = :seller",
[":price" => $item->price, ":uid" => $uid, ":seller" => $item->creator]
);
}
Database::singleton()->run(
"INSERT INTO ownedAssets (assetId, userId, timestamp) VALUES (:aid, :uid, UNIX_TIMESTAMP())",
[":aid" => $id, ":uid" => $uid]
);
if ($item->creator != SESSION["user"]["id"])
{
Database::singleton()->run(
"INSERT INTO transactions (purchaser, seller, assetId, amount, flagged, timestamp)
VALUES (:uid, :sid, :aid, :price, :flagged, UNIX_TIMESTAMP())",
[":uid" => $uid, ":sid" => $item->creator, ":aid" => $id, ":price" => $item->price, ":flagged" => (int)$IsAlt]
);
Database::singleton()->run("UPDATE assets SET Sales = Sales + 1 WHERE id = :AssetID", [":AssetID" => $id]);
}
die(json_encode(
[
"status" => 200,
"success" => true,
"message" => "OK",
"header" => "Purchase Complete!",
"image" => Thumbnails::GetAsset($item),
"text" => "You have successfully purchased the ".htmlspecialchars($item->name)." ".Catalog::GetTypeByNum($item->type)." from ".$item->username." for ".getPrice($item->price),
"buttons" => [['class' => 'btn btn-primary continue-shopping', 'dismiss' => true, 'text' => 'Continue Shopping']],
]));

View File

@ -1,40 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Database;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$userid = SESSION["user"]["id"];
$type = $_POST["type"] ?? false;
$page = $_POST["page"] ?? 1;
$assets = [];
if (!Catalog::GetTypeByNum($type)) API::respond(400, false, "Invalid asset type");
$assets = Database::singleton()->run(
"SELECT * FROM assets WHERE creator = :uid AND type = :type ORDER BY id DESC",
[":uid" => $userid, ":type" => $type]
);
$items = [];
while ($asset = $assets->fetch(\PDO::FETCH_OBJ))
{
$items[] =
[
"name" => htmlspecialchars($asset->name),
"id" => $asset->id,
"version" => $asset->type == 9 ? $asset->Version : false,
"thumbnail" => Thumbnails::GetAsset($asset),
"item_url" => "/".encode_asset_name($asset->name)."-item?id={$asset->id}",
"config_url" => $asset->type == 9 ? "/places/{$asset->id}/update" : "/my/item?ID={$asset->id}",
"created" => date("j/n/Y", $asset->created),
"sales-total" => $asset->Sales,
"sales-week" => 0 //$info->sales_week
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "assets" => $items]));

View File

@ -1,168 +1,16 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Catalog;
use pizzaboxer\ProjectPolygon\Image;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\Gzip;
use pizzaboxer\ProjectPolygon\API;
use Verot\Upload\Upload;
if($_SERVER['REQUEST_METHOD'] != 'POST') api::respond(405, false, "Method Not Allowed");
api::requireLogin();
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$userid = SESSION["user"]["id"];
$userid = SESSION["userId"];
$file = $_FILES["file"] ?? false;
$name = $_POST["name"] ?? false;
$type = $_POST["type"] ?? false;
if(!$file) API::respond(200, false, "You must select a file");
if(!in_array($file["type"], ["image/png", "image/jpg", "image/jpeg"]) && $type != 10) API::respond(200, false, "Must be a .png or .jpg file");
if(!isset($_POST["polygon-csrf"]) || $_POST["polygon-csrf"] != SESSION["csrfToken"])
api::respond(400, false, "Failed to validate CSRF");
if(empty($name)) API::respond(200, false, "You must specify a name");
if(strlen($name) > 50) API::respond(200, false, "The name is too long");
if(Polygon::IsExplicitlyFiltered($name)) API::respond(200, false, "The name contains inappropriate text");
if(!$file) api::respond(400, false, "You must select a file");
if(!in_array($type, [2, 10, 11, 12, 13])) API::respond(200, false, "You can't upload that type of content!");
$lastCreation = Database::singleton()->run(
"SELECT created FROM assets WHERE creator = :uid ORDER BY id DESC",
[":uid" => $userid]
)->fetchColumn();
if($userid != 1 && $lastCreation+30 > time()) API::respond(200, false, "Please wait ".(30-(time()-$lastCreation))." seconds before creating a new asset");
// tshirts are a bit messy but straightforward:
// the image asset itself must be 128x128 with the texture resized to preserve aspect ratio
// the image thumbnail should have the texture positioned top
//
// shirts and pants should ideally be 585x559 but it doesnt really matter -
// just as long as it looks right on the avatar. if it doesnt then disapprove
//
// decals are a lot more messy:
// the image asset itself is scaled to be 256 pixels in width, while preserving the texture ratio
// the image thumbnail should have the texture positioned center
// the decal asset however must have the texture stretched to 1:1 for all its respective sizes
// [example: https://www.roblox.com/Item.aspx?ID=8553820]
//
// we won't have to worry about image size constraints as they're always gonna be
// resized to fit in a smaller resolution
//
// refer to here for the thumbnail sizes: https://github.com/matthewdean/roblox-web-apis
//
// THUMBNAIL SIZES FOR EACH ITEM TYPE
// legend: [f = fit] [t = top] [c = center] [s = stretch] // [M = Model] [He = Head] [S = Shirt] [P = Pants]
//
// | 48x48 | 60x62 | 75x75 | 100x100 | 110x110 | 160x100 | 250x250 | 352x352 | 420x230 | 420x420 |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// Image | |yes (f)| | | | | | | | yes (t) |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// T-Shirt | | | | yes | yes | | | | | yes |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// Audio | | | yes | yes | yes | | yes | yes | yes | yes |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// Hat/Gear | yes | | yes | yes | yes | | yes | yes | yes (fc)| yes |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// Place | yes |yes(fc)| yes | yes | yes | yes | yes | yes | yes | yes |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// M/He/S/P | yes | | yes | yes | yes | | yes | yes | | yes |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
// Decal/Face |yes (s)| |yes (s)| yes (s) | yes (s) | | yes (s) | yes (s) | yes (s) | yes (s) |
// +-------+-------+-------+---------+---------+---------+---------+---------+---------+---------+
$image = new Upload($file);
if(!$image->uploaded) API::respond(200, false, "Failed to process image - please contact an admin");
$image->allowed = ['image/png', 'image/jpg', 'image/jpeg'];
$image->image_convert = 'png';
$imageId = Catalog::CreateAsset(["type" => 1, "creator" => SESSION["user"]["id"], "name" => $name, "description" => Catalog::GetTypeByNum($type)." Image"]);
if ($type == 2) //tshirt
{
$Processed = Image::Process($image, ["name" => "$imageId", "keepRatio" => true, "align" => "T", "x" => 128, "y" => 128, "dir" => "assets/"]);
if ($Processed !== true) API::respond(200, false, "Image processing failed: $Processed");
Thumbnails::UploadAsset($image, $imageId, 420, 420, ["keepRatio" => true, "align" => "T"]);
$itemId = Catalog::CreateAsset(["type" => 2, "creator" => SESSION["user"]["id"], "name" => $name, "description" => "T-Shirt", "imageID" => $imageId]);
file_put_contents(SITE_CONFIG['paths']['assets'].$itemId, Catalog::GenerateGraphicXML("T-Shirt", $imageId));
//process initial tshirt thumbnail
$template = imagecreatefrompng($_SERVER['DOCUMENT_ROOT']."/img/tshirt-template.png");
$shirtdecal = Image::Resize(SITE_CONFIG['paths']['thumbs_assets']."/$imageId-420x420.png", 250, 250);
imagesavealpha($template, true);
imagesavealpha($shirtdecal, true);
Image::MergeLayers($template, $shirtdecal, 85, 85, 0, 0, 250, 250, 100);
imagepng($template, SITE_CONFIG['paths']['thumbs_assets']."/$itemId-420x420.png");
Thumbnails::UploadToCDN(SITE_CONFIG['paths']['thumbs_assets']."/$itemId-420x420.png");
}
else if ($type == 11 || $type == 12) //shirt / pants
{
$Processed = Image::Process($image, ["name" => "$imageId", "x" => 585, "y" => 559, "dir" => "assets/"]);
if ($Processed !== true) API::respond(200, false, "Image processing failed: $Processed");
Thumbnails::UploadAsset($image, $imageId, 420, 420, ["keepRatio" => true, "align" => "C"]);
$itemId = Catalog::CreateAsset(["type" => $type, "creator" => SESSION["user"]["id"], "name" => $name, "description" => Catalog::GetTypeByNum($type), "imageID" => $imageId]);
file_put_contents(SITE_CONFIG['paths']['assets'].$itemId, Catalog::GenerateGraphicXML(Catalog::GetTypeByNum($type), $imageId));
Polygon::RequestRender("Clothing", $itemId);
}
else if ($type == 10) // model
{
$ModelXML = file_get_contents($file["tmp_name"]);
$ModelXML = str_ireplace("http://".$_SERVER['HTTP_HOST']."/asset/?id=", "%ROBLOXASSETURL%", $ModelXML);
$ModelXML = str_ireplace("http://".$_SERVER['HTTP_HOST']."/asset?id=", "%ROBLOXASSETURL%", $ModelXML);
$isScript = stripos($ModelXML, 'class="Script" referent="RBX0"');
if (strlen($ModelXML) > 16000000) api::respond(200, false, "Model cannot be larger than 16 megabytes");
libxml_use_internal_errors(true);
$SimpleXML = simplexml_load_string($ModelXML);
if ($SimpleXML === false)
{
api::respond(200, false, "Model File is invalid, are you sure it is an older format place file?");
}
$modelId = Catalog::CreateAsset([
"type" => 10,
"creator" => SESSION["user"]["id"],
"name" => $name,
"description" => "Model",
"PublicDomain" => 0,
"approved" => $isScript ? 1 : 0
]);
file_put_contents(Polygon::GetSharedResource("assets/{$modelId}"), $ModelXML);
Gzip::Compress(Polygon::GetSharedResource("assets/{$modelId}"));
if ($isScript)
{
//put script image as thumbnail
Image::RenderFromStaticImage("Script", $modelId);
}
else
{
// user uploaded models are rendered as "usermodels" - this is just normal model rendering except there's no alpha
// no roblox thumbnails had transparency up until like 2013 anyway so its not that big of a deal
Polygon::RequestRender("UserModel", $modelId);
}
}
else if ($type == 13) //decal
{
$Processed = Image::Process($image, ["name" => "$imageId", "x" => 256, "scaleY" => true, "dir" => "assets/"]);
if ($Processed !== true) api::respond(200, false, "Image processing failed: $Processed");
Thumbnails::UploadAsset($image, $imageId, 420, 420, ["keepRatio" => true, "align" => "C"]);
$itemId = Catalog::CreateAsset(["type" => 13, "creator" => SESSION["user"]["id"], "name" => $name, "description" => "Decal", "imageID" => $imageId]);
file_put_contents(SITE_CONFIG['paths']['assets'].$itemId, Catalog::GenerateGraphicXML("Decal", $imageId));
Thumbnails::UploadAsset($image, $itemId, 420, 420);
}
API::respond(200, true, Catalog::GetTypeByNum($type)." successfully created!");
die(json_encode(["status" => 200, "success" => true, "message" => "OK"]));

View File

@ -1,28 +0,0 @@
<?php require $_SERVER["DOCUMENT_ROOT"]."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "GET", "api" => "DiscordBot"]);
if (isset($_GET["Token"]) && isset($_GET["DiscordID"]))
{
$userInfo = Database::singleton()->run("SELECT * FROM users WHERE discordKey = :key", [":key" => $_GET["Token"]])->fetch(\PDO::FETCH_OBJ);
if (!$userInfo) API::respond(200, false, "InvalidKey"); // check if verification key is valid
if ($userInfo->discordID != NULL) API::respond(200, false, "AlreadyVerified"); // check if mercury account is already verified
Database::singleton()->run(
"UPDATE users SET discordID = :id, discordVerifiedTime = UNIX_TIMESTAMP() WHERE discordKey = :key",
[":id" => $_GET["DiscordID"], ":key" => $_GET["Token"]]
);
API::respond(200, true, $userInfo->username);
}
else if (isset($_GET["DiscordID"]))
{
$username = Database::singleton()->run("SELECT username FROM users WHERE discordID = :id", [":id" => $_GET["DiscordID"]]);
if (!$username->rowCount()) API::respond(200, false, "NotVerified"); // check if discord account is already verified
API::respond(200, true, $username->fetchColumn());
}
API::respond(400, false, "Bad Request");

View File

@ -1,34 +0,0 @@
<?php require $_SERVER["DOCUMENT_ROOT"]."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "GET", "api" => "DiscordBot"]);
if (isset($_GET["UserName"]))
{
$userInfo = Database::singleton()->run(
"SELECT id, username, blurb, adminlevel, jointime, lastonline, discordID, discordVerifiedTime FROM users WHERE username = :name",
[":name" => $_GET["UserName"]]
)->fetch(\PDO::FETCH_OBJ);
if (!$userInfo) API::respond(200, false, "DoesntExist");
}
else if (isset($_GET["DiscordID"]))
{
$userInfo = Database::singleton()->run(
"SELECT id, username, blurb, adminlevel, jointime, lastonline, discordID, discordVerifiedTime FROM users WHERE discordID = :id",
[":id" => $_GET["DiscordID"]]
)->fetch(\PDO::FETCH_OBJ);
if (!$userInfo) API::respond(200, false, "NotVerified");
}
else
{
API::respond(400, false, "Bad Request");
}
$userInfo->thumbnail = Thumbnails::GetAvatar($userInfo->id, 420, 420, true);
$userInfo->blurb = str_ireplace(["@everyone", "@here"], ["[everyone]", "[here]"], $userInfo->blurb);
$userInfo->blurb = preg_replace("/<(@[0-9]+)>/i", "[$1]", $userInfo->blurb);
API::respond(200, true, $userInfo);

View File

@ -1,16 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$RequestsCount = Database::singleton()->run(
"SELECT COUNT(*) FROM friends WHERE receiverId = :UserID AND status = 0", [":UserID" => SESSION["user"]["id"]]
)->fetchColumn();
if($RequestsCount == 0) API::respond(200, false, "You don't have any friend requests to accept right now");
Database::singleton()->run("UPDATE friends SET status = 1 WHERE receiverId = :UserID AND status = 0", [":UserID" => SESSION["user"]["id"]]);
API::respond(200, true, "All your friend requests have been accepted");

View File

@ -1,26 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$FriendID = API::GetParameter("POST", "FriendID", "int");
$FriendRequest = Database::singleton()->run("SELECT * FROM friends WHERE id = :FriendID AND status = 0", [":FriendID" => $FriendID]);
$FriendRequestInfo = $FriendRequest->fetch(\PDO::FETCH_OBJ);
if($FriendRequest->rowCount() == 0) API::respond(200, false, "Friend request doesn't exist");
if((int) $FriendRequestInfo->receiverId != SESSION["user"]["id"]) API::respond(200, false, "You are not the recipient of this friend request");
Database::singleton()->run("UPDATE friends SET status = 1 WHERE id = :FriendID", [":FriendID" => $FriendID]);
// since we're the one receiving it, we just need to update our pending requests
Database::singleton()->run(
"UPDATE users
SET PendingFriendRequests = (SELECT COUNT(*) FROM friends WHERE receiverId = users.id AND status = 0)
WHERE id = :UserID",
[":UserID" => SESSION["user"]["id"]]
);
API::respond(200, true, "OK");

View File

@ -0,0 +1,28 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(!isset($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
if(!is_numeric($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
$userid = SESSION["userId"];
if($_POST['userID'] == SESSION["userId"]){ api::respond(400, false, "You can't perform friend operations on yourself"); }
$query = $pdo->prepare("SELECT id, requesterId FROM friends WHERE :uid IN (requesterId, receiverId) AND :rid IN (requesterId, receiverId) AND status = 0");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":rid", $_POST['userID'], PDO::PARAM_INT);
$query->execute();
$result = $query->fetch(PDO::FETCH_OBJ);
if(!$query->rowCount()){ api::respond(400, false, "Friend request doesn't exist"); }
if($result->requesterId == $userid){ api::respond(400, false, "Only the request receiver can accept the request"); }
$query = $pdo->prepare("UPDATE friends SET status = 1 WHERE id = :id");
$query->bindParam(":id", $result->id, PDO::PARAM_INT);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -1,36 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$Page = API::GetParameter("POST", "Page", "int", 1);
$RequestsCount = Database::singleton()->run(
"SELECT COUNT(*) FROM friends WHERE receiverId = :UserID AND status = 0",
[":UserID" => SESSION["user"]["id"]]
)->fetchColumn();
if($RequestsCount == 0) API::respond(200, true, "You're all up-to-date with your friend requests");
$Pagination = Pagination($Page, $RequestsCount, 18);
$Requests = Database::singleton()->run(
"SELECT * FROM friends WHERE receiverId = :UserID AND status = 0 LIMIT 18 OFFSET :Offset",
[":UserID" => SESSION["user"]["id"], ":Offset" => $Pagination->Offset]
);
while($Request = $Requests->fetch(\PDO::FETCH_OBJ))
{
$Items[] =
[
"Username" => Users::GetNameFromID($Request->requesterId),
"UserID" => $Request->requesterId,
"Avatar" => Thumbnails::GetAvatar($Request->requesterId),
"FriendID" => $Request->id
];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "items" => $Items, "count" => (int) $RequestsCount, "pages" => (int) $Pagination->Pages]);

View File

@ -1,40 +1,32 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
api::requireLogin();
if(isset($_POST['page']) && !is_numeric($_POST['page'])){ api::respond(400, false, "Invalid Request - page is not numeric"); }
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$userid = SESSION["userId"];
$userid = SESSION["user"]["id"];
$page = $_POST['page'] ?? 1;
$page = isset($_POST['page']) ? $_POST['page'] : 1;
$friendCount = Database::singleton()->run(
"SELECT COUNT(*) FROM friends WHERE receiverId = :uid AND status = 0",
[":uid" => $userid]
)->fetchColumn();
$query = $pdo->prepare("SELECT * FROM friends WHERE :uid = receiverId AND status = 0");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->execute();
$pagination = Pagination($page, $friendCount, 18);
$friends = [];
if (!$pagination->Pages) API::respond(200, true, "You're all up-to-date with your friend requests!");
$friends = Database::singleton()->run(
"SELECT * FROM friends WHERE receiverId = :uid AND status = 0 LIMIT 18 OFFSET :offset",
[":uid" => $userid, ":offset" => $pagination->Offset]
);
$items = [];
while ($friend = $friends->fetch(\PDO::FETCH_OBJ))
while($row = $query->fetch(PDO::FETCH_OBJ))
{
$items[] =
[
"username" => Users::GetNameFromID($friend->requesterId),
"userid" => $friend->requesterId,
"avatar" => Thumbnails::GetAvatar($friend->requesterId),
"friendid" => $friend->id
];
$friends[] = ["userName" => users::getUserNameFromUid($row->requesterId), "userId" => $row->requesterId];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "requests" => $items, "pages" => $pagination->Pages]);
die(json_encode(
[
"status" => 200,
"success" => true,
"message" => "OK",
"requestCount" => $query->rowCount(),
"requests" => $friends,
"pages" => 1
]));

View File

@ -1,51 +1,71 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
if(!isset($_POST['userID'])){ api::respond(400, false, "Invalid Request - userID not set"); }
if(!is_numeric($_POST['userID'])){ api::respond(400, false, "Invalid Request - userID is not numeric"); }
if(!users::getUserInfoFromUid($_POST['userID'])){ api::respond(400, false, "User does not exist"); }
if(isset($_POST['page']) && !is_numeric($_POST['page'])){ api::respond(400, false, "Invalid Request - page is not numeric"); }
if(isset($_POST['limit']) && !is_numeric($_POST['limit'])){ api::respond(400, false, "Invalid Request - limit is not numeric"); }
API::initialize(["method" => "POST"]);
$page = isset($_POST['page']) ? $_POST['page'] : 1;
$limit = isset($_POST['limit']) ? $_POST['limit'] : 18;
$url = $_SERVER['HTTP_REFERER'] ?? false;
$userId = $_POST['userID'] ?? false;
$page = $_POST['page'] ?? 1;
$order = strpos($url, "/home") ? "lastonline DESC" : "id";
$limit = strpos($url, "/friends") ? 18 : 6;
$self = str_ends_with($url, "/user") || str_ends_with($url, "/friends") || strpos($url, "/home");
$query = $pdo->prepare("SELECT COUNT(*) FROM friends WHERE :uid IN (requesterId, receiverId) AND status = 1");
$query->bindParam(":uid", $_POST['userID'], PDO::PARAM_INT);
$query->execute();
if (!Users::GetInfoFromID($userId)) API::respond(400, false, "User does not exist");
$pages = ceil($query->fetchColumn()/$limit);
$offset = ($page - 1)*$limit;
$friendCount = Database::singleton()->run(
"SELECT COUNT(*) FROM friends WHERE :uid IN (requesterId, receiverId) AND status = 1",
[":uid" => $userId]
)->fetchColumn();
$query = $pdo->prepare("SELECT * FROM friends WHERE :uid IN (requesterId, receiverId) AND status = 1 LIMIT :limit OFFSET :offset");
$query->bindParam(":uid", $_POST['userID'], PDO::PARAM_INT);
$query->bindParam(":limit", $limit, PDO::PARAM_INT);
$query->bindParam(":offset", $offset, PDO::PARAM_INT);
$query->execute();
$pagination = Pagination($page, $friendCount, $limit);
$friends = [];
if (!$pagination->Pages) API::respond(200, true, ($self ? "You do" : Users::GetNameFromID($userId)." does")."n't have any friends");
$friends = Database::singleton()->run(
"SELECT friends.*, users.username, users.id AS userId, users.status, users.lastonline FROM friends
INNER JOIN users ON users.id = (CASE WHEN requesterId = :uid THEN receiverId ELSE requesterId END)
WHERE :uid IN (requesterId, receiverId) AND friends.status = 1
ORDER BY {$order} LIMIT :limit OFFSET :offset",
[":uid" => $userId, ":limit" => $limit, ":offset" => $pagination->Offset]
);
$items = [];
while ($friend = $friends->fetch(\PDO::FETCH_OBJ))
{
$items[] =
[
"username" => $friend->username,
"userid" => $friend->userId,
"avatar" => Thumbnails::GetAvatar($friend->userId),
"friendid" => $friend->id,
"status" => Polygon::FilterText($friend->status)
];
while($row = $query->fetch(PDO::FETCH_OBJ))
{
$friendId = $row->requesterId == $_POST['userID'] ? $row->receiverId : $row->requesterId;
$friends[] = ["userName" => users::getUserNameFromUid($friendId), "userId" => $friendId];
}
API::respondCustom(["status" => 200, "success" => true, "message" => "OK", "items" => $items, "pages" => $pagination->Pages]);
ob_start(); ?>
<nav aria-label="Friend Pagination">
<ul class="pagination justify-content-center mb-0">
<li class="page-item<?=$page<=1?' disabled':''?>">
<a class="page-link" href="#" aria-label="Previous" data-control="friends-pager" data-page="<?=$page-1?>">
<span aria-hidden="true">&laquo;</span>
<span class="sr-only">Previous</span>
</a>
</li>
<?php $paginator = 1; while($paginator <= $pages){ ?>
<li class="page-item<?=($paginator == $page)?' active':''?>"><a class="page-link" href="#" data-control="friends-pager" data-page="<?=$paginator?>"><?=$paginator?></a></li>
<?php $paginator++; } ?>
<li class="page-item<?=$page>=$pages?' disabled':''?>">
<a class="page-link" href="#" aria-label="Next" data-control="friends-pager" data-page="<?=$page+1?>">
<span aria-hidden="true">&raquo;</span>
<span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
<?php
$pager = ob_get_clean();
die(json_encode(
[
"status" => 200,
"success" => true,
"message" => "OK",
"username" => users::getUserNameFromUid($_POST['userID']),
"friendCount" => $query->rowCount(),
"friends" => $friends,
"pages" => $pages,
"pager" => $pages > 1 ? $pager : false
]));

View File

@ -1,16 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$RequestsCount = Database::singleton()->run(
"SELECT COUNT(*) FROM friends WHERE receiverId = :UserID AND status = 0", [":UserID" => SESSION["user"]["id"]]
)->fetchColumn();
if($RequestsCount == 0) API::respond(200, false, "You don't have any friend requests to decline right now");
Database::singleton()->run("UPDATE friends SET status = 2 WHERE receiverId = :UserID AND status = 0", [":UserID" => SESSION["user"]["id"]]);
API::respond(200, true, "All your friend requests have been decline");

View File

@ -1,26 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$FriendID = API::GetParameter("POST", "FriendID", "int");
$FriendConnection = Database::singleton()->run("SELECT * FROM friends WHERE id = :FriendID AND NOT status = 2", [":FriendID" => $FriendID]);
$FriendConnectionInfo = $FriendConnection->fetch(\PDO::FETCH_OBJ);
if($FriendConnection->rowCount() == 0) API::respond(200, false, "Friend connection doesn't exist");
if(!in_array(SESSION["user"]["id"], [$FriendConnectionInfo->requesterId, $FriendConnectionInfo->receiverId])) API::respond(200, false, "You are not a part of this friend connection");
Database::singleton()->run("UPDATE friends SET status = 2 WHERE id = :FriendID", [":FriendID" => $FriendID]);
// a pending request revocation can come from either the sender or the receiver, so we update both
Database::singleton()->run(
"UPDATE users
SET PendingFriendRequests = (SELECT COUNT(*) FROM friends WHERE receiverId = users.id AND status = 0)
WHERE id IN (:RequesterID, :ReceiverID)",
[":RequesterID" => $FriendConnectionInfo->requesterId, ":ReceiverID" => $FriendConnectionInfo->receiverId]
);
API::respond(200, true, "OK");

View File

@ -0,0 +1,27 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
if(!isset($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
if(!is_numeric($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
api::requireLogin();
$userid = SESSION["userId"];
if($_POST['userID'] == SESSION["userId"]){ api::respond(400, false, "You can't perform friend operations on yourself"); }
$query = $pdo->prepare("SELECT id FROM friends WHERE :uid IN (requesterId, receiverId) AND :rid IN (requesterId, receiverId) AND NOT status = 2");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":rid", $_POST['userID'], PDO::PARAM_INT);
$query->execute();
$frId = $query->fetchColumn();
if(!$query->rowCount()){ api::respond(400, false, "Friend connection doesn't exist"); }
$query = $pdo->prepare("UPDATE friends SET status = 2 WHERE id = :id");
$query->bindParam(":id", $frId, PDO::PARAM_INT);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -1,39 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
$UserID = API::GetParameter("POST", "UserID", "int");
if ($UserID == SESSION["user"]["id"]) API::respond(200, false, "You can't perform friend operations on yourself");
if (!Users::GetInfoFromID($UserID)) API::respond(200, false, "That user doesn't exist");
$FriendConnection = Database::singleton()->run(
"SELECT status FROM friends WHERE :UserID IN (requesterId, receiverId) AND :ReceiverID IN (requesterId, receiverId) AND NOT status = 2",
[":UserID" => SESSION["user"]["id"], ":ReceiverID" => $UserID]
);
if($FriendConnection->rowCount() != 0) API::respond(200, false, "Friend connection already exists");
$LastRequest = Database::singleton()->run(
"SELECT timeSent FROM friends WHERE requesterId = :UserID AND timeSent+60 > UNIX_TIMESTAMP()",
[":UserID" => SESSION["user"]["id"]]
);
if($LastRequest->rowCount() != 0) API::respond(200, false, "Please wait ".GetReadableTime($LastRequest->fetchColumn(), ["RelativeTime" => "1 minute"])." before sending another request");
Database::singleton()->run(
"INSERT INTO friends (requesterId, receiverId, timeSent) VALUES (:UserID, :ReceiverID, UNIX_TIMESTAMP())",
[":UserID" => SESSION["user"]["id"], ":ReceiverID" => $UserID]
);
// update the user's pending requests
Database::singleton()->run(
"UPDATE users
SET PendingFriendRequests = (SELECT COUNT(*) FROM friends WHERE receiverId = users.id AND status = 0)
WHERE id = :ReceiverID",
[":ReceiverID" => $UserID]
);
API::respond(200, true, "OK");

View File

@ -0,0 +1,33 @@
<?php
require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
header("content-type: application/json");
if($_SERVER['REQUEST_METHOD'] != 'POST'){ api::respond(405, false, "Method Not Allowed"); }
if(!isset($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
if(!is_numeric($_POST['userID'])){ api::respond(400, false, "Invalid Request"); }
if(!users::getUserInfoFromUid($_POST['userID'])){ api::respond(400, false, "User does not exist"); }
api::requireLogin();
$userid = SESSION["userId"];
if($_POST['userID'] == SESSION["userId"]){ api::respond(400, false, "You can't perform friend operations on yourself"); }
$query = $pdo->prepare("SELECT COUNT(*) FROM friends WHERE :uid IN (requesterId, receiverId) AND :rid IN (requesterId, receiverId) AND NOT status = 2");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":rid", $_POST['userID'], PDO::PARAM_INT);
$query->execute();
if($query->fetchColumn()){ api::respond(400, false, "Friend connection already exists"); }
$query = $pdo->prepare("SELECT timeSent FROM friends WHERE requesterId = :uid AND timeSent+30 > UNIX_TIMESTAMP()");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->execute();
if($query->rowCount()){ api::respond(400, false, "Please wait ".(($query->fetchColumn()+30)-time())." seconds before sending another request"); }
$query = $pdo->prepare("INSERT INTO friends (requesterId, receiverId, timeSent) VALUES (:uid, :rid, UNIX_TIMESTAMP())");
$query->bindParam(":uid", $userid, PDO::PARAM_INT);
$query->bindParam(":rid", $_POST['userID'], PDO::PARAM_INT);
if($query->execute()){ api::respond(200, true, "OK"); }
else{ api::respond(500, false, "Internal Server Error"); }

View File

@ -1,42 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true]);
$PlaceID = API::GetParameter("POST", "PlaceID", "int", false);
$GameJobCount = Database::singleton()->run(
"SELECT COUNT(*) FROM GameJobs WHERE Status = \"Ready\" AND PlaceID = :PlaceID",
[":PlaceID" => $PlaceID]
)->fetchColumn();
$Pagination = Pagination(API::GetParameter("POST", "Page", "int", 1), $GameJobCount, 5);
$GameJobs = Database::singleton()->run(
"SELECT GameJobs.*, assets.MaxPlayers FROM GameJobs
INNER JOIN assets ON assets.id = PlaceID
WHERE Status = \"Ready\" AND PlaceID = :PlaceID
ORDER BY PlayerCount DESC LIMIT 5 OFFSET :Offset",
[":PlaceID" => $PlaceID, ":Offset" => $Pagination->Offset]
);
if ($GameJobs->rowCount() == 0)
{
API::respond(200, true, "No games are currently running for this place");
}
while ($GameJob = $GameJobs->fetch(\PDO::FETCH_OBJ))
{
$Items[] =
[
"JobID" => $GameJob->JobID,
"PlayerCount" => (int) $GameJob->PlayerCount,
"MaximumPlayers" => (int) $GameJob->MaxPlayers,
"IngamePlayers" => Games::GetPlayersInGame($GameJob->JobID)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pagination->Pages, "items" => $Items]));

View File

@ -1,102 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true]);
$Filters =
[
"Default" => "ServerRunning DESC, ActivePlayers DESC, LastServerUpdate DESC, updated DESC",
"Top Played" => "Visits DESC",
"Recently Updated" => "updated DESC"
];
$Query = API::GetParameter("POST", "Query", "string", "");
$FilterBy = API::GetParameter("POST", "FilterBy", ["Default", "Top Played", "Recently Updated"], "Default");
$Version = API::GetParameter("POST", "FilterVersion", ["All", "2010", "2011", "2012"], "All");
$CreatorID = API::GetParameter("POST", "CreatorID", "int", false);
$QueryParameters = "type = 9";
$ValueParameters = [];
if (strlen($Query))
{
$QueryParameters .= " AND name LIKE :Query";
$ValueParameters[":Query"] = "%{$Query}%";
}
if ($Version != "All")
{
$QueryParameters .= " AND Version = :Version";
$ValueParameters[":Version"] = $Version;
}
if ($CreatorID !== false)
{
$Limit = 10;
$OrderBy = "created DESC";
$QueryParameters .= " AND creator = :CreatorID";
$ValueParameters[":CreatorID"] = $CreatorID;
}
else
{
$Limit = 24;
$OrderBy = $Filters[$FilterBy];
}
$PlaceCount = Database::singleton()->run("SELECT COUNT(*) FROM assets WHERE {$QueryParameters}", $ValueParameters)->fetchColumn();
$Pagination = Pagination(API::GetParameter("POST", "Page", "int", 1), $PlaceCount, $Limit);
$ValueParameters[":Limit"] = $Limit;
$ValueParameters[":Offset"] = $Pagination->Offset;
$Places = Database::singleton()->run(
"SELECT assets.*, users.username FROM assets
INNER JOIN users ON users.id = assets.creator
WHERE {$QueryParameters} ORDER BY {$OrderBy} LIMIT :Limit OFFSET :Offset",
$ValueParameters
);
if ($Places->rowCount() == 0)
{
if ($CreatorID === false)
{
API::respond(200, true, "No games matched your query");
}
else if ($CreatorID == SESSION["user"]["id"])
{
API::respond(200, true, "You do not have any active places. <a href=\"/develop?View=9\">Manage My Places</a>");
}
else
{
API::respond(200, true, Users::GetNameFromID($CreatorID) . " does not have any active places");
}
}
while ($Place = $Places->fetch(\PDO::FETCH_OBJ))
{
$Items[] =
[
"PlaceID" => (int) $Place->id,
"Name" => Polygon::FilterText($Place->name),
// "Description" => Polygon::FilterText($Place->description),
"Description" => Polygon::FilterText($markdown->setEmbedsEnabled(true)->line($Place->description), false),
"Visits" => number_format($Place->Visits),
"OnlinePlayers" => $Place->ServerRunning ? number_format($Place->ActivePlayers) : false,
"Location" => "/" . encode_asset_name($Place->name) . "-place?id={$Place->id}",
"Thumbnail" => Thumbnails::GetAsset($Place, 768, 432),
"CreatorName" => $Place->username,
"CreatorID" => $Place->creator,
"Version" => (int) $Place->Version,
"Uncopylocked" => (bool) $Place->publicDomain,
"CanPlayGame" => (bool) Games::CanPlayGame($Place)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pagination->Pages, "items" => $Items]));

View File

@ -1,254 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
header("Pragma: no-cache");
header("Cache-Control: no-cache");
$Statuses =
[
"Waiting" =>
[
"Message" => "Waiting for a server",
"Code" => 0
],
"Loading" =>
[
"Message" => "A server is loading the game",
"Code" => 1
],
"Joining" =>
[
"Message" => "The server is ready. Joining the game...",
"Code" => 2
],
"Error" =>
[
"Message" => "An error occured. Please try again later",
"Code" => 4
],
"Expired" =>
[
"Message" => "There are no game servers available at this time. Please try again later.",
"Code" => 4
],
"GameEnded" =>
[
"Message" => "The game you requested has ended",
"Code" => 5
],
"GameFull" =>
[
"Message" => "The game you requested is full. Please try again later",
"Code" => 6
],
"Ratelimit" =>
[
"Message" => "You are joining games too fast. Please try again later",
"Code" => 11
],
"Unauthorized" =>
[
"Message" => "Cannot join game with no authenticated user.",
"Code" => 4
]
];
$IsTeleport = isset($_GET["isTeleport"]) && $_GET['isTeleport'] == "true";
if ($IsTeleport)
{
$UserInfo = Users::GetInfoFromJobTicket();
}
else
{
API::initialize(["method" => "GET", "logged_in" => true, "secure" => true]);
$UserInfo = (object)SESSION["user"];
}
$Request = API::GetParameter("GET", "request", ["RequestGame", "RequestGameJob", "RequestFollowUser", "CheckGameJobStatus"]);
if ($IsTeleport && GetUserAgent() != "Roblox/WinInet")
{
die(json_encode([
"Error" => "Request is not authorized from specified origin",
"userAgent" => $_SERVER["HTTP_USER_AGENT"] ?? null,
"referrer" => $_SERVER["HTTP_REFERER"] ?? null
]));
}
if (!$UserInfo)
{
Respond("Unauthorized");
}
function Respond($Status, $JobID = null, $Version = null, $JoinScriptUrl = null)
{
global $Statuses;
$Response = [];
$StatusInfo = $Statuses[$Status];
$Response["jobId"] = $JobID;
$Response["status"] = $StatusInfo["Code"];
$Response["joinScriptUrl"] = $JoinScriptUrl;
$Response["authenticationUrl"] = $JoinScriptUrl ? "https://{$_SERVER['HTTP_HOST']}/Login/Negotiate.ashx" : null;
$Response["authenticationTicket"] = $JoinScriptUrl ? "0" : null;
$Response["message"] = $StatusInfo["Message"];
$Response["version"] = $Version;
die(json_encode($Response));
}
function CheckRatelimit()
{
global $UserInfo;
$SessionsRequested = Database::singleton()->run(
"SELECT COUNT(*) FROM GameJobSessions WHERE UserID = :UserID AND TimeCreated + 60 > UNIX_TIMESTAMP()",
[":UserID" => $UserInfo->id]
)->fetchColumn();
if ($SessionsRequested >= 2) Respond("Ratelimit");
}
function CreateNewSession($Job)
{
global $UserInfo, $IsTeleport;
$Ticket = generateUUID();
$SecurityTicket = generateUUID();
CheckRatelimit();
Database::singleton()->run(
"INSERT INTO GameJobSessions (Ticket, SecurityTicket, JobID, IsTeleport, UserID, TimeCreated)
VALUES (:Ticket, :SecurityTicket, :JobID, :IsTeleport, :UserID, UNIX_TIMESTAMP())",
[":Ticket" => $Ticket, ":SecurityTicket" => $SecurityTicket, ":JobID" => $Job->JobID, ":IsTeleport" => (int)$IsTeleport, ":UserID" => $UserInfo->id]
);
Respond("Joining", $Job->JobID, $Job->Version, "http://{$_SERVER['HTTP_HOST']}/Game/Join.ashx?JobTicket={$Ticket}");
}
if ($Request == "RequestGame") // clicking the "play" button
{
$PlaceID = API::GetParameter("GET", "placeId", "int");
$PlaceInfo = Database::singleton()->run("SELECT * FROM assets WHERE id = :PlaceID", [":PlaceID" => $PlaceID])->fetch(\PDO::FETCH_OBJ);
if (!$PlaceInfo || $PlaceInfo->type != 9) Respond("Error");
if ($IsTeleport && $PlaceInfo->Version != 2012) Respond("Error"); // TODO - add multi-client support for individual places?
if (!Games::CanPlayGame($PlaceInfo))
{
Respond("Error");
}
// check for an available game job
$AvailableJob = Database::singleton()->run(
"SELECT GameJobs.* FROM GameJobs
WHERE NOT Status IN (\"Closed\", \"Crashed\")
AND PlaceID = :PlaceID
AND PlayerCount < :MaxPlayers
LIMIT 1",
[":PlaceID" => $PlaceID, ":MaxPlayers" => $PlaceInfo->MaxPlayers]
)->fetch(\PDO::FETCH_OBJ);
if ($AvailableJob)
{
if ($AvailableJob->Status == "Ready")
{
CreateNewSession($AvailableJob);
}
else
{
Respond($AvailableJob->Status == "Pending" ? "Waiting" : "Loading", $AvailableJob->JobID);
}
}
else
{
CheckRatelimit();
// get an available server
$GameServer = Database::singleton()->run(
"SELECT * FROM GameServers
WHERE Online
AND LastUpdated + 65 > UNIX_TIMESTAMP()
AND ActiveJobs < MaximumJobs
AND CpuUsage < 90
AND AvailableMemory > 1024
ORDER BY Priority ASC LIMIT 1"
)->fetch(\PDO::FETCH_OBJ);
if (!$GameServer) Respond("Expired");
$JobID = generateUUID();
$ServersRequested = Database::singleton()->run(
"SELECT COUNT(*) FROM GameJobs WHERE RequestedBy = :UserID AND TimeCreated + 60 > UNIX_TIMESTAMP()",
[":UserID" => $UserInfo->id]
)->fetchColumn();
if ($ServersRequested >= 2) Respond("Error");
// request a new job
$GameJob = Database::singleton()->run(
"INSERT INTO GameJobs (RequestedBy, JobID, ServerID, Version, PlaceID, TimeCreated, LastUpdated)
VALUES (:UserID, :JobID, :ServerID, :Version, :PlaceID, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())",
[
":UserID" => $UserInfo->id,
":JobID" => $JobID,
":ServerID" => $GameServer->ServerID,
":Version" => $PlaceInfo->Version,
":PlaceID" => $PlaceInfo->id
]
);
$Request = "{\"Operation\":\"OpenJob\", \"JobID\":\"{$JobID}\", \"Version\":{$PlaceInfo->Version}, \"PlaceID\":{$PlaceInfo->id}}";
$Socket = fsockopen($GameServer->ServiceAddress, $GameServer->ServicePort);
fwrite($Socket, $Request);
fclose($Socket);
Respond("Waiting", $JobID);
}
}
else if ($Request == "RequestFollowUser") // joining a user's game
{
}
else if ($Request == "RequestGameJob" || $Request == "CheckGameJobStatus")
{
$JobID = API::GetParameter("GET", "jobId", "string");
// check for an available game job
$AvailableJob = Database::singleton()->run(
"SELECT GameJobs.*, assets.MaxPlayers FROM GameJobs
INNER JOIN assets ON assets.id = PlaceID
WHERE JobID = :JobID",
[":JobID" => $JobID]
)->fetch(\PDO::FETCH_OBJ);
if (!Games::CanPlayGame((int)$AvailableJob->PlaceID))
{
Respond("Error");
}
if (!$AvailableJob) Respond("Error");
if ($AvailableJob->Status == "Closed" || $AvailableJob->Status == "Crashed") Respond("GameEnded");
if ($AvailableJob->PlayerCount >= $AvailableJob->MaxPlayers) Respond("GameFull");
if ($AvailableJob->Status == "Pending") Respond("Waiting", $JobID);
if ($AvailableJob->Status == "Loading") Respond("Loading", $JobID);
CreateNewSession($AvailableJob);
}

View File

@ -1,26 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "GET", "logged_in" => true, "secure" => true]);
$JobID = API::GetParameter("GET", "jobId", "string");
$JobInfo = Database::singleton()->run("SELECT * FROM GameJobs WHERE JobID = :JobID", [":JobID" => $JobID])->fetch(\PDO::FETCH_OBJ);
if (!$JobInfo) API::respond(200, false, "The requested game does not exist");
$ServerInfo = Database::singleton()->run("SELECT * FROM GameServers WHERE ServerID = :ServerID", [":ServerID" => $JobInfo->ServerID])->fetch(\PDO::FETCH_OBJ);
$PlaceInfo = Database::singleton()->run("SELECT * FROM assets WHERE id = :PlaceID", [":PlaceID" => $JobInfo->PlaceID])->fetch(\PDO::FETCH_OBJ);
if ($PlaceInfo->creator != SESSION["user"]["id"] && !Users::IsAdmin(Users::STAFF_ADMINISTRATOR)) API::respond(200, false, "The requested game cannot be shut down");
if ($JobInfo->Status == "Closed" || $JobInfo->Status == "Crashed") API::respond(200, false, "The requested game has already been shut down");
if ($JobInfo->Status != "Ready") API::respond(200, false, "The requested game cannot be shut down");
$Request = "{\"Operation\":\"CloseJob\", \"JobID\":\"{$JobID}\"}";
$Socket = fsockopen($ServerInfo->ServiceAddress, $ServerInfo->ServicePort);
fwrite($Socket, $Request);
fclose($Socket);
API::respond(200, true, "The requested game has been shut down");

View File

@ -1,55 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(isset($_POST["Page"]) && !is_numeric($_POST["Page"])) API::respond(400, false, "Page is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$Page = $_POST["Page"] ?? 1;
$Members = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if($Rank->Level == 0) API::respond(200, false, "You are not a member of this group");
if(!$Rank->Permissions->CanManageGroupAdmin) API::respond(200, false, "You are not allowed to perform this action");
$MemberCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_members
WHERE GroupID = :GroupID AND Rank < :RankLevel AND NOT Pending",
[":GroupID" => $GroupID, ":RankLevel" => $Rank->Level]
)->fetchColumn();
$Pages = ceil($MemberCount/12);
$Offset = ($Page - 1)*12;
if(!$Pages) API::respond(200, true, "This group does not have any members.");
$MembersQuery = Database::singleton()->run(
"SELECT users.username, users.id, Rank FROM groups_members
INNER JOIN users ON users.id = groups_members.UserID
WHERE GroupID = :GroupID AND Rank < :RankLevel AND NOT Pending
ORDER BY Joined DESC LIMIT 12 OFFSET $Offset",
[":GroupID" => $GroupID, ":RankLevel" => $Rank->Level]
);
while($Member = $MembersQuery->fetch(\PDO::FETCH_OBJ))
{
$Members[] =
[
"UserName" => $Member->username,
"UserID" => $Member->id,
"RoleLevel" => $Member->Rank,
"Avatar" => Thumbnails::GetAvatar($Member->id)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pages, "count" => $MemberCount, "items" => $Members]));

View File

@ -1,47 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST"]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$Roles = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if($Rank->Level == 0) API::respond(200, false, "You are not a member of this group");
if(!$Rank->Permissions->CanManageGroupAdmin) API::respond(200, false, "You are not allowed to perform this action");
if($Rank->Level == 255)
{
$RolesQuery = Database::singleton()->run(
"SELECT * FROM groups_ranks WHERE GroupID = :GroupID ORDER BY Rank ASC",
[":GroupID" => $GroupID]
);
}
else
{
$RolesQuery = Database::singleton()->run(
"SELECT * FROM groups_ranks WHERE GroupID = :GroupID AND Rank < :MyRank ORDER BY Rank ASC",
[":GroupID" => $GroupID, ":MyRank" => $Rank->Level]
);
}
while($Role = $RolesQuery->fetch(\PDO::FETCH_OBJ))
{
$Roles[] =
[
"Name" => htmlspecialchars($Role->Name),
"Description" => htmlspecialchars($Role->Description),
"Rank" => $Role->Rank,
"Permissions" => json_decode($Role->Permissions)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "items" => $Roles]));

View File

@ -1,114 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Recipient"])) API::respond(400, false, "Recipient is not set");
if(!isset($_POST["Type"])) API::respond(400, false, "Type is not set");
if(!in_array($_POST["Type"], ["ally", "enemy"])) API::respond(400, false, "Type is not valid");
$GroupID = $_POST["GroupID"] ?? false;
$RecipientName = $_POST["Recipient"] ?? false;
$Type = $_POST["Type"] ?? false;
$Groups = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$Recipient = Database::singleton()->run("SELECT * FROM groups WHERE name = :GroupName", [":GroupName" => $RecipientName]);
$RecipientInfo = $Recipient->fetch(\PDO::FETCH_OBJ);
if(!$Recipient->rowCount()) API::respond(200, false, "No group with that name exists");
$MyRank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$MyRank->Permissions->CanManageRelationships) API::respond(200, false, "You are not allowed to manage this group's relationships");
if($RecipientInfo->id == $GroupID)
{
if($Type == "ally") API::respond(200, false, "You cannot send an ally request to your own group");
else if($Type == "enemy") API::respond(200, false, "You cannot declare your own group as an enemy");
}
$Relationship = Database::singleton()->run(
"SELECT * FROM groups_relationships WHERE :GroupID IN (Declarer, Recipient) AND :Recipient IN (Declarer, Recipient) AND Status != 2",
[":GroupID" => $GroupID, ":Recipient" => $RecipientInfo->id]
);
$RelationshipInfo = $Relationship->fetch(\PDO::FETCH_OBJ);
if($Relationship->rowCount())
{
if($RelationshipInfo->Type == "Allies")
{
if($RelationshipInfo->Status == 0)
{
if($RelationshipInfo->Declarer == $GroupID)
{
API::respond(200, false, "You already have an outgoing ally request to this group");
}
else
{
API::respond(200, false, "You already have an incoming ally request from this group");
}
}
else if($RelationshipInfo->Status == 1)
{
API::respond(200, false, "You are already allies with this group!");
}
}
else if($RelationshipInfo->Type == "Enemies")
{
API::respond(200, false, "You are already enemies with this group!");
}
}
if($Type == "ally")
{
$LastRequest = Database::singleton()->run("SELECT Declared FROM groups_relationships WHERE Declarer = :GroupID AND Declared+3600 > UNIX_TIMESTAMP()", [":GroupID" => $GroupID]);
if($LastRequest->rowCount())
API::respond(429, false, "Please wait ".GetReadableTime($LastRequest->fetchColumn(), ["RelativeTime" => "1 hour"])." before sending a new ally request");
Database::singleton()->run(
"INSERT INTO groups_relationships (Type, Declarer, Recipient, Status, Declared)
VALUES (\"Allies\", :GroupID, :Recipient, 0, UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":Recipient" => $RecipientInfo->id]
);
Groups::LogAction(
$GroupID, "Send Ally Request",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> sent an ally request to <a href=\"/groups?gid=%d\">%s</a>",
SESSION["user"]["id"], SESSION["user"]["username"], $RecipientInfo->id, htmlspecialchars($RecipientInfo->name)
)
);
API::respond(200, true, "Ally request has been sent to ".Polygon::FilterText($RecipientInfo->name));
}
else if($Type == "enemy")
{
$LastRequest = Database::singleton()->run("SELECT Declared FROM groups_relationships WHERE Declarer = :GroupID AND Declared+3600 > UNIX_TIMESTAMP()", [":GroupID" => $GroupID]);
if($LastRequest->rowCount())
API::respond(429, false, "Please wait ".GetReadableTime($LastRequest->fetchColumn(), ["RelativeTime" => "1 hour"])." before sending a new ally request");
Database::singleton()->run(
"INSERT INTO groups_relationships (Type, Declarer, Recipient, Status, Declared, Established)
VALUES (\"Enemies\", :GroupID, :Recipient, 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":Recipient" => $RecipientInfo->id]
);
Groups::LogAction(
$GroupID, "Create Enemy",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> declared <a href=\"/groups?gid=%d\">%s</a> as an enemy",
SESSION["user"]["id"], SESSION["user"]["username"], $RecipientInfo->id, htmlspecialchars($RecipientInfo->name)
)
);
API::respond(200, true, Polygon::FilterText($RecipientInfo->name)." is now your enemy!");
}
API::respond(200, false, "An unexpected error occurred");

View File

@ -1,61 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["UserID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["UserID"])) API::respond(400, false, "GroupID is not a number");
if(isset($_POST["RoleLevel"]) && !is_numeric($_POST["RoleLevel"])) API::respond(400, false, "RoleLevel is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$UserID = $_POST["UserID"] ?? false;
$RoleLevel = $_POST["RoleLevel"] ?? false;
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$MyRole = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
$UserRole = Groups::GetUserRank($UserID, $GroupID);
if($MyRole->Level == 0) API::respond(200, false, "You are not a member of this group");
if(!$MyRole->Permissions->CanManageGroupAdmin) API::respond(200, false, "You are not allowed to perform this action");
if($UserRole->Level == 0) API::respond(200, false, "That user is not a member of this group");
if($RoleLevel !== false)
{
if(!Groups::GetRankInfo($GroupID, $RoleLevel)) API::respond(200, false, "That role does not exist");
if($RoleLevel == 0 || $RoleLevel == 255) API::respond(200, false, "That role cannot be manually assigned to a member");
if($UserRole->Level == $RoleLevel) API::respond(200, false, "The role you tried to assign is the user's current role");
if($MyRole->Level <= $RoleLevel) API::respond(200, false, "You can only assign roles lower than yours");
if($MyRole->Level <= $UserRole->Level) API::respond(200, false, "You can only modify the role of a user who is a role lower than yours");
Database::singleton()->run(
"UPDATE groups_members SET Rank = :RoleLevel WHERE GroupID = :GroupID AND UserID = :UserID",
[":GroupID" => $GroupID, ":UserID" => $UserID, ":RoleLevel" => $RoleLevel]
);
$UserName = Users::GetNameFromID($UserID);
$RoleName = Groups::GetRankInfo($GroupID, $RoleLevel)->Name;
$Action = $RoleLevel > $UserRole->Level ? "promoted" : "demoted";
Groups::LogAction(
$GroupID, "Change Rank",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> %s <a href=\"/user?ID=%d\">%s</a> from %s to %s",
SESSION["user"]["id"], SESSION["user"]["username"], $Action, $UserID, $UserName, htmlspecialchars($UserRole->Name), htmlspecialchars($RoleName)
)
);
API::respond(200, true, "$UserName has been $Action to " . htmlspecialchars($RoleName));
}
API::respond(200, true, "OK");

View File

@ -1,108 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Recipient"])) API::respond(400, false, "Recipient is not set");
if(!is_numeric($_POST["Recipient"])) API::respond(400, false, "Recipient is not a number");
if(!isset($_POST["Action"])) API::respond(400, false, "Action is not set");
if(!in_array($_POST["Action"], ["accept", "decline"])) API::respond(400, false, "Action is not valid");
$GroupID = $_POST["GroupID"] ?? false;
$Recipient = $_POST["Recipient"] ?? false;
$Action = $_POST["Action"] ?? false;
$Groups = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
if(!Groups::GetGroupInfo($Recipient)) API::respond(200, false, "Recipient group does not exist");
$MyRank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$MyRank->Permissions->CanManageRelationships) API::respond(200, false, "You are not allowed to manage this group's relationships");
$Relationship = Database::singleton()->run(
"SELECT groups_relationships.*, groups.name FROM groups_relationships
INNER JOIN groups ON groups.id = (CASE WHEN Declarer = :GroupID THEN Recipient ELSE Declarer END)
WHERE :GroupID IN (Declarer, Recipient) AND :Recipient IN (Declarer, Recipient) AND Status != 2",
[":GroupID" => $GroupID, ":Recipient" => $Recipient]
);
$RelationshipInfo = $Relationship->fetch(\PDO::FETCH_OBJ);
if(!$Relationship->rowCount()) API::respond(200, false, "You are not in a relationship with this group");
if($Action == "accept")
{
if($RelationshipInfo->Type == "Enemies") API::respond(200, false, "You cannot accept an enemy relationship");
if($RelationshipInfo->Status != 0) API::respond(200, false, "You are already in a relationship with this group");
Database::singleton()->run(
"UPDATE groups_relationships SET Status = 1, Established = UNIX_TIMESTAMP() WHERE ID = :RelationshipID",
[":RelationshipID" => $RelationshipInfo->ID]
);
Groups::LogAction(
$GroupID, "Accept Ally Request",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> accepted an ally request from <a href=\"/groups?gid=%d\">%s</a>",
SESSION["user"]["id"], SESSION["user"]["username"], $Recipient, htmlspecialchars($RelationshipInfo->name)
)
);
API::respond(200, true, "You have accepted {$RelationshipInfo->name}'s ally request");
}
else if($Action == "decline")
{
Database::singleton()->run(
"UPDATE groups_relationships SET Status = 2, Broken = UNIX_TIMESTAMP() WHERE ID = :RelationshipID",
[":RelationshipID" => $RelationshipInfo->ID]
);
if($RelationshipInfo->Type == "Allies")
{
if($RelationshipInfo->Status == 0)
{
Groups::LogAction(
$GroupID, "Decline Ally Request",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> declined an ally request from <a href=\"/groups?gid=%d\">%s</a>",
SESSION["user"]["id"], SESSION["user"]["username"], $Recipient, htmlspecialchars($RelationshipInfo->name)
)
);
API::respond(200, true, "You have declined ".Polygon::FilterText($RelationshipInfo->name)."'s ally request");
}
else if($RelationshipInfo->Status == 1)
{
Groups::LogAction(
$GroupID, "Delete Ally",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> removed <a href=\"/groups?gid=%d\">%s</a> as an ally",
SESSION["user"]["id"], SESSION["user"]["username"], $Recipient, htmlspecialchars($RelationshipInfo->name)
)
);
API::respond(200, true, "You are no longer allies with ".Polygon::FilterText($RelationshipInfo->name));
}
}
else if($RelationshipInfo->Type == "Enemies")
{
Groups::LogAction(
$GroupID, "Delete Enemy",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> removed <a href=\"/groups?gid=%d\">%s</a> as an enemy",
SESSION["user"]["id"], SESSION["user"]["username"], $Recipient, htmlspecialchars($RelationshipInfo->name)
)
);
API::respond(200, true, "You are no longer enemies with ".Polygon::FilterText($RelationshipInfo->name));
}
}
API::respond(200, false, "An unexpected error occurred");

View File

@ -1,170 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Roles"])) API::respond(400, false, "Roles is not set");
$GroupID = $_POST["GroupID"];
$Roles = json_decode($_POST["Roles"]);
if(!$Roles) API::respond(400, false, "Roles is not valid JSON");
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$MyRole = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if($MyRole->Level == 0) API::respond(200, false, "You are not a member of this group");
if($MyRole->Level != 255) API::respond(200, false, "You are not allowed to perform this action");
function FindRolesWithRank($Rank)
{
global $Roles;
$Count = 0;
foreach ($Roles as $Role)
{
if (!isset($Role->Rank)) continue;
if ($Role->Rank == $Rank) $Count += 1;
}
return $Count;
}
function FindRoleWithRank($Rank)
{
global $Roles;
foreach ($Roles as $Role)
{
if (!isset($Role->Rank)) continue;
if ($Role->Rank == $Rank) return $Role;
}
return false;
}
$Permissions =
[
"CanViewGroupWall",
"CanViewGroupStatus",
"CanPostOnGroupWall",
"CanPostGroupStatus",
"CanDeleteGroupWallPosts",
"CanAcceptJoinRequests",
"CanKickLowerRankedMembers",
"CanRoleLowerRankedMembers",
"CanManageRelationships",
"CanCreateAssets",
"CanConfigureAssets",
"CanSpendFunds",
"CanManageGames",
"CanManageGroupAdmin",
"CanViewAuditLog"
];
if(FindRolesWithRank(0) == 0) API::respond(200, false, "You can not remove the Guest role");
if(FindRolesWithRank(255) == 0) API::respond(200, false, "You can not remove the Owner role");
if(count($Roles) < 3) API::respond(200, false, "There must be at least three roles");
if(count($Roles) > 10) API::respond(200, false, "There must be no more than ten roles");
foreach($Roles as $Role)
{
if(!isset($Role->Name) || !isset($Role->Description) || !isset($Role->Rank) || !isset($Role->Permissions))
API::respond(200, false, "Roles are missing parameters");
if($Role->Rank < 0 || $Role->Rank > 255) API::respond(200, false, "Each role must have a rank number between 0 and 255");
if(FindRolesWithRank($Role->Rank) > 1) API::respond(200, false, "Each role must have a unique rank number");
$CurrentRole = Groups::GetRankInfo($GroupID, $Role->Rank);
if($CurrentRole === false) $Role->Action = "Create";
else $Role->Action = "Update";
if($Role->Rank == 0)
{
if($Role->Name != $CurrentRole->Name || $Role->Description != $CurrentRole->Description)
API::respond(200, false, "You can not modify the Guest role");
}
if($Role->Rank == 255 && $Role->Permissions != $CurrentRole->Permissions)
API::respond(200, false, "You can not modify the permissions of the Owner role");
if(strlen($Role->Name) < 3) API::respond(200, false, "Role names must be at least 3 characters long");
if(strlen($Role->Name) > 15) API::respond(200, false, "Role names must be no longer than 15 characters");
if(strlen($Role->Description) < 3) API::respond(200, false, "Role description must at least 3 characters long");
if(strlen($Role->Description) > 64) API::respond(200, false, "Role description must be no longer than 64 characters");
foreach ($Permissions as $Permission)
{
if(!isset($Role->Permissions->$Permission)) API::respond(200, false, "Role is missing a permission");
if(!is_bool($Role->Permissions->$Permission)) API::respond(200, false, "Role permission property must have a boolean value");
}
if(count((array)$Role->Permissions) != count($Permissions)) API::respond(200, false, "Role permissions contains an incorrect number of permissions");
}
foreach($Roles as $Role)
{
if($Role->Action == "Create")
{
// if(SESSION["user"]["id"] == 1) echo "Creating Role {$Role->Rank}\r\n";
Database::singleton()->run(
"INSERT INTO groups_ranks (GroupID, Name, Description, Rank, Permissions, Created)
VALUES (:GroupID, :Name, :Description, :Rank, :Permissions, UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":Name" => $Role->Name, ":Description" => $Role->Description, ":Rank" => $Role->Rank, ":Permissions" => json_encode($Role->Permissions)]
);
}
}
$GroupRoles = Groups::GetGroupRanks($GroupID, true);
while($ExistingRole = $GroupRoles->fetch(\PDO::FETCH_OBJ))
{
$Role = FindRoleWithRank($ExistingRole->Rank);
if($Role == false)
{
// if(SESSION["user"]["id"] == 1) echo "Deleting Role {$ExistingRole->Rank}\r\n";
// for this one we gotta move the members with a role thats being deleted to the lowest rank
// slight issue with this is for a brief period, members assigned the role thats being deleted
// will have no role - if the timing is just right this could mess up the view of the group page
// delete the rank by the oldest id - so that we dont accidentally delete the new one
Database::singleton()->run(
"DELETE FROM groups_ranks WHERE GroupID = :GroupID AND Rank = :Rank ORDER BY id ASC LIMIT 1",
[":GroupID" => $GroupID, ":Rank" => $ExistingRole->Rank]
);
$NewRank = Database::singleton()->run(
"SELECT Rank FROM polygon.groups_ranks WHERE GroupID = :GroupID AND Rank != 0 ORDER BY Rank ASC LIMIT 1",
[":GroupID" => $GroupID]
)->fetchColumn();
// if(SESSION["user"]["id"] == 1) echo "Updating existing members to {$NewRank}\r\n";
Database::singleton()->run(
"UPDATE groups_members SET Rank = :NewRank WHERE GroupID = :GroupID AND Rank = :Rank",
[":GroupID" => $GroupID, ":Rank" => $ExistingRole->Rank, ":NewRank" => $NewRank]
);
}
else if(isset($Role->Action) && $Role->Action == "Update")
{
// if(SESSION["user"]["id"] == 1) echo "Updating Role {$Role->Rank}\r\n";
Database::singleton()->run(
"UPDATE groups_ranks SET Name = :Name, Description = :Description, Permissions = :Permissions
WHERE GroupID = :GroupID AND Rank = :Rank",
[":GroupID" => $GroupID, ":Name" => $Role->Name, ":Description" => $Role->Description, ":Rank" => $Role->Rank, ":Permissions" => json_encode($Role->Permissions)]
);
}
}
die(json_encode(["status" => 200, "success" => true, "message" => "Group roles have successfully been updated"]));

View File

@ -1,44 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["PostID"])) API::respond(400, false, "PostID is not set");
if(!is_numeric($_POST["PostID"])) API::respond(400, false, "PostID is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$PostID = $_POST["PostID"] ?? false;
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$Rank->Permissions->CanDeleteGroupWallPosts) API::respond(200, false, "You are not allowed to delete wall posts on this group");
$PostInfo = Database::singleton()->run(
"SELECT * FROM groups_wall WHERE id = :PostID AND :GroupID = :GroupID",
[":PostID" => $PostID, ":GroupID" => $GroupID]
)->fetch(\PDO::FETCH_OBJ);
if(!$PostInfo) API::respond(200, false, "Wall post does not exist");
Groups::LogAction(
$GroupID, "Delete Post",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> deleted post \"%s\" by <a href=\"/user?ID=%d\">%s</a>",
SESSION["user"]["id"], SESSION["user"]["username"], htmlspecialchars($PostInfo->Content), $PostInfo->PosterID, Users::GetNameFromID($PostInfo->PosterID)
)
);
Database::singleton()->run(
"DELETE FROM groups_wall WHERE id = :PostID AND :GroupID = :GroupID",
[":PostID" => $PostID, ":GroupID" => $GroupID]
);
API::respond(200, true, "OK");

View File

@ -1,79 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST"]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(isset($_POST["Page"]) && !is_numeric($_POST["Page"])) API::respond(400, false, "Page is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$Filter = $_POST["Filter"] ?? "All Actions";
$Page = $_POST["Page"] ?? 1;
$Logs = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$MyRank = Groups::GetUserRank(SESSION["user"]["id"] ?? 0, $GroupID);
if(!$MyRank->Permissions->CanViewAuditLog) API::respond(200, false, "You cannot audit this group");
if($Filter == "All Actions")
{
$LogCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_audit WHERE GroupID = :GroupID",
[":GroupID" => $GroupID]
)->fetchColumn();
}
else
{
$LogCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_audit WHERE GroupID = :GroupID AND Category = :Action",
[":GroupID" => $GroupID, ":Action" => $Filter]
)->fetchColumn();
}
$Pages = ceil($LogCount/20);
$Offset = ($Page - 1)*20;
if(!$Pages) API::respond(200, true, "This group does not have any logs for this action.");
if($Filter == "All Actions")
{
$LogsQuery = Database::singleton()->run(
"SELECT groups_audit.*, users.username FROM groups_audit
INNER JOIN users ON users.id = UserId
WHERE GroupID = :GroupID
ORDER BY Time DESC LIMIT 20 OFFSET $Offset",
[":GroupID" => $GroupID]
);
}
else
{
$LogsQuery = Database::singleton()->run(
"SELECT groups_audit.*, users.username FROM groups_audit
INNER JOIN users ON users.id = UserId
WHERE GroupID = :GroupID AND Category = :Action
ORDER BY Time DESC LIMIT 20 OFFSET $Offset",
[":GroupID" => $GroupID, ":Action" => $Filter]
);
}
while($Log = $LogsQuery->fetch(\PDO::FETCH_OBJ))
{
$Logs[] =
[
"Date" => date('j/n/y G:i', $Log->Time),
"UserName" => $Log->username,
"UserID" => $Log->UserID,
"UserAvatar" => Thumbnails::GetAvatar($Log->UserID),
"Rank" => Polygon::FilterText($Log->Rank),
"Description" => Polygon::FilterText($Log->Description, false)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pages, "items" => $Logs]));

View File

@ -1,53 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST"]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["RankLevel"])) API::respond(400, false, "RankLevel is not set");
if(!is_numeric($_POST["RankLevel"])) API::respond(400, false, "RankLevel is not a number");
if(isset($_POST["Page"]) && !is_numeric($_POST["Page"])) API::respond(400, false, "Page is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$RankID = $_POST["RankLevel"] ?? false;
$Members = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
if(!Groups::GetRankInfo($GroupID, $RankID)) API::respond(200, false, "Group rank does not exist");
$MemberCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_members WHERE GroupID = :GroupID AND Rank = :RankID AND NOT Pending",
[":GroupID" => $GroupID, ":RankID" => $RankID]
)->fetchColumn();
$Pagination = Pagination($_POST["Page"] ?? 1, $MemberCount, 12);
if($Pagination->Pages == 0) API::respond(200, true, "This group does not have any members of this rank.");
$MembersQuery = Database::singleton()->run(
"SELECT users.username, users.id, Rank FROM groups_members
INNER JOIN users ON users.id = groups_members.UserID
WHERE GroupID = :GroupID AND Rank = :RankID AND NOT Pending
ORDER BY Joined DESC LIMIT 12 OFFSET :Offset",
[":GroupID" => $GroupID, ":RankID" => $RankID, ":Offset" => $Pagination->Offset]
);
while($Member = $MembersQuery->fetch(\PDO::FETCH_OBJ))
{
$Members[] =
[
"UserName" => $Member->username,
"UserID" => $Member->id,
"RoleLevel" => $Member->Rank,
"Avatar" => Thumbnails::GetAvatar($Member->id)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pagination->Pages, "count" => $MemberCount, "items" => $Members]));

View File

@ -1,82 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST"]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Type"])) API::respond(400, false, "Type is not set");
if(!in_array($_POST["Type"], ["Pending Allies", "Allies", "Enemies"])) API::respond(400, false, "Type is not valid");
if(isset($_POST["Page"]) && !is_numeric($_POST["Page"])) API::respond(400, false, "Page is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$Type = $_POST["Type"] ?? false;
$Page = $_POST["Page"] ?? 1;
$Groups = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
if($Type == "Pending Allies")
{
if(!SESSION) API::respond(200, false, "You are not allowed to get this group's pending allies");
$MyRank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$MyRank->Permissions->CanManageRelationships) API::respond(200, false, "You are not allowed to get this group's pending allies");
$GroupsCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_relationships WHERE Recipient = :GroupID AND Type = \"Allies\" AND Status = 0",
[":GroupID" => $GroupID]
)->fetchColumn();
}
else
{
$GroupsCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_relationships WHERE :GroupID IN (Declarer, Recipient) AND Type = :Type AND Status = 1",
[":GroupID" => $GroupID, ":Type" => $Type]
)->fetchColumn();
}
$Pages = ceil($GroupsCount/12);
$Offset = ($Page - 1)*12;
if(!$Pages) API::respond(200, true, "This group does not have any $Type");
if($Type == "Pending Allies")
{
$GroupsQuery = Database::singleton()->run(
"SELECT groups.name, groups.id, groups.emblem, groups.MemberCount FROM groups_relationships
INNER JOIN groups ON groups.id = (CASE WHEN Declarer = :GroupID THEN Recipient ELSE Declarer END)
WHERE Recipient = :GroupID AND Type = \"Allies\" AND Status = 0
ORDER BY Declared DESC LIMIT 12 OFFSET $Offset",
[":GroupID" => $GroupID]
);
}
else
{
$GroupsQuery = Database::singleton()->run(
"SELECT groups.name, groups.id, groups.emblem, groups.MemberCount FROM groups_relationships
INNER JOIN groups ON groups.id = (CASE WHEN Declarer = :GroupID THEN Recipient ELSE Declarer END)
WHERE :GroupID IN (Declarer, Recipient) AND Type = :Type AND Status = 1
ORDER BY Established DESC LIMIT 12 OFFSET $Offset",
[":GroupID" => $GroupID, ":Type" => $Type]
);
}
while($Group = $GroupsQuery->fetch(\PDO::FETCH_OBJ))
{
$Groups[] =
[
"Name" => Polygon::FilterText($Group->name),
"ID" => $Group->id,
"MemberCount" => $Group->MemberCount,
"Emblem" => Thumbnails::GetAssetFromID($Group->emblem)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pages, "items" => $Groups]));

View File

@ -1,55 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST"]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(isset($_POST["Page"]) && !is_numeric($_POST["Page"])) API::respond(400, false, "Page is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$Wall = [];
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
if(SESSION) $Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
else $Rank = Groups::GetRankInfo($GroupID, 0);
if(!$Rank->Permissions->CanViewGroupWall) API::respond(200, false, "You are not allowed to view this group wall");
$PostCount = Database::singleton()->run(
"SELECT COUNT(*) FROM groups_wall WHERE GroupID = :GroupID AND NOT Deleted",
[":GroupID" => $GroupID]
)->fetchColumn();
$Pagination = Pagination($_POST["Page"] ?? 1, $PostCount, 15);
if($Pagination->Pages == 0) API::respond(200, true, "This group does not have any wall posts.");
$PostQuery = Database::singleton()->run(
"SELECT groups_wall.id, users.username AS PosterName, PosterID, Content, TimePosted FROM groups_wall
INNER JOIN users ON users.id = PosterID WHERE GroupID = :GroupID AND NOT Deleted
ORDER BY TimePosted DESC LIMIT 15 OFFSET :Offset",
[":GroupID" => $GroupID, ":Offset" => $Pagination->Offset]
);
while($Post = $PostQuery->fetch(\PDO::FETCH_OBJ))
{
$Wall[] =
[
"id" => $Post->id,
"username" => $Post->PosterName,
"userid" => $Post->PosterID,
"content" => nl2br(Polygon::FilterText($Post->Content)),
"time" => date('j/n/Y g:i:s A', $Post->TimePosted),
"avatar" => Thumbnails::GetAvatar($Post->PosterID)
];
}
die(json_encode(["status" => 200, "success" => true, "message" => "OK", "pages" => $Pagination->Pages, "count" => $PostCount, "items" => $Wall]));

View File

@ -1,35 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
$GroupID = $_POST["GroupID"] ?? false;
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
if(Groups::CheckIfUserInGroup(SESSION["user"]["id"], $GroupID)) API::respond(200, false, "You are already in this group");
if(Groups::GetUserGroups(SESSION["user"]["id"])->rowCount() >= 20) API::respond(200, false, "You have reached the maximum number of groups");
$RateLimit = Database::singleton()->run("SELECT Joined FROM groups_members WHERE UserID = :UserID AND Joined+300 > UNIX_TIMESTAMP()", [":UserID" => SESSION["user"]["id"]]);
if($RateLimit->rowCount())
API::respond(200, false, "Please wait ".GetReadableTime($RateLimit->fetchColumn(), ["RelativeTime" => "5 minutes"])." before joining a new group");
$RankLevel = Database::singleton()->run(
"SELECT Rank FROM groups_ranks WHERE GroupID = :GroupID AND Rank != 0 ORDER BY Rank ASC LIMIT 1",
[":GroupID" => $GroupID]
)->fetchColumn();
Database::singleton()->run(
"INSERT INTO groups_members (GroupID, UserID, Rank, Joined) VALUES (:GroupID, :UserID, :RankLevel, UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"], ":RankLevel" => $RankLevel]
);
Database::singleton()->run("UPDATE groups SET MemberCount = MemberCount + 1 WHERE id = :GroupID", [":GroupID" => $GroupID]);
API::respond(200, true, "OK");

View File

@ -1,26 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
$GroupID = $_POST["GroupID"] ?? false;
$GroupInfo = Groups::GetGroupInfo($GroupID);
if(!$GroupInfo) API::respond(200, false, "Group does not exist");
if($GroupInfo->creator == SESSION["user"]["id"]) API::respond(200, false, "You are the creator of this group");
if(!Groups::CheckIfUserInGroup(SESSION["user"]["id"], $GroupID)) API::respond(200, false, "You are not in this group");
Database::singleton()->run(
"DELETE FROM groups_members WHERE GroupID = :GroupID AND UserID = :UserID",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"]]
);
Database::singleton()->run("UPDATE groups SET MemberCount = MemberCount - 1 WHERE id = :GroupID", [":GroupID" => $GroupID]);
API::respond(200, true, "OK");

View File

@ -1,59 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\Thumbnails;
use pizzaboxer\ProjectPolygon\Discord;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Content"])) API::respond(400, false, "Content is not set");
$GroupID = $_POST["GroupID"] ?? false;
$Content = $_POST["Content"] ?? false;
$GroupInfo = Groups::GetGroupInfo($GroupID);
if(!$GroupInfo) API::respond(200, false, "Group does not exist");
$Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$Rank->Permissions->CanPostGroupStatus) API::respond(200, false, "You are not allowed to post on this group wall");
if(strlen($Content) < 3) API::respond(200, false, "Group shout must be at least 3 characters long");
if(strlen($Content) > 255) API::respond(200, false, "Group shout can not be longer than 64 characters");
$LastPost = Database::singleton()->run(
"SELECT timestamp FROM feed WHERE groupId = :GroupID AND userId = :UserID AND timestamp+300 > UNIX_TIMESTAMP()",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"]]
);
if($LastPost->rowCount())
API::respond(200, false, "Please wait ".GetReadableTime($LastPost->fetchColumn(), ["RelativeTime" => "5 minutes"])." before posting a group shout");
Groups::LogAction(
$GroupID, "Post Shout",
sprintf(
"<a href=\"/user?ID=%d\">%s</a> changed the group status to: %s",
SESSION["user"]["id"], SESSION["user"]["username"], htmlspecialchars($Content)
)
);
Database::singleton()->run(
"INSERT INTO feed (groupId, userId, text, timestamp) VALUES (:GroupID, :UserID, :Content, UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"], ":Content" => $Content]
);
Discord::SendToWebhook(
[
"username" => $GroupInfo->name,
"content" => $Content."\n(Posted by ".SESSION["user"]["username"].")",
"avatar_url" => Thumbnails::GetAssetFromID($GroupInfo->emblem)
],
Discord::WEBHOOK_KUSH
);
API::respond(200, true, "OK");

View File

@ -1,41 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Groups;
use pizzaboxer\ProjectPolygon\API;
API::initialize(["method" => "POST", "logged_in" => true, "secure" => true]);
if(!isset($_POST["GroupID"])) API::respond(400, false, "GroupID is not set");
if(!is_numeric($_POST["GroupID"])) API::respond(400, false, "GroupID is not a number");
if(!isset($_POST["Content"])) API::respond(400, false, "Content is not set");
$GroupID = $_POST["GroupID"] ?? false;
$Content = $_POST["Content"] ?? false;
if(!Groups::GetGroupInfo($GroupID)) API::respond(200, false, "Group does not exist");
$Rank = Groups::GetUserRank(SESSION["user"]["id"], $GroupID);
if(!$Rank->Permissions->CanPostOnGroupWall) API::respond(200, false, "You are not allowed to post on this group wall");
if(strlen($Content) < 3) API::respond(200, false, "Wall post must be at least 3 characters long");
if(strlen($Content) > 255) API::respond(200, false, "Wall post can not be longer than 255 characters");
$LastPost = Database::singleton()->run(
"SELECT TimePosted FROM groups_wall
WHERE GroupID = :GroupID AND PosterID = :UserID AND TimePosted+60 > UNIX_TIMESTAMP()
ORDER BY TimePosted DESC LIMIT 1",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"]]
);
if(SESSION["user"]["id"] != 1 && $LastPost->rowCount())
API::respond(200, false, "Please wait ".(60-(time()-$LastPost->fetchColumn()))." seconds before posting a new wall post");
Database::singleton()->run(
"INSERT INTO groups_wall (GroupID, PosterID, Content, TimePosted) VALUES (:GroupID, :UserID, :Content, UNIX_TIMESTAMP())",
[":GroupID" => $GroupID, ":UserID" => SESSION["user"]["id"], ":Content" => $Content]
);
API::respond(200, true, "OK");

View File

@ -1,121 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Thumbnails;
$categories =
[
0=>"Bricks",
1=>"Robots",
2=>"Chassis",
3=>"Furniture",
4=>"Roads",
5=>"Billboards",
6=>"Game Objects",
"MyDecals"=>"My Decals",
"FreeDecals"=>"Free Decals",
"MyModels"=>"My Models",
"FreeModels"=>"Free Models"
];
$category = isset($_POST['category']) && isset($categories[$_POST['category']]) ? $_POST['category'] : "FreeModels";
$categoryText = $categories[$category];
$type = strpos($category, "Decals") ? 13 : 10;
$page = $_POST['page'] ?? 1;
$keywd = $_POST['keyword'] ?? false;
if(is_numeric($category)) //static category
{
//$query = $pdo->prepare("SELECT COUNT(*) FROM catalog_items WHERE toolboxCategory = :category");
//$query->bindParam(":category", $categoryText, \PDO::PARAM_STR);
}
else //dynamic category - user assets, catalog assets
{
if(SESSION && strpos($categoryText, "My") !== false) //get assets from inventory
{
$assetCount = Database::singleton()->run(
"SELECT COUNT(*) FROM assets WHERE type = :type AND approved = 1 AND id IN (SELECT assetId FROM ownedAssets WHERE userId = :uid)",
[":uid" => SESSION["user"]["id"], ":type" => $type]
)->fetchColumn();
}
else //get assets from catalog
{
$assetCount = Database::singleton()->run(
"SELECT COUNT(*) FROM assets WHERE type = :type AND approved = 1 AND (name LIKE :q OR description LIKE :q)",
[":type" => $type, ":q" => "%{$keywd}%"]
)->fetchColumn();
}
}
$pagination = Pagination($page, $assetCount, 20);
if(is_numeric($category)) //static category
{
//$query = $pdo->prepare("SELECT * FROM catalog_items WHERE toolboxCategory = :category ORDER BY id ASC LIMIT 20 OFFSET :offset");
//$query->bindParam(":category", $categoryText, \PDO::PARAM_STR);
}
else //dynamic category - user assets, catalog assets
{
if(strpos($categoryText, "My") !== false) //get assets from inventory
{
$assets = Database::singleton()->run(
"SELECT assets.* FROM ownedAssets
INNER JOIN assets ON assets.id = assetId WHERE userId = :uid AND assets.type = :type
ORDER BY timestamp DESC LIMIT 20 OFFSET :offset",
[":uid" => SESSION["user"]["id"], ":type" => $type, ":offset" => $pagination->Offset]
);
}
else //get assets from catalog
{
$assets = Database::singleton()->run(
"SELECT * FROM assets WHERE type = :type AND approved = 1 AND (name LIKE :q OR description LIKE :q)
ORDER BY updated DESC LIMIT 20 OFFSET :offset",
[":type" => $type, ":q" => "%{$keywd}%", ":offset" => $pagination->Offset]
);
}
}
?>
<div id="ToolBoxPage">
<div>
<?php if($pagination->Pages>1) { ?>
<div id="pNavigation" style="display:table">
<div class="Navigation">
<div id="Previous">
<a href="#" onclick="getToolbox('<?=$category?>', '<?=$keywd?>', <?=$pagination->Page-1?>)" id="PreviousPage" <?=$pagination->Page <= 1 ? 'style="visibility:hidden"':''?>><span class="NavigationIndicators">&lt;&lt;</span>
Prev</a>
</div>
<div id="Next">
<a href="#" onclick="getToolbox('<?=$category?>', '<?=$keywd?>', <?=$pagination->Page+1?>)" id="NextPage" <?=$pagination->Page >= $pagination->Pages ? 'style="visibility:hidden"':''?>>Next <span class="NavigationIndicators">&gt;&gt;</span></a>
</div>
<div id="Location">
<span id="PagerLocation"><?=number_format((($pagination->Page-1)*20)+1)?>-<?=number_format($pagination->Page*20)?> of <?=number_format($assetCount)?></span>
</div>
</div>
</div>
<?php } ?>
<div id="ToolboxItems">
<?php while($row = $assets->fetch(\PDO::FETCH_OBJ)) { $name = Polygon::FilterText($row->name); ?>
<a class="ToolboxItem" title="<?=$name?>" href="javascript:insertContent(<?=$row->id?>)" ondragstart="dragRBX(<?=$row->id?>)" onmouseover="this.style.borderStyle='outset'" onmouseout="this.style.borderStyle='solid'" style="border-style: solid;display:inline-block;height:60px;width:60px;cursor:pointer;">
<img width="60" src="<?=Thumbnails::GetAsset($row)?>" border="0" id="img" alt="<?=$name?>">
</a>
<?php } ?>
</div>
<?php if($pagination->Pages>1) { ?>
<div id="pNavigation" style="display:table">
<div class="Navigation">
<div id="Previous">
<a href="#" onclick="getToolbox('<?=$category?>', '<?=$keywd?>', <?=$pagination->Page-1?>)" id="PreviousPage" <?=$pagination->Page <= 1 ? 'style="visibility:hidden"':''?>><span class="NavigationIndicators">&lt;&lt;</span>
Prev</a>
</div>
<div id="Next">
<a href="#" onclick="getToolbox('<?=$category?>', '<?=$keywd?>', <?=$pagination->Page+1?>)" id="NextPage" <?=$pagination->Page >= $pagination->Pages ? 'style="visibility:hidden"':''?>>Next <span class="NavigationIndicators">&gt;&gt;</span></a>
</div>
<div id="Location">
<span id="PagerLocation"><?=number_format((($pagination->Page-1)*20)+1)?>-<?=number_format($pagination->Page*20)?> of <?=number_format($assetCount)?></span>
</div>
</div>
</div>
<?php } ?>
</div>
</div>

View File

@ -1,361 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT']."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\RBXClient;
use pizzaboxer\ProjectPolygon\PageBuilder;
if (!Polygon::IsGameserverAuthorized()) PageBuilder::instance()->errorCode(404);
$ScriptArgs = (object)
[
"jobId" => $_GET["jobId"] ?? "nil",
"placeId" => $_GET["placeId"] ?? "nil",
"port" => $_GET["port"] ?? "nil",
"maxPlayers" => $_GET["maxPlayers"] ?? "nil",
];
header("content-type: text/plain; charset=utf-8");
ob_start();
?>
local injectScriptAssetID = nil
local libraryRegistrationScriptAssetID = nil
local jobId = "<?=$ScriptArgs->jobId?>"
local placeId = <?=$ScriptArgs->placeId?>
local port = <?=$ScriptArgs->port?>
local maxPlayers = <?=$ScriptArgs->maxPlayers?>
local url = "http://<?=$_SERVER["HTTP_HOST"]?>"
local servicesUrl = url
local access = "<?=SITE_CONFIG["keys"]["GameserverAccess"]?>"
local PolygonTickets = {}
-- Signal to PolygonDLLUtilities to set DataModel.jobId
print(game.JobId)
-- StartGame --
pcall(function() game:GetService("ScriptContext"):AddStarterScript(injectScriptAssetID) end)
game:GetService("Visit"):SetUploadUrl("")
game:GetService("RunService"):Run()
-- REQUIRES: StartGanmeSharedArgs.txt
-- REQUIRES: MonitorGameStatus.txt
------------------- UTILITY FUNCTIONS --------------------------
function waitForChild(parent, childName)
while true do
local child = parent:findFirstChild(childName)
if child then
return child
end
parent.ChildAdded:wait()
end
end
-- returns the player object that killed this humanoid
-- returns nil if the killer is no longer in the game
function getKillerOfHumanoidIfStillInGame(humanoid)
-- check for kill tag on humanoid - may be more than one - todo: deal with this
local tag = humanoid:findFirstChild("creator")
-- find player with name on tag
if tag then
local killer = tag.Value
if killer.Parent then -- killer still in game
return killer
end
end
return nil
end
-- send kill and death stats when a player dies
function onDied(victim, humanoid)
local killer = getKillerOfHumanoidIfStillInGame(humanoid)
local victorId = 0
if killer and killer.userId ~= victim.userId then
victorId = killer.userId
print("STAT: kill by " .. victorId .. " of " .. victim.userId)
game:HttpGet(url .. "/Game/Knockouts.ashx?UserID=" .. victorId .. "&" .. access)
print("STAT: death of " .. victim.userId .. " by " .. victorId)
game:HttpGet(url .. "/Game/Wipeouts.ashx?UserID=" .. victim.userId .. "&" .. access)
end
end
-- This code might move to C++
function characterRessurection(player)
if player.Character then
local humanoid = player.Character.Humanoid
humanoid.Died:connect(function() wait(5) player:LoadCharacter() end)
end
end
-----------------------------------END UTILITY FUNCTIONS -------------------------
-----------------------------------"CUSTOM" SHARED CODE----------------------------------
pcall(function() settings().Network.UseInstancePacketCache = true end)
pcall(function() settings().Network.UsePhysicsPacketCache = true end)
--pcall(function() settings()["Task Scheduler"].PriorityMethod = Enum.PriorityMethod.FIFO end)
pcall(function() settings()["Task Scheduler"].PriorityMethod = Enum.PriorityMethod.AccumulatedError end)
--settings().Network.PhysicsSend = 1 -- 1==RoundRobin
pcall(function() settings().Network.PhysicsSend = Enum.PhysicsSendMethod.ErrorComputation2 end)
pcall(function() settings().Network.ExperimentalPhysicsEnabled = true end)
pcall(function() settings().Network.WaitingForCharacterLogRate = 100 end)
pcall(function() settings().Diagnostics:LegacyScriptMode() end)
-----------------------------------START GAME SHARED SCRIPT------------------------------
local assetId = placeId -- might be able to remove this now
local scriptContext = game:GetService('ScriptContext')
pcall(function() scriptContext:AddStarterScript(libraryRegistrationScriptAssetID) end)
scriptContext.ScriptsDisabled = true
pcall(function() game:SetPlaceID(assetId, false) end)
game:GetService("ChangeHistoryService"):SetEnabled(false)
-- establish this peer as the Server
local ns = game:GetService("NetworkServer")
if url~=nil then
pcall(function() game:GetService("Players"):SetAbuseReportUrl(url .. "/AbuseReport/InGameChatHandler.ashx") end)
pcall(function() game:GetService("ScriptInformationProvider"):SetAssetUrl(url .. "/Asset/") end)
pcall(function() game:GetService("ContentProvider"):SetBaseUrl(url .. "/") end)
-- pcall(function() game:GetService("Players"):SetChatFilterUrl(url .. "/Game/ChatFilter.ashx") end)
game:GetService("BadgeService"):SetPlaceId(placeId)
if access~=nil then
game:GetService("BadgeService"):SetAwardBadgeUrl(url .. "/Game/Badge/AwardBadge.ashx?UserID=%d&BadgeID=%d&PlaceID=%d&" .. access)
game:GetService("BadgeService"):SetHasBadgeUrl(url .. "/Game/Badge/HasBadge.ashx?UserID=%d&BadgeID=%d&" .. access)
game:GetService("BadgeService"):SetIsBadgeDisabledUrl(url .. "/Game/Badge/IsBadgeDisabled.ashx?BadgeID=%d&PlaceID=%d&" .. access)
pcall(function() game:GetService("FriendService"):SetMakeFriendUrl(servicesUrl .. "/Friend/CreateFriend?firstUserId=%d&secondUserId=%d&jobId=" .. jobId .. "&" .. access) end)
pcall(function() game:GetService("FriendService"):SetBreakFriendUrl(servicesUrl .. "/Friend/BreakFriend?firstUserId=%d&secondUserId=%d&jobId=" .. jobId .. "&" .. access) end)
pcall(function() game:GetService("FriendService"):SetGetFriendsUrl(servicesUrl .. "/Friend/AreFriends?userId=%d&" .. access) end)
end
game:GetService("BadgeService"):SetIsBadgeLegalUrl("")
game:GetService("InsertService"):SetBaseSetsUrl(url .. "/Game/Tools/InsertAsset.ashx?nsets=10&type=base")
game:GetService("InsertService"):SetUserSetsUrl(url .. "/Game/Tools/InsertAsset.ashx?nsets=20&type=user&userid=%d")
game:GetService("InsertService"):SetCollectionUrl(url .. "/Game/Tools/InsertAsset.ashx?sid=%d")
game:GetService("InsertService"):SetAssetUrl(url .. "/Asset/?id=%d")
game:GetService("InsertService"):SetAssetVersionUrl(url .. "/Asset/?assetversionid=%d")
pcall(function() loadfile(url .. "/Game/LoadPlaceInfo.ashx?PlaceId=" .. placeId)() end)
pcall(function()
if access then
loadfile(url .. "/Game/PlaceSpecificScript.ashx?PlaceId=" .. placeId .. "&" .. access)()
end
end)
end
pcall(function() game:GetService("NetworkServer"):SetIsPlayerAuthenticationRequired(true) end)
settings().Diagnostics.LuaRamLimit = 0
--settings().Network:SetThroughputSensitivity(0.08, 0.01)
--settings().Network.SendRate = 35
--settings().Network.PhysicsSend = 0 -- 1==RoundRobin
--shared["__time"] = 0
--game:GetService("RunService").Stepped:connect(function (time) shared["__time"] = time end)
if placeId~=nil and url~=nil then
-- listen for the death of a Player
function createDeathMonitor(player)
-- we don't need to clean up old monitors or connections since the Character will be destroyed soon
if player.Character then
local humanoid = waitForChild(player.Character, "Humanoid")
humanoid.Died:connect(
function ()
onDied(player, humanoid)
end
)
end
end
-- listen to all Players' Characters
game:GetService("Players").ChildAdded:connect(
function (player)
createDeathMonitor(player)
player.Changed:connect(
function (property)
if property=="Character" then
createDeathMonitor(player)
end
end
)
end
)
end
function InactivityHandler(time)
wait(1)
if #game:GetService("Players"):GetChildren() > 0 then
if time ~= nil then
print("Inactive shutdown timer aborted")
end
return
end
if time == nil then
print("Server is inactive, shutting down in 5 minutes")
time = 0
end
if time == 300 then
game:Shutdown()
end
InactivityHandler(time+1)
end
game:GetService("Players").PlayerAdded:connect(function(player)
print("Player " .. player.userId .. " added")
characterRessurection(player)
player.Changed:connect(function(name)
if name=="Character" then
characterRessurection(player)
end
end)
player.Chatted:connect(function(message, recipient)
print("[" .. player.Name .. "]: " .. message)
-- 1 : needs semicolon
-- 2 : doesn't need semicolon
local commands = {
["ec"] = 1,
["energycell"] = 1,
["reset"] = 1,
["kys"] = 1,
["xlxi"] = 1,
["egg"] = 2,
["pog"] = 2,
["poggers"] = 2
}
if commands[message:sub(2):lower()] == 1 or commands[message:lower()] == 2 then
if player.Character then
local Head = player.Character:FindFirstChild("Head")
if Head then
local Sound = Instance.new("Sound", Head)
Sound.SoundId = "http://polygon.pizzaboxer.xyz/asset/?id=12679"
Sound:Play()
end
player.Character:BreakJoints()
end
end
end)
--[[ if url and access and placeId and player and player.userId then
game:HttpGet(url .. "/Game/ClientPresence.ashx?action=connect&" .. access .. "&Ticket=" .. player.PolygonTicket.Value)
game:HttpGet(url .. "/Game/PlaceVisit.ashx?Ticket=" .. player.PolygonTicket .. "&" .. access)
end --]]
end)
game:GetService("Players").PlayerRemoving:connect(function(player)
print("Player " .. player.userId .. " leaving")
if url and access and placeId and player and player.userId and PolygonTickets[player.userId] ~= nil then
game:HttpGet(url .. "/Game/ClientPresence.ashx?action=disconnect&" .. access .. "&Ticket=" .. PolygonTickets[player.userId])
PolygonTickets[player.userId] = nil
end
InactivityHandler()
end)
-- this is already handled by the arbiter, but this is still here just in case
game.Close:connect(function()
game:HttpGet(url .. "/api/polygongs/update-job?" .. access .. "&JobID=" .. jobId .. "&Status=Closed")
end)
if placeId~=nil and url~=nil then
-- yield so that file load happens in the heartbeat thread
wait()
-- load the game
game:Load(url .. "/asset/?id=" .. placeId .. "&" .. access)
end
ns.ChildAdded:connect(function(replicator)
player = replicator:GetPlayer()
i = 0
if player == nil then
while wait(0.25) do
player = replicator:GetPlayer()
if player ~= nil then break end
if i == 120 then
print("[paclib] kicked incoming connection because could not get player")
replicator:CloseConnection()
return
end
i = i + 1
end
end
if player.CharacterAppearance ~= url .. "/Asset/CharacterFetch.ashx?userId=" ..player.userId.. "&placeId=" .. placeId then
replicator:CloseConnection()
print("[paclib] kicked " .. player.Name .. " because player does not have correct character appearance for this server")
print("[paclib] correct character appearance url: " .. url .. "/Asset/CharacterFetch.ashx?userId=" .. player.userId .. "&placeId=" .. placeId)
print("[paclib] appearance that the server received: " .. player.CharacterAppearance)
return
end
if player:FindFirstChild("PolygonTicket") == nil then
replicator:CloseConnection()
print("[paclib] kicked " .. player.Name .. " because player does not have an authentication ticket")
return
end
-- todo - pass in membership value
response = game:HttpGet(url .. "/api/polygongs/verify-player?Username=" .. player.Name .. "&UserID=" .. player.userId .. "&Ticket=" .. player.PolygonTicket.Value .. "&JobID=" .. jobId .. "&" .. access, true)
if response ~= "True" then
replicator:CloseConnection()
print("[paclib] kicked " .. player.Name .. " because could not validate player")
print("[paclib] validation handler returned: " .. response)
return
end
PolygonTickets[player.userId] = player.PolygonTicket.Value
player.PolygonTicket:Remove()
print("[paclib] " .. player.Name .. " has been authenticated")
if url and access and placeId and player and player.userId then
print("[presence] Submitting " .. player.Name .. "'s client presence...")
game:HttpGet(url .. "/Game/ClientPresence.ashx?action=connect&" .. access .. "&Ticket=" .. PolygonTickets[player.userId])
game:HttpGet(url .. "/Game/PlaceVisit.ashx?Ticket=" .. PolygonTickets[player.userId] .. "&" .. access)
end
end)
-- Now start the connection
ns:Start(port, 15)
scriptContext:SetTimeout(10)
scriptContext.ScriptsDisabled = false
--delay(1, function()
-- loadfile(url .. "/analytics/GamePerfMonitor.ashx")(jobId, placeId)
--end)
game:HttpGet(url .. "/api/polygongs/update-job?" .. access .. "&JobID=" .. jobId .. "&Status=Ready")
InactivityHandler()
------------------------------END START GAME SHARED SCRIPT--------------------------
<?php echo RBXClient::CryptSignScript(ob_get_clean());

View File

@ -1,23 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT']."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\PageBuilder;
use pizzaboxer\ProjectPolygon\API;
if (!Polygon::IsGameserverAuthorized()) PageBuilder::instance()->errorCode(404);
header("content-type: text/plain; charset=utf-8");
$GameserverID = API::GetParameter("POST", "GameserverID", "int");
$CpuUsage = API::GetParameter("POST", "CpuUsage", "int");
$AvailableMemory = API::GetParameter("POST", "AvailableMemory", "int");
Database::singleton()->run("
UPDATE GameServers
SET LastUpdated = UNIX_TIMESTAMP(), CpuUsage = :CpuUsage, AvailableMemory = :AvailableMemory
WHERE ServerID = :GameserverID",
[":CpuUsage" => $CpuUsage, ":AvailableMemory" => $AvailableMemory, ":GameserverID" => $GameserverID]
);
echo "OK";

View File

@ -1,20 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT']."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\PageBuilder;
use pizzaboxer\ProjectPolygon\API;
if (!Polygon::IsGameserverAuthorized()) PageBuilder::instance()->errorCode(404);
header("content-type: text/plain; charset=utf-8");
$GameserverID = API::GetParameter("GET", "GameserverID", "int");
$Online = API::GetParameter("GET", "Online", "int");
Database::singleton()->run(
"UPDATE GameServers SET Online = :Online, ActiveJobs = 0, LastUpdated = UNIX_TIMESTAMP() WHERE ServerID = :GameserverID",
[":Online" => $Online, ":GameserverID" => $GameserverID]
);
echo "OK";

View File

@ -1,72 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT']."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\PageBuilder;
use pizzaboxer\ProjectPolygon\Games;
use pizzaboxer\ProjectPolygon\API;
if (!Polygon::IsGameserverAuthorized()) PageBuilder::instance()->errorCode(404);
header("content-type: text/plain; charset=utf-8");
function AddSQLParameter($Name, $Value)
{
global $Parameters;
global $ParametersSQL;
$ParametersSQL .= ", {$Name} = :{$Name}";
$Parameters[":{$Name}"] = $Value;
}
$JobID = API::GetParameter("GET", "JobID", "string");
$Status = API::GetParameter("GET", "Status", "string");
$MachineAddress = API::GetParameter("GET", "MachineAddress", "string", false);
$ServerPort = API::GetParameter("GET", "ServerPort", "int", false);
$ParametersSQL = "LastUpdated = UNIX_TIMESTAMP()";
$Parameters = [":JobID" => $JobID];
if ($Status !== false) AddSQLParameter("Status", $Status);
if ($MachineAddress !== false) AddSQLParameter("MachineAddress", $MachineAddress);
if ($ServerPort !== false) AddSQLParameter("ServerPort", $ServerPort);
$JobInfo = Games::GetJobInfo($JobID);
// update the job with the specified parameters
Database::singleton()->run(
"UPDATE GameJobs SET {$ParametersSQL} WHERE JobID = :JobID",
$Parameters
);
Database::singleton()->run("UPDATE assets SET LastServerUpdate = UNIX_TIMESTAMP() WHERE id = :PlaceID", [":PlaceID" => $JobInfo->PlaceID]);
if ($JobInfo->Status == $Status) die("OK");
if ($Status == "Loading")
{
// refresh the gameserver's job count
Games::RefreshJobCount($JobInfo->ServerID);
}
else if ($Status == "Ready")
{
// mark place as having a running game
Database::singleton()->run("UPDATE assets SET ServerRunning = 1 WHERE id = :PlaceID", [":PlaceID" => $JobInfo->PlaceID]);
}
else if ($Status == "Closed" || $Status == "Crashed")
{
// refresh the gameserver's job count
Games::RefreshJobCount($JobInfo->ServerID);
// close all player sessions
Database::singleton()->run("UPDATE GameJobs SET PlayerCount = 0 WHERE JobID = :JobID", [":JobID" => $JobID]);
Database::singleton()->run("UPDATE GameJobSessions SET Active = 0 WHERE JobID = :JobID", [":JobID" => $JobID]);
// refresh the game's active players
Games::RefreshActivePlayers($JobInfo->PlaceID);
// refresh running game marker for place
Games::RefreshRunningGameMarker($JobInfo->PlaceID);
}
echo "OK";

View File

@ -1,33 +0,0 @@
<?php require $_SERVER['DOCUMENT_ROOT']."/api/private/core.php";
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\PageBuilder;
use pizzaboxer\ProjectPolygon\API;
if (!Polygon::IsGameserverAuthorized()) PageBuilder::instance()->errorCode(404);
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("content-type: text/plain; charset=utf-8");
$Username = API::GetParameter("GET", "Username", "string");
$UserID = API::GetParameter("GET", "UserID", "string");
$Ticket = API::GetParameter("GET", "Ticket", "string");
$JobID = API::GetParameter("GET", "JobID", "string");
$TicketInfo = Database::singleton()->run(
"SELECT GameJobSessions.*, users.username, users.adminlevel FROM GameJobSessions
INNER JOIN users ON users.id = UserID WHERE SecurityTicket = :Ticket",
[":Ticket" => $Ticket]
)->fetch(\PDO::FETCH_OBJ);
if ($TicketInfo === false) die("False");
if ($TicketInfo->Verified) die("False");
if ($TicketInfo->UserID != $UserID) die("False");
if ($TicketInfo->username != $Username) die("False");
if ($TicketInfo->JobID != $JobID) die("False");
Database::singleton()->run("UPDATE GameJobSessions SET Verified = 1 WHERE SecurityTicket = :Ticket", [":Ticket" => $Ticket]);
die("True");

View File

@ -1,457 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class Core
{
const HEADER_VERSION_SIZE = 4;
const MINIMUM_CIPHERTEXT_SIZE = 84;
const CURRENT_VERSION = "\xDE\xF5\x02\x00";
const CIPHER_METHOD = 'aes-256-ctr';
const BLOCK_BYTE_SIZE = 16;
const KEY_BYTE_SIZE = 32;
const SALT_BYTE_SIZE = 32;
const MAC_BYTE_SIZE = 32;
const HASH_FUNCTION_NAME = 'sha256';
const ENCRYPTION_INFO_STRING = 'DefusePHP|V2|KeyForEncryption';
const AUTHENTICATION_INFO_STRING = 'DefusePHP|V2|KeyForAuthentication';
const BUFFER_BYTE_SIZE = 1048576;
const LEGACY_CIPHER_METHOD = 'aes-128-cbc';
const LEGACY_BLOCK_BYTE_SIZE = 16;
const LEGACY_KEY_BYTE_SIZE = 16;
const LEGACY_HASH_FUNCTION_NAME = 'sha256';
const LEGACY_MAC_BYTE_SIZE = 32;
const LEGACY_ENCRYPTION_INFO_STRING = 'DefusePHP|KeyForEncryption';
const LEGACY_AUTHENTICATION_INFO_STRING = 'DefusePHP|KeyForAuthentication';
/*
* V2.0 Format: VERSION (4 bytes) || SALT (32 bytes) || IV (16 bytes) ||
* CIPHERTEXT (varies) || HMAC (32 bytes)
*
* V1.0 Format: HMAC (32 bytes) || IV (16 bytes) || CIPHERTEXT (varies).
*/
/**
* Adds an integer to a block-sized counter.
*
* @param string $ctr
* @param int $inc
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*
* @psalm-suppress RedundantCondition - It's valid to use is_int to check for overflow.
*/
public static function incrementCounter($ctr, $inc)
{
Core::ensureTrue(
Core::ourStrlen($ctr) === Core::BLOCK_BYTE_SIZE,
'Trying to increment a nonce of the wrong size.'
);
Core::ensureTrue(
\is_int($inc),
'Trying to increment nonce by a non-integer.'
);
// The caller is probably re-using CTR-mode keystream if they increment by 0.
Core::ensureTrue(
$inc > 0,
'Trying to increment a nonce by a nonpositive amount'
);
Core::ensureTrue(
$inc <= PHP_INT_MAX - 255,
'Integer overflow may occur'
);
/*
* We start at the rightmost byte (big-endian)
* So, too, does OpenSSL: http://stackoverflow.com/a/3146214/2224584
*/
for ($i = Core::BLOCK_BYTE_SIZE - 1; $i >= 0; --$i) {
$sum = \ord($ctr[$i]) + $inc;
/* Detect integer overflow and fail. */
Core::ensureTrue(\is_int($sum), 'Integer overflow in CTR mode nonce increment');
$ctr[$i] = \pack('C', $sum & 0xFF);
$inc = $sum >> 8;
}
return $ctr;
}
/**
* Returns a random byte string of the specified length.
*
* @param int $octets
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
public static function secureRandom($octets)
{
self::ensureFunctionExists('random_bytes');
try {
return \random_bytes($octets);
} catch (\Exception $ex) {
throw new Ex\EnvironmentIsBrokenException(
'Your system does not have a secure random number generator.'
);
}
}
/**
* Computes the HKDF key derivation function specified in
* http://tools.ietf.org/html/rfc5869.
*
* @param string $hash Hash Function
* @param string $ikm Initial Keying Material
* @param int $length How many bytes?
* @param string $info What sort of key are we deriving?
* @param string $salt
*
* @throws Ex\EnvironmentIsBrokenException
* @psalm-suppress UndefinedFunction - We're checking if the function exists first.
*
* @return string
*/
public static function HKDF($hash, $ikm, $length, $info = '', $salt = null)
{
static $nativeHKDF = null;
if ($nativeHKDF === null) {
$nativeHKDF = \is_callable('\\hash_hkdf');
}
if ($nativeHKDF) {
if (\is_null($salt)) {
$salt = '';
}
return \hash_hkdf($hash, $ikm, $length, $info, $salt);
}
$digest_length = Core::ourStrlen(\hash_hmac($hash, '', '', true));
// Sanity-check the desired output length.
Core::ensureTrue(
!empty($length) && \is_int($length) && $length >= 0 && $length <= 255 * $digest_length,
'Bad output length requested of HDKF.'
);
// "if [salt] not provided, is set to a string of HashLen zeroes."
if (\is_null($salt)) {
$salt = \str_repeat("\x00", $digest_length);
}
// HKDF-Extract:
// PRK = HMAC-Hash(salt, IKM)
// The salt is the HMAC key.
$prk = \hash_hmac($hash, $ikm, $salt, true);
// HKDF-Expand:
// This check is useless, but it serves as a reminder to the spec.
Core::ensureTrue(Core::ourStrlen($prk) >= $digest_length);
// T(0) = ''
$t = '';
$last_block = '';
for ($block_index = 1; Core::ourStrlen($t) < $length; ++$block_index) {
// T(i) = HMAC-Hash(PRK, T(i-1) | info | 0x??)
$last_block = \hash_hmac(
$hash,
$last_block . $info . \chr($block_index),
$prk,
true
);
// T = T(1) | T(2) | T(3) | ... | T(N)
$t .= $last_block;
}
// ORM = first L octets of T
/** @var string $orm */
$orm = Core::ourSubstr($t, 0, $length);
Core::ensureTrue(\is_string($orm));
return $orm;
}
/**
* Checks if two equal-length strings are the same without leaking
* information through side channels.
*
* @param string $expected
* @param string $given
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return bool
*/
public static function hashEquals($expected, $given)
{
static $native = null;
if ($native === null) {
$native = \function_exists('hash_equals');
}
if ($native) {
return \hash_equals($expected, $given);
}
// We can't just compare the strings with '==', since it would make
// timing attacks possible. We could use the XOR-OR constant-time
// comparison algorithm, but that may not be a reliable defense in an
// interpreted language. So we use the approach of HMACing both strings
// with a random key and comparing the HMACs.
// We're not attempting to make variable-length string comparison
// secure, as that's very difficult. Make sure the strings are the same
// length.
Core::ensureTrue(Core::ourStrlen($expected) === Core::ourStrlen($given));
$blind = Core::secureRandom(32);
$message_compare = \hash_hmac(Core::HASH_FUNCTION_NAME, $given, $blind);
$correct_compare = \hash_hmac(Core::HASH_FUNCTION_NAME, $expected, $blind);
return $correct_compare === $message_compare;
}
/**
* Throws an exception if the constant doesn't exist.
*
* @param string $name
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
*/
public static function ensureConstantExists($name)
{
Core::ensureTrue(
\defined($name),
'Constant '.$name.' does not exists'
);
}
/**
* Throws an exception if the function doesn't exist.
*
* @param string $name
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
*/
public static function ensureFunctionExists($name)
{
Core::ensureTrue(
\function_exists($name),
'function '.$name.' does not exists'
);
}
/**
* Throws an exception if the condition is false.
*
* @param bool $condition
* @param string $message
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
*/
public static function ensureTrue($condition, $message = '')
{
if (!$condition) {
throw new Ex\EnvironmentIsBrokenException($message);
}
}
/*
* We need these strlen() and substr() functions because when
* 'mbstring.func_overload' is set in php.ini, the standard strlen() and
* substr() are replaced by mb_strlen() and mb_substr().
*/
/**
* Computes the length of a string in bytes.
*
* @param string $str
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return int
*/
public static function ourStrlen($str)
{
static $exists = null;
if ($exists === null) {
$exists = \extension_loaded('mbstring') && \ini_get('mbstring.func_overload') !== false && (int)\ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING;
}
if ($exists) {
$length = \mb_strlen($str, '8bit');
Core::ensureTrue($length !== false);
return $length;
} else {
return \strlen($str);
}
}
/**
* Behaves roughly like the function substr() in PHP 7 does.
*
* @param string $str
* @param int $start
* @param int $length
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string|bool
*/
public static function ourSubstr($str, $start, $length = null)
{
static $exists = null;
if ($exists === null) {
$exists = \extension_loaded('mbstring') && \ini_get('mbstring.func_overload') !== false && (int)\ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING;
}
// This is required to make mb_substr behavior identical to substr.
// Without this, mb_substr() would return false, contra to what the
// PHP documentation says (it doesn't say it can return false.)
$input_len = Core::ourStrlen($str);
if ($start === $input_len && !$length) {
return '';
}
if ($start > $input_len) {
return false;
}
// mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP 5.3,
// so we have to find the length ourselves. Also, substr() doesn't
// accept null for the length.
if (! isset($length)) {
if ($start >= 0) {
$length = $input_len - $start;
} else {
$length = -$start;
}
}
if ($length < 0) {
throw new \InvalidArgumentException(
"Negative lengths are not supported with ourSubstr."
);
}
if ($exists) {
$substr = \mb_substr($str, $start, $length, '8bit');
// At this point there are two cases where mb_substr can
// legitimately return an empty string. Either $length is 0, or
// $start is equal to the length of the string (both mb_substr and
// substr return an empty string when this happens). It should never
// ever return a string that's longer than $length.
if (Core::ourStrlen($substr) > $length || (Core::ourStrlen($substr) === 0 && $length !== 0 && $start !== $input_len)) {
throw new Ex\EnvironmentIsBrokenException(
'Your version of PHP has bug #66797. Its implementation of
mb_substr() is incorrect. See the details here:
https://bugs.php.net/bug.php?id=66797'
);
}
return $substr;
}
return \substr($str, $start, $length);
}
/**
* Computes the PBKDF2 password-based key derivation function.
*
* The PBKDF2 function is defined in RFC 2898. Test vectors can be found in
* RFC 6070. This implementation of PBKDF2 was originally created by Taylor
* Hornby, with improvements from http://www.variations-of-shadow.com/.
*
* @param string $algorithm The hash algorithm to use. Recommended: SHA256
* @param string $password The password.
* @param string $salt A salt that is unique to the password.
* @param int $count Iteration count. Higher is better, but slower. Recommended: At least 1000.
* @param int $key_length The length of the derived key in bytes.
* @param bool $raw_output If true, the key is returned in raw binary format. Hex encoded otherwise.
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string A $key_length-byte key derived from the password and salt.
*/
public static function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
// Type checks:
if (! \is_string($algorithm)) {
throw new \InvalidArgumentException(
'pbkdf2(): algorithm must be a string'
);
}
if (! \is_string($password)) {
throw new \InvalidArgumentException(
'pbkdf2(): password must be a string'
);
}
if (! \is_string($salt)) {
throw new \InvalidArgumentException(
'pbkdf2(): salt must be a string'
);
}
// Coerce strings to integers with no information loss or overflow
$count += 0;
$key_length += 0;
$algorithm = \strtolower($algorithm);
Core::ensureTrue(
\in_array($algorithm, \hash_algos(), true),
'Invalid or unsupported hash algorithm.'
);
// Whitelist, or we could end up with people using CRC32.
$ok_algorithms = [
'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
'ripemd160', 'ripemd256', 'ripemd320', 'whirlpool',
];
Core::ensureTrue(
\in_array($algorithm, $ok_algorithms, true),
'Algorithm is not a secure cryptographic hash function.'
);
Core::ensureTrue($count > 0 && $key_length > 0, 'Invalid PBKDF2 parameters.');
if (\function_exists('hash_pbkdf2')) {
// The output length is in NIBBLES (4-bits) if $raw_output is false!
if (! $raw_output) {
$key_length = $key_length * 2;
}
return \hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output);
}
$hash_length = Core::ourStrlen(\hash($algorithm, '', true));
$block_count = \ceil($key_length / $hash_length);
$output = '';
for ($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . \pack('N', $i);
// first iteration
$last = $xorsum = \hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
/**
* @psalm-suppress InvalidOperand
*/
$xorsum ^= ($last = \hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if ($raw_output) {
return (string) Core::ourSubstr($output, 0, $key_length);
} else {
return Encoding::binToHex((string) Core::ourSubstr($output, 0, $key_length));
}
}
}

View File

@ -1,445 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
class Crypto
{
/**
* Encrypts a string with a Key.
*
* @param string $plaintext
* @param Key $key
* @param bool $raw_binary
*
* @throws Ex\EnvironmentIsBrokenException
* @throws \TypeError
*
* @return string
*/
public static function encrypt($plaintext, $key, $raw_binary = false)
{
if (!\is_string($plaintext)) {
throw new \TypeError(
'String expected for argument 1. ' . \ucfirst(\gettype($plaintext)) . ' given instead.'
);
}
if (!($key instanceof Key)) {
throw new \TypeError(
'Key expected for argument 2. ' . \ucfirst(\gettype($key)) . ' given instead.'
);
}
if (!\is_bool($raw_binary)) {
throw new \TypeError(
'Boolean expected for argument 3. ' . \ucfirst(\gettype($raw_binary)) . ' given instead.'
);
}
return self::encryptInternal(
$plaintext,
KeyOrPassword::createFromKey($key),
$raw_binary
);
}
/**
* Encrypts a string with a password, using a slow key derivation function
* to make password cracking more expensive.
*
* @param string $plaintext
* @param string $password
* @param bool $raw_binary
*
* @throws Ex\EnvironmentIsBrokenException
* @throws \TypeError
*
* @return string
*/
public static function encryptWithPassword($plaintext, $password, $raw_binary = false)
{
if (!\is_string($plaintext)) {
throw new \TypeError(
'String expected for argument 1. ' . \ucfirst(\gettype($plaintext)) . ' given instead.'
);
}
if (!\is_string($password)) {
throw new \TypeError(
'String expected for argument 2. ' . \ucfirst(\gettype($password)) . ' given instead.'
);
}
if (!\is_bool($raw_binary)) {
throw new \TypeError(
'Boolean expected for argument 3. ' . \ucfirst(\gettype($raw_binary)) . ' given instead.'
);
}
return self::encryptInternal(
$plaintext,
KeyOrPassword::createFromPassword($password),
$raw_binary
);
}
/**
* Decrypts a ciphertext to a string with a Key.
*
* @param string $ciphertext
* @param Key $key
* @param bool $raw_binary
*
* @throws \TypeError
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*
* @return string
*/
public static function decrypt($ciphertext, $key, $raw_binary = false)
{
if (!\is_string($ciphertext)) {
throw new \TypeError(
'String expected for argument 1. ' . \ucfirst(\gettype($ciphertext)) . ' given instead.'
);
}
if (!($key instanceof Key)) {
throw new \TypeError(
'Key expected for argument 2. ' . \ucfirst(\gettype($key)) . ' given instead.'
);
}
if (!\is_bool($raw_binary)) {
throw new \TypeError(
'Boolean expected for argument 3. ' . \ucfirst(\gettype($raw_binary)) . ' given instead.'
);
}
return self::decryptInternal(
$ciphertext,
KeyOrPassword::createFromKey($key),
$raw_binary
);
}
/**
* Decrypts a ciphertext to a string with a password, using a slow key
* derivation function to make password cracking more expensive.
*
* @param string $ciphertext
* @param string $password
* @param bool $raw_binary
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
* @throws \TypeError
*
* @return string
*/
public static function decryptWithPassword($ciphertext, $password, $raw_binary = false)
{
if (!\is_string($ciphertext)) {
throw new \TypeError(
'String expected for argument 1. ' . \ucfirst(\gettype($ciphertext)) . ' given instead.'
);
}
if (!\is_string($password)) {
throw new \TypeError(
'String expected for argument 2. ' . \ucfirst(\gettype($password)) . ' given instead.'
);
}
if (!\is_bool($raw_binary)) {
throw new \TypeError(
'Boolean expected for argument 3. ' . \ucfirst(\gettype($raw_binary)) . ' given instead.'
);
}
return self::decryptInternal(
$ciphertext,
KeyOrPassword::createFromPassword($password),
$raw_binary
);
}
/**
* Decrypts a legacy ciphertext produced by version 1 of this library.
*
* @param string $ciphertext
* @param string $key
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
* @throws \TypeError
*
* @return string
*/
public static function legacyDecrypt($ciphertext, $key)
{
if (!\is_string($ciphertext)) {
throw new \TypeError(
'String expected for argument 1. ' . \ucfirst(\gettype($ciphertext)) . ' given instead.'
);
}
if (!\is_string($key)) {
throw new \TypeError(
'String expected for argument 2. ' . \ucfirst(\gettype($key)) . ' given instead.'
);
}
RuntimeTests::runtimeTest();
// Extract the HMAC from the front of the ciphertext.
if (Core::ourStrlen($ciphertext) <= Core::LEGACY_MAC_BYTE_SIZE) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Ciphertext is too short.'
);
}
/**
* @var string
*/
$hmac = Core::ourSubstr($ciphertext, 0, Core::LEGACY_MAC_BYTE_SIZE);
Core::ensureTrue(\is_string($hmac));
/**
* @var string
*/
$messageCiphertext = Core::ourSubstr($ciphertext, Core::LEGACY_MAC_BYTE_SIZE);
Core::ensureTrue(\is_string($messageCiphertext));
// Regenerate the same authentication sub-key.
$akey = Core::HKDF(
Core::LEGACY_HASH_FUNCTION_NAME,
$key,
Core::LEGACY_KEY_BYTE_SIZE,
Core::LEGACY_AUTHENTICATION_INFO_STRING,
null
);
if (self::verifyHMAC($hmac, $messageCiphertext, $akey)) {
// Regenerate the same encryption sub-key.
$ekey = Core::HKDF(
Core::LEGACY_HASH_FUNCTION_NAME,
$key,
Core::LEGACY_KEY_BYTE_SIZE,
Core::LEGACY_ENCRYPTION_INFO_STRING,
null
);
// Extract the IV from the ciphertext.
if (Core::ourStrlen($messageCiphertext) <= Core::LEGACY_BLOCK_BYTE_SIZE) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Ciphertext is too short.'
);
}
/**
* @var string
*/
$iv = Core::ourSubstr($messageCiphertext, 0, Core::LEGACY_BLOCK_BYTE_SIZE);
Core::ensureTrue(\is_string($iv));
/**
* @var string
*/
$actualCiphertext = Core::ourSubstr($messageCiphertext, Core::LEGACY_BLOCK_BYTE_SIZE);
Core::ensureTrue(\is_string($actualCiphertext));
// Do the decryption.
$plaintext = self::plainDecrypt($actualCiphertext, $ekey, $iv, Core::LEGACY_CIPHER_METHOD);
return $plaintext;
} else {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Integrity check failed.'
);
}
}
/**
* Encrypts a string with either a key or a password.
*
* @param string $plaintext
* @param KeyOrPassword $secret
* @param bool $raw_binary
*
* @return string
*/
private static function encryptInternal($plaintext, KeyOrPassword $secret, $raw_binary)
{
RuntimeTests::runtimeTest();
$salt = Core::secureRandom(Core::SALT_BYTE_SIZE);
$keys = $secret->deriveKeys($salt);
$ekey = $keys->getEncryptionKey();
$akey = $keys->getAuthenticationKey();
$iv = Core::secureRandom(Core::BLOCK_BYTE_SIZE);
$ciphertext = Core::CURRENT_VERSION . $salt . $iv . self::plainEncrypt($plaintext, $ekey, $iv);
$auth = \hash_hmac(Core::HASH_FUNCTION_NAME, $ciphertext, $akey, true);
$ciphertext = $ciphertext . $auth;
if ($raw_binary) {
return $ciphertext;
}
return Encoding::binToHex($ciphertext);
}
/**
* Decrypts a ciphertext to a string with either a key or a password.
*
* @param string $ciphertext
* @param KeyOrPassword $secret
* @param bool $raw_binary
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*
* @return string
*/
private static function decryptInternal($ciphertext, KeyOrPassword $secret, $raw_binary)
{
RuntimeTests::runtimeTest();
if (! $raw_binary) {
try {
$ciphertext = Encoding::hexToBin($ciphertext);
} catch (Ex\BadFormatException $ex) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Ciphertext has invalid hex encoding.'
);
}
}
if (Core::ourStrlen($ciphertext) < Core::MINIMUM_CIPHERTEXT_SIZE) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Ciphertext is too short.'
);
}
// Get and check the version header.
/** @var string $header */
$header = Core::ourSubstr($ciphertext, 0, Core::HEADER_VERSION_SIZE);
if ($header !== Core::CURRENT_VERSION) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Bad version header.'
);
}
// Get the salt.
/** @var string $salt */
$salt = Core::ourSubstr(
$ciphertext,
Core::HEADER_VERSION_SIZE,
Core::SALT_BYTE_SIZE
);
Core::ensureTrue(\is_string($salt));
// Get the IV.
/** @var string $iv */
$iv = Core::ourSubstr(
$ciphertext,
Core::HEADER_VERSION_SIZE + Core::SALT_BYTE_SIZE,
Core::BLOCK_BYTE_SIZE
);
Core::ensureTrue(\is_string($iv));
// Get the HMAC.
/** @var string $hmac */
$hmac = Core::ourSubstr(
$ciphertext,
Core::ourStrlen($ciphertext) - Core::MAC_BYTE_SIZE,
Core::MAC_BYTE_SIZE
);
Core::ensureTrue(\is_string($hmac));
// Get the actual encrypted ciphertext.
/** @var string $encrypted */
$encrypted = Core::ourSubstr(
$ciphertext,
Core::HEADER_VERSION_SIZE + Core::SALT_BYTE_SIZE +
Core::BLOCK_BYTE_SIZE,
Core::ourStrlen($ciphertext) - Core::MAC_BYTE_SIZE - Core::SALT_BYTE_SIZE -
Core::BLOCK_BYTE_SIZE - Core::HEADER_VERSION_SIZE
);
Core::ensureTrue(\is_string($encrypted));
// Derive the separate encryption and authentication keys from the key
// or password, whichever it is.
$keys = $secret->deriveKeys($salt);
if (self::verifyHMAC($hmac, $header . $salt . $iv . $encrypted, $keys->getAuthenticationKey())) {
$plaintext = self::plainDecrypt($encrypted, $keys->getEncryptionKey(), $iv, Core::CIPHER_METHOD);
return $plaintext;
} else {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Integrity check failed.'
);
}
}
/**
* Raw unauthenticated encryption (insecure on its own).
*
* @param string $plaintext
* @param string $key
* @param string $iv
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
protected static function plainEncrypt($plaintext, $key, $iv)
{
Core::ensureConstantExists('OPENSSL_RAW_DATA');
Core::ensureFunctionExists('openssl_encrypt');
/** @var string $ciphertext */
$ciphertext = \openssl_encrypt(
$plaintext,
Core::CIPHER_METHOD,
$key,
OPENSSL_RAW_DATA,
$iv
);
Core::ensureTrue(\is_string($ciphertext), 'openssl_encrypt() failed');
return $ciphertext;
}
/**
* Raw unauthenticated decryption (insecure on its own).
*
* @param string $ciphertext
* @param string $key
* @param string $iv
* @param string $cipherMethod
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
protected static function plainDecrypt($ciphertext, $key, $iv, $cipherMethod)
{
Core::ensureConstantExists('OPENSSL_RAW_DATA');
Core::ensureFunctionExists('openssl_decrypt');
/** @var string $plaintext */
$plaintext = \openssl_decrypt(
$ciphertext,
$cipherMethod,
$key,
OPENSSL_RAW_DATA,
$iv
);
Core::ensureTrue(\is_string($plaintext), 'openssl_decrypt() failed.');
return $plaintext;
}
/**
* Verifies an HMAC without leaking information through side-channels.
*
* @param string $expected_hmac
* @param string $message
* @param string $key
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return bool
*/
protected static function verifyHMAC($expected_hmac, $message, $key)
{
$message_hmac = \hash_hmac(Core::HASH_FUNCTION_NAME, $message, $key, true);
return Core::hashEquals($message_hmac, $expected_hmac);
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace Defuse\Crypto;
/**
* Class DerivedKeys
* @package Defuse\Crypto
*/
final class DerivedKeys
{
/**
* @var string
*/
private $akey = '';
/**
* @var string
*/
private $ekey = '';
/**
* Returns the authentication key.
* @return string
*/
public function getAuthenticationKey()
{
return $this->akey;
}
/**
* Returns the encryption key.
* @return string
*/
public function getEncryptionKey()
{
return $this->ekey;
}
/**
* Constructor for DerivedKeys.
*
* @param string $akey
* @param string $ekey
*/
public function __construct($akey, $ekey)
{
$this->akey = $akey;
$this->ekey = $ekey;
}
}

View File

@ -1,269 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class Encoding
{
const CHECKSUM_BYTE_SIZE = 32;
const CHECKSUM_HASH_ALGO = 'sha256';
const SERIALIZE_HEADER_BYTES = 4;
/**
* Converts a byte string to a hexadecimal string without leaking
* information through side channels.
*
* @param string $byte_string
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
public static function binToHex($byte_string)
{
$hex = '';
$len = Core::ourStrlen($byte_string);
for ($i = 0; $i < $len; ++$i) {
$c = \ord($byte_string[$i]) & 0xf;
$b = \ord($byte_string[$i]) >> 4;
$hex .= \pack(
'CC',
87 + $b + ((($b - 10) >> 8) & ~38),
87 + $c + ((($c - 10) >> 8) & ~38)
);
}
return $hex;
}
/**
* Converts a hexadecimal string into a byte string without leaking
* information through side channels.
*
* @param string $hex_string
*
* @throws Ex\BadFormatException
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
* @psalm-suppress TypeDoesNotContainType
*/
public static function hexToBin($hex_string)
{
$hex_pos = 0;
$bin = '';
$hex_len = Core::ourStrlen($hex_string);
$state = 0;
$c_acc = 0;
while ($hex_pos < $hex_len) {
$c = \ord($hex_string[$hex_pos]);
$c_num = $c ^ 48;
$c_num0 = ($c_num - 10) >> 8;
$c_alpha = ($c & ~32) - 55;
$c_alpha0 = (($c_alpha - 10) ^ ($c_alpha - 16)) >> 8;
if (($c_num0 | $c_alpha0) === 0) {
throw new Ex\BadFormatException(
'Encoding::hexToBin() input is not a hex string.'
);
}
$c_val = ($c_num0 & $c_num) | ($c_alpha & $c_alpha0);
if ($state === 0) {
$c_acc = $c_val * 16;
} else {
$bin .= \pack('C', $c_acc | $c_val);
}
$state ^= 1;
++$hex_pos;
}
return $bin;
}
/**
* Remove trialing whitespace without table look-ups or branches.
*
* Calling this function may leak the length of the string as well as the
* number of trailing whitespace characters through side-channels.
*
* @param string $string
* @return string
*/
public static function trimTrailingWhitespace($string = '')
{
$length = Core::ourStrlen($string);
if ($length < 1) {
return '';
}
do {
$prevLength = $length;
$last = $length - 1;
$chr = \ord($string[$last]);
/* Null Byte (0x00), a.k.a. \0 */
// if ($chr === 0x00) $length -= 1;
$sub = (($chr - 1) >> 8 ) & 1;
$length -= $sub;
$last -= $sub;
/* Horizontal Tab (0x09) a.k.a. \t */
$chr = \ord($string[$last]);
// if ($chr === 0x09) $length -= 1;
$sub = (((0x08 - $chr) & ($chr - 0x0a)) >> 8) & 1;
$length -= $sub;
$last -= $sub;
/* New Line (0x0a), a.k.a. \n */
$chr = \ord($string[$last]);
// if ($chr === 0x0a) $length -= 1;
$sub = (((0x09 - $chr) & ($chr - 0x0b)) >> 8) & 1;
$length -= $sub;
$last -= $sub;
/* Carriage Return (0x0D), a.k.a. \r */
$chr = \ord($string[$last]);
// if ($chr === 0x0d) $length -= 1;
$sub = (((0x0c - $chr) & ($chr - 0x0e)) >> 8) & 1;
$length -= $sub;
$last -= $sub;
/* Space */
$chr = \ord($string[$last]);
// if ($chr === 0x20) $length -= 1;
$sub = (((0x1f - $chr) & ($chr - 0x21)) >> 8) & 1;
$length -= $sub;
} while ($prevLength !== $length && $length > 0);
return (string) Core::ourSubstr($string, 0, $length);
}
/*
* SECURITY NOTE ON APPLYING CHECKSUMS TO SECRETS:
*
* The checksum introduces a potential security weakness. For example,
* suppose we apply a checksum to a key, and that an adversary has an
* exploit against the process containing the key, such that they can
* overwrite an arbitrary byte of memory and then cause the checksum to
* be verified and learn the result.
*
* In this scenario, the adversary can extract the key one byte at
* a time by overwriting it with their guess of its value and then
* asking if the checksum matches. If it does, their guess was right.
* This kind of attack may be more easy to implement and more reliable
* than a remote code execution attack.
*
* This attack also applies to authenticated encryption as a whole, in
* the situation where the adversary can overwrite a byte of the key
* and then cause a valid ciphertext to be decrypted, and then
* determine whether the MAC check passed or failed.
*
* By using the full SHA256 hash instead of truncating it, I'm ensuring
* that both ways of going about the attack are equivalently difficult.
* A shorter checksum of say 32 bits might be more useful to the
* adversary as an oracle in case their writes are coarser grained.
*
* Because the scenario assumes a serious vulnerability, we don't try
* to prevent attacks of this style.
*/
/**
* INTERNAL USE ONLY: Applies a version header, applies a checksum, and
* then encodes a byte string into a range of printable ASCII characters.
*
* @param string $header
* @param string $bytes
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
public static function saveBytesToChecksummedAsciiSafeString($header, $bytes)
{
// Headers must be a constant length to prevent one type's header from
// being a prefix of another type's header, leading to ambiguity.
Core::ensureTrue(
Core::ourStrlen($header) === self::SERIALIZE_HEADER_BYTES,
'Header must be ' . self::SERIALIZE_HEADER_BYTES . ' bytes.'
);
return Encoding::binToHex(
$header .
$bytes .
\hash(
self::CHECKSUM_HASH_ALGO,
$header . $bytes,
true
)
);
}
/**
* INTERNAL USE ONLY: Decodes, verifies the header and checksum, and returns
* the encoded byte string.
*
* @param string $expected_header
* @param string $string
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\BadFormatException
*
* @return string
*/
public static function loadBytesFromChecksummedAsciiSafeString($expected_header, $string)
{
// Headers must be a constant length to prevent one type's header from
// being a prefix of another type's header, leading to ambiguity.
Core::ensureTrue(
Core::ourStrlen($expected_header) === self::SERIALIZE_HEADER_BYTES,
'Header must be 4 bytes.'
);
/* If you get an exception here when attempting to load from a file, first pass your
key to Encoding::trimTrailingWhitespace() to remove newline characters, etc. */
$bytes = Encoding::hexToBin($string);
/* Make sure we have enough bytes to get the version header and checksum. */
if (Core::ourStrlen($bytes) < self::SERIALIZE_HEADER_BYTES + self::CHECKSUM_BYTE_SIZE) {
throw new Ex\BadFormatException(
'Encoded data is shorter than expected.'
);
}
/* Grab the version header. */
$actual_header = (string) Core::ourSubstr($bytes, 0, self::SERIALIZE_HEADER_BYTES);
if ($actual_header !== $expected_header) {
throw new Ex\BadFormatException(
'Invalid header.'
);
}
/* Grab the bytes that are part of the checksum. */
$checked_bytes = (string) Core::ourSubstr(
$bytes,
0,
Core::ourStrlen($bytes) - self::CHECKSUM_BYTE_SIZE
);
/* Grab the included checksum. */
$checksum_a = (string) Core::ourSubstr(
$bytes,
Core::ourStrlen($bytes) - self::CHECKSUM_BYTE_SIZE,
self::CHECKSUM_BYTE_SIZE
);
/* Re-compute the checksum. */
$checksum_b = \hash(self::CHECKSUM_HASH_ALGO, $checked_bytes, true);
/* Check if the checksum matches. */
if (! Core::hashEquals($checksum_a, $checksum_b)) {
throw new Ex\BadFormatException(
"Data is corrupted, the checksum doesn't match"
);
}
return (string) Core::ourSubstr(
$bytes,
self::SERIALIZE_HEADER_BYTES,
Core::ourStrlen($bytes) - self::SERIALIZE_HEADER_BYTES - self::CHECKSUM_BYTE_SIZE
);
}
}

View File

@ -1,7 +0,0 @@
<?php
namespace Defuse\Crypto\Exception;
class BadFormatException extends \Defuse\Crypto\Exception\CryptoException
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace Defuse\Crypto\Exception;
class CryptoException extends \Exception
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace Defuse\Crypto\Exception;
class EnvironmentIsBrokenException extends \Defuse\Crypto\Exception\CryptoException
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace Defuse\Crypto\Exception;
class IOException extends \Defuse\Crypto\Exception\CryptoException
{
}

View File

@ -1,7 +0,0 @@
<?php
namespace Defuse\Crypto\Exception;
class WrongKeyOrModifiedCiphertextException extends \Defuse\Crypto\Exception\CryptoException
{
}

View File

@ -1,778 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class File
{
/**
* Encrypts the input file, saving the ciphertext to the output file.
*
* @param string $inputFilename
* @param string $outputFilename
* @param Key $key
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
*/
public static function encryptFile($inputFilename, $outputFilename, Key $key)
{
self::encryptFileInternal(
$inputFilename,
$outputFilename,
KeyOrPassword::createFromKey($key)
);
}
/**
* Encrypts a file with a password, using a slow key derivation function to
* make password cracking more expensive.
*
* @param string $inputFilename
* @param string $outputFilename
* @param string $password
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
*/
public static function encryptFileWithPassword($inputFilename, $outputFilename, $password)
{
self::encryptFileInternal(
$inputFilename,
$outputFilename,
KeyOrPassword::createFromPassword($password)
);
}
/**
* Decrypts the input file, saving the plaintext to the output file.
*
* @param string $inputFilename
* @param string $outputFilename
* @param Key $key
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function decryptFile($inputFilename, $outputFilename, Key $key)
{
self::decryptFileInternal(
$inputFilename,
$outputFilename,
KeyOrPassword::createFromKey($key)
);
}
/**
* Decrypts a file with a password, using a slow key derivation function to
* make password cracking more expensive.
*
* @param string $inputFilename
* @param string $outputFilename
* @param string $password
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function decryptFileWithPassword($inputFilename, $outputFilename, $password)
{
self::decryptFileInternal(
$inputFilename,
$outputFilename,
KeyOrPassword::createFromPassword($password)
);
}
/**
* Takes two resource handles and encrypts the contents of the first,
* writing the ciphertext into the second.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param Key $key
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function encryptResource($inputHandle, $outputHandle, Key $key)
{
self::encryptResourceInternal(
$inputHandle,
$outputHandle,
KeyOrPassword::createFromKey($key)
);
}
/**
* Encrypts the contents of one resource handle into another with a
* password, using a slow key derivation function to make password cracking
* more expensive.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param string $password
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function encryptResourceWithPassword($inputHandle, $outputHandle, $password)
{
self::encryptResourceInternal(
$inputHandle,
$outputHandle,
KeyOrPassword::createFromPassword($password)
);
}
/**
* Takes two resource handles and decrypts the contents of the first,
* writing the plaintext into the second.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param Key $key
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function decryptResource($inputHandle, $outputHandle, Key $key)
{
self::decryptResourceInternal(
$inputHandle,
$outputHandle,
KeyOrPassword::createFromKey($key)
);
}
/**
* Decrypts the contents of one resource into another with a password, using
* a slow key derivation function to make password cracking more expensive.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param string $password
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*/
public static function decryptResourceWithPassword($inputHandle, $outputHandle, $password)
{
self::decryptResourceInternal(
$inputHandle,
$outputHandle,
KeyOrPassword::createFromPassword($password)
);
}
/**
* Encrypts a file with either a key or a password.
*
* @param string $inputFilename
* @param string $outputFilename
* @param KeyOrPassword $secret
* @return void
*
* @throws Ex\CryptoException
* @throws Ex\IOException
*/
private static function encryptFileInternal($inputFilename, $outputFilename, KeyOrPassword $secret)
{
if (file_exists($inputFilename) && file_exists($outputFilename) && realpath($inputFilename) === realpath($outputFilename)) {
throw new Ex\IOException('Input and output filenames must be different.');
}
/* Open the input file. */
$if = @\fopen($inputFilename, 'rb');
if ($if === false) {
throw new Ex\IOException(
'Cannot open input file for encrypting: ' .
self::getLastErrorMessage()
);
}
if (\is_callable('\\stream_set_read_buffer')) {
/* This call can fail, but the only consequence is performance. */
\stream_set_read_buffer($if, 0);
}
/* Open the output file. */
$of = @\fopen($outputFilename, 'wb');
if ($of === false) {
\fclose($if);
throw new Ex\IOException(
'Cannot open output file for encrypting: ' .
self::getLastErrorMessage()
);
}
if (\is_callable('\\stream_set_write_buffer')) {
/* This call can fail, but the only consequence is performance. */
\stream_set_write_buffer($of, 0);
}
/* Perform the encryption. */
try {
self::encryptResourceInternal($if, $of, $secret);
} catch (Ex\CryptoException $ex) {
\fclose($if);
\fclose($of);
throw $ex;
}
/* Close the input file. */
if (\fclose($if) === false) {
\fclose($of);
throw new Ex\IOException(
'Cannot close input file after encrypting'
);
}
/* Close the output file. */
if (\fclose($of) === false) {
throw new Ex\IOException(
'Cannot close output file after encrypting'
);
}
}
/**
* Decrypts a file with either a key or a password.
*
* @param string $inputFilename
* @param string $outputFilename
* @param KeyOrPassword $secret
* @return void
*
* @throws Ex\CryptoException
* @throws Ex\IOException
*/
private static function decryptFileInternal($inputFilename, $outputFilename, KeyOrPassword $secret)
{
if (file_exists($inputFilename) && file_exists($outputFilename) && realpath($inputFilename) === realpath($outputFilename)) {
throw new Ex\IOException('Input and output filenames must be different.');
}
/* Open the input file. */
$if = @\fopen($inputFilename, 'rb');
if ($if === false) {
throw new Ex\IOException(
'Cannot open input file for decrypting: ' .
self::getLastErrorMessage()
);
}
if (\is_callable('\\stream_set_read_buffer')) {
/* This call can fail, but the only consequence is performance. */
\stream_set_read_buffer($if, 0);
}
/* Open the output file. */
$of = @\fopen($outputFilename, 'wb');
if ($of === false) {
\fclose($if);
throw new Ex\IOException(
'Cannot open output file for decrypting: ' .
self::getLastErrorMessage()
);
}
if (\is_callable('\\stream_set_write_buffer')) {
/* This call can fail, but the only consequence is performance. */
\stream_set_write_buffer($of, 0);
}
/* Perform the decryption. */
try {
self::decryptResourceInternal($if, $of, $secret);
} catch (Ex\CryptoException $ex) {
\fclose($if);
\fclose($of);
throw $ex;
}
/* Close the input file. */
if (\fclose($if) === false) {
\fclose($of);
throw new Ex\IOException(
'Cannot close input file after decrypting'
);
}
/* Close the output file. */
if (\fclose($of) === false) {
throw new Ex\IOException(
'Cannot close output file after decrypting'
);
}
}
/**
* Encrypts a resource with either a key or a password.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param KeyOrPassword $secret
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @psalm-suppress PossiblyInvalidArgument
* Fixes erroneous errors caused by PHP 7.2 switching the return value
* of hash_init from a resource to a HashContext.
*/
private static function encryptResourceInternal($inputHandle, $outputHandle, KeyOrPassword $secret)
{
if (! \is_resource($inputHandle)) {
throw new Ex\IOException(
'Input handle must be a resource!'
);
}
if (! \is_resource($outputHandle)) {
throw new Ex\IOException(
'Output handle must be a resource!'
);
}
$inputStat = \fstat($inputHandle);
$inputSize = $inputStat['size'];
$file_salt = Core::secureRandom(Core::SALT_BYTE_SIZE);
$keys = $secret->deriveKeys($file_salt);
$ekey = $keys->getEncryptionKey();
$akey = $keys->getAuthenticationKey();
$ivsize = Core::BLOCK_BYTE_SIZE;
$iv = Core::secureRandom($ivsize);
/* Initialize a streaming HMAC state. */
/** @var mixed $hmac */
$hmac = \hash_init(Core::HASH_FUNCTION_NAME, HASH_HMAC, $akey);
Core::ensureTrue(
\is_resource($hmac) || \is_object($hmac),
'Cannot initialize a hash context'
);
/* Write the header, salt, and IV. */
self::writeBytes(
$outputHandle,
Core::CURRENT_VERSION . $file_salt . $iv,
Core::HEADER_VERSION_SIZE + Core::SALT_BYTE_SIZE + $ivsize
);
/* Add the header, salt, and IV to the HMAC. */
\hash_update($hmac, Core::CURRENT_VERSION);
\hash_update($hmac, $file_salt);
\hash_update($hmac, $iv);
/* $thisIv will be incremented after each call to the encryption. */
$thisIv = $iv;
/* How many blocks do we encrypt at a time? We increment by this value. */
/**
* @psalm-suppress RedundantCast
*/
$inc = (int) (Core::BUFFER_BYTE_SIZE / Core::BLOCK_BYTE_SIZE);
/* Loop until we reach the end of the input file. */
$at_file_end = false;
while (! (\feof($inputHandle) || $at_file_end)) {
/* Find out if we can read a full buffer, or only a partial one. */
/** @var int */
$pos = \ftell($inputHandle);
if (!\is_int($pos)) {
throw new Ex\IOException(
'Could not get current position in input file during encryption'
);
}
if ($pos + Core::BUFFER_BYTE_SIZE >= $inputSize) {
/* We're at the end of the file, so we need to break out of the loop. */
$at_file_end = true;
$read = self::readBytes(
$inputHandle,
$inputSize - $pos
);
} else {
$read = self::readBytes(
$inputHandle,
Core::BUFFER_BYTE_SIZE
);
}
/* Encrypt this buffer. */
/** @var string */
$encrypted = \openssl_encrypt(
$read,
Core::CIPHER_METHOD,
$ekey,
OPENSSL_RAW_DATA,
$thisIv
);
Core::ensureTrue(\is_string($encrypted), 'OpenSSL encryption error');
/* Write this buffer's ciphertext. */
self::writeBytes($outputHandle, $encrypted, Core::ourStrlen($encrypted));
/* Add this buffer's ciphertext to the HMAC. */
\hash_update($hmac, $encrypted);
/* Increment the counter by the number of blocks in a buffer. */
$thisIv = Core::incrementCounter($thisIv, $inc);
/* WARNING: Usually, unless the file is a multiple of the buffer
* size, $thisIv will contain an incorrect value here on the last
* iteration of this loop. */
}
/* Get the HMAC and append it to the ciphertext. */
$final_mac = \hash_final($hmac, true);
self::writeBytes($outputHandle, $final_mac, Core::MAC_BYTE_SIZE);
}
/**
* Decrypts a file-backed resource with either a key or a password.
*
* @param resource $inputHandle
* @param resource $outputHandle
* @param KeyOrPassword $secret
* @return void
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\IOException
* @throws Ex\WrongKeyOrModifiedCiphertextException
* @psalm-suppress PossiblyInvalidArgument
* Fixes erroneous errors caused by PHP 7.2 switching the return value
* of hash_init from a resource to a HashContext.
*/
public static function decryptResourceInternal($inputHandle, $outputHandle, KeyOrPassword $secret)
{
if (! \is_resource($inputHandle)) {
throw new Ex\IOException(
'Input handle must be a resource!'
);
}
if (! \is_resource($outputHandle)) {
throw new Ex\IOException(
'Output handle must be a resource!'
);
}
/* Make sure the file is big enough for all the reads we need to do. */
$stat = \fstat($inputHandle);
if ($stat['size'] < Core::MINIMUM_CIPHERTEXT_SIZE) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Input file is too small to have been created by this library.'
);
}
/* Check the version header. */
$header = self::readBytes($inputHandle, Core::HEADER_VERSION_SIZE);
if ($header !== Core::CURRENT_VERSION) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Bad version header.'
);
}
/* Get the salt. */
$file_salt = self::readBytes($inputHandle, Core::SALT_BYTE_SIZE);
/* Get the IV. */
$ivsize = Core::BLOCK_BYTE_SIZE;
$iv = self::readBytes($inputHandle, $ivsize);
/* Derive the authentication and encryption keys. */
$keys = $secret->deriveKeys($file_salt);
$ekey = $keys->getEncryptionKey();
$akey = $keys->getAuthenticationKey();
/* We'll store the MAC of each buffer-sized chunk as we verify the
* actual MAC, so that we can check them again when decrypting. */
$macs = [];
/* $thisIv will be incremented after each call to the decryption. */
$thisIv = $iv;
/* How many blocks do we encrypt at a time? We increment by this value. */
/**
* @psalm-suppress RedundantCast
*/
$inc = (int) (Core::BUFFER_BYTE_SIZE / Core::BLOCK_BYTE_SIZE);
/* Get the HMAC. */
if (\fseek($inputHandle, (-1 * Core::MAC_BYTE_SIZE), SEEK_END) === -1) {
throw new Ex\IOException(
'Cannot seek to beginning of MAC within input file'
);
}
/* Get the position of the last byte in the actual ciphertext. */
/** @var int $cipher_end */
$cipher_end = \ftell($inputHandle);
if (!\is_int($cipher_end)) {
throw new Ex\IOException(
'Cannot read input file'
);
}
/* We have the position of the first byte of the HMAC. Go back by one. */
--$cipher_end;
/* Read the HMAC. */
/** @var string $stored_mac */
$stored_mac = self::readBytes($inputHandle, Core::MAC_BYTE_SIZE);
/* Initialize a streaming HMAC state. */
/** @var mixed $hmac */
$hmac = \hash_init(Core::HASH_FUNCTION_NAME, HASH_HMAC, $akey);
Core::ensureTrue(\is_resource($hmac) || \is_object($hmac), 'Cannot initialize a hash context');
/* Reset file pointer to the beginning of the file after the header */
if (\fseek($inputHandle, Core::HEADER_VERSION_SIZE, SEEK_SET) === -1) {
throw new Ex\IOException(
'Cannot read seek within input file'
);
}
/* Seek to the start of the actual ciphertext. */
if (\fseek($inputHandle, Core::SALT_BYTE_SIZE + $ivsize, SEEK_CUR) === -1) {
throw new Ex\IOException(
'Cannot seek input file to beginning of ciphertext'
);
}
/* PASS #1: Calculating the HMAC. */
\hash_update($hmac, $header);
\hash_update($hmac, $file_salt);
\hash_update($hmac, $iv);
/** @var mixed $hmac2 */
$hmac2 = \hash_copy($hmac);
$break = false;
while (! $break) {
/** @var int $pos */
$pos = \ftell($inputHandle);
if (!\is_int($pos)) {
throw new Ex\IOException(
'Could not get current position in input file during decryption'
);
}
/* Read the next buffer-sized chunk (or less). */
if ($pos + Core::BUFFER_BYTE_SIZE >= $cipher_end) {
$break = true;
$read = self::readBytes(
$inputHandle,
$cipher_end - $pos + 1
);
} else {
$read = self::readBytes(
$inputHandle,
Core::BUFFER_BYTE_SIZE
);
}
/* Update the HMAC. */
\hash_update($hmac, $read);
/* Remember this buffer-sized chunk's HMAC. */
/** @var mixed $chunk_mac */
$chunk_mac = \hash_copy($hmac);
Core::ensureTrue(\is_resource($chunk_mac) || \is_object($chunk_mac), 'Cannot duplicate a hash context');
$macs []= \hash_final($chunk_mac);
}
/* Get the final HMAC, which should match the stored one. */
/** @var string $final_mac */
$final_mac = \hash_final($hmac, true);
/* Verify the HMAC. */
if (! Core::hashEquals($final_mac, $stored_mac)) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'Integrity check failed.'
);
}
/* PASS #2: Decrypt and write output. */
/* Rewind to the start of the actual ciphertext. */
if (\fseek($inputHandle, Core::SALT_BYTE_SIZE + $ivsize + Core::HEADER_VERSION_SIZE, SEEK_SET) === -1) {
throw new Ex\IOException(
'Could not move the input file pointer during decryption'
);
}
$at_file_end = false;
while (! $at_file_end) {
/** @var int $pos */
$pos = \ftell($inputHandle);
if (!\is_int($pos)) {
throw new Ex\IOException(
'Could not get current position in input file during decryption'
);
}
/* Read the next buffer-sized chunk (or less). */
if ($pos + Core::BUFFER_BYTE_SIZE >= $cipher_end) {
$at_file_end = true;
$read = self::readBytes(
$inputHandle,
$cipher_end - $pos + 1
);
} else {
$read = self::readBytes(
$inputHandle,
Core::BUFFER_BYTE_SIZE
);
}
/* Recalculate the MAC (so far) and compare it with the one we
* remembered from pass #1 to ensure attackers didn't change the
* ciphertext after MAC verification. */
\hash_update($hmac2, $read);
/** @var mixed $calc_mac */
$calc_mac = \hash_copy($hmac2);
Core::ensureTrue(\is_resource($calc_mac) || \is_object($calc_mac), 'Cannot duplicate a hash context');
$calc = \hash_final($calc_mac);
if (empty($macs)) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'File was modified after MAC verification'
);
} elseif (! Core::hashEquals(\array_shift($macs), $calc)) {
throw new Ex\WrongKeyOrModifiedCiphertextException(
'File was modified after MAC verification'
);
}
/* Decrypt this buffer-sized chunk. */
/** @var string $decrypted */
$decrypted = \openssl_decrypt(
$read,
Core::CIPHER_METHOD,
$ekey,
OPENSSL_RAW_DATA,
$thisIv
);
Core::ensureTrue(\is_string($decrypted), 'OpenSSL decryption error');
/* Write the plaintext to the output file. */
self::writeBytes(
$outputHandle,
$decrypted,
Core::ourStrlen($decrypted)
);
/* Increment the IV by the amount of blocks in a buffer. */
/** @var string $thisIv */
$thisIv = Core::incrementCounter($thisIv, $inc);
/* WARNING: Usually, unless the file is a multiple of the buffer
* size, $thisIv will contain an incorrect value here on the last
* iteration of this loop. */
}
}
/**
* Read from a stream; prevent partial reads.
*
* @param resource $stream
* @param int $num_bytes
* @return string
*
* @throws Ex\IOException
* @throws Ex\EnvironmentIsBrokenException
*/
public static function readBytes($stream, $num_bytes)
{
Core::ensureTrue($num_bytes >= 0, 'Tried to read less than 0 bytes');
if ($num_bytes === 0) {
return '';
}
$buf = '';
$remaining = $num_bytes;
while ($remaining > 0 && ! \feof($stream)) {
/** @var string $read */
$read = \fread($stream, $remaining);
if (!\is_string($read)) {
throw new Ex\IOException(
'Could not read from the file'
);
}
$buf .= $read;
$remaining -= Core::ourStrlen($read);
}
if (Core::ourStrlen($buf) !== $num_bytes) {
throw new Ex\IOException(
'Tried to read past the end of the file'
);
}
return $buf;
}
/**
* Write to a stream; prevents partial writes.
*
* @param resource $stream
* @param string $buf
* @param int $num_bytes
* @return int
*
* @throws Ex\IOException
*/
public static function writeBytes($stream, $buf, $num_bytes = null)
{
$bufSize = Core::ourStrlen($buf);
if ($num_bytes === null) {
$num_bytes = $bufSize;
}
if ($num_bytes > $bufSize) {
throw new Ex\IOException(
'Trying to write more bytes than the buffer contains.'
);
}
if ($num_bytes < 0) {
throw new Ex\IOException(
'Tried to write less than 0 bytes'
);
}
$remaining = $num_bytes;
while ($remaining > 0) {
/** @var int $written */
$written = \fwrite($stream, $buf, $remaining);
if (!\is_int($written)) {
throw new Ex\IOException(
'Could not write to the file'
);
}
$buf = (string) Core::ourSubstr($buf, $written, null);
$remaining -= $written;
}
return $num_bytes;
}
/**
* Returns the last PHP error's or warning's message string.
*
* @return string
*/
private static function getLastErrorMessage()
{
$error = error_get_last();
if ($error === null) {
return '[no PHP error]';
} else {
return $error['message'];
}
}
}

View File

@ -1,94 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class Key
{
const KEY_CURRENT_VERSION = "\xDE\xF0\x00\x00";
const KEY_BYTE_SIZE = 32;
/**
* @var string
*/
private $key_bytes;
/**
* Creates new random key.
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return Key
*/
public static function createNewRandomKey()
{
return new Key(Core::secureRandom(self::KEY_BYTE_SIZE));
}
/**
* Loads a Key from its encoded form.
*
* By default, this function will call Encoding::trimTrailingWhitespace()
* to remove trailing CR, LF, NUL, TAB, and SPACE characters, which are
* commonly appended to files when working with text editors.
*
* @param string $saved_key_string
* @param bool $do_not_trim (default: false)
*
* @throws Ex\BadFormatException
* @throws Ex\EnvironmentIsBrokenException
*
* @return Key
*/
public static function loadFromAsciiSafeString($saved_key_string, $do_not_trim = false)
{
if (!$do_not_trim) {
$saved_key_string = Encoding::trimTrailingWhitespace($saved_key_string);
}
$key_bytes = Encoding::loadBytesFromChecksummedAsciiSafeString(self::KEY_CURRENT_VERSION, $saved_key_string);
return new Key($key_bytes);
}
/**
* Encodes the Key into a string of printable ASCII characters.
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
public function saveToAsciiSafeString()
{
return Encoding::saveBytesToChecksummedAsciiSafeString(
self::KEY_CURRENT_VERSION,
$this->key_bytes
);
}
/**
* Gets the raw bytes of the key.
*
* @return string
*/
public function getRawBytes()
{
return $this->key_bytes;
}
/**
* Constructs a new Key object from a string of raw bytes.
*
* @param string $bytes
*
* @throws Ex\EnvironmentIsBrokenException
*/
private function __construct($bytes)
{
Core::ensureTrue(
Core::ourStrlen($bytes) === self::KEY_BYTE_SIZE,
'Bad key length.'
);
$this->key_bytes = $bytes;
}
}

View File

@ -1,149 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class KeyOrPassword
{
const PBKDF2_ITERATIONS = 100000;
const SECRET_TYPE_KEY = 1;
const SECRET_TYPE_PASSWORD = 2;
/**
* @var int
*/
private $secret_type = 0;
/**
* @var Key|string
*/
private $secret;
/**
* Initializes an instance of KeyOrPassword from a key.
*
* @param Key $key
*
* @return KeyOrPassword
*/
public static function createFromKey(Key $key)
{
return new KeyOrPassword(self::SECRET_TYPE_KEY, $key);
}
/**
* Initializes an instance of KeyOrPassword from a password.
*
* @param string $password
*
* @return KeyOrPassword
*/
public static function createFromPassword($password)
{
return new KeyOrPassword(self::SECRET_TYPE_PASSWORD, $password);
}
/**
* Derives authentication and encryption keys from the secret, using a slow
* key derivation function if the secret is a password.
*
* @param string $salt
*
* @throws Ex\CryptoException
* @throws Ex\EnvironmentIsBrokenException
*
* @return DerivedKeys
*/
public function deriveKeys($salt)
{
Core::ensureTrue(
Core::ourStrlen($salt) === Core::SALT_BYTE_SIZE,
'Bad salt.'
);
if ($this->secret_type === self::SECRET_TYPE_KEY) {
Core::ensureTrue($this->secret instanceof Key);
/**
* @psalm-suppress PossiblyInvalidMethodCall
*/
$akey = Core::HKDF(
Core::HASH_FUNCTION_NAME,
$this->secret->getRawBytes(),
Core::KEY_BYTE_SIZE,
Core::AUTHENTICATION_INFO_STRING,
$salt
);
/**
* @psalm-suppress PossiblyInvalidMethodCall
*/
$ekey = Core::HKDF(
Core::HASH_FUNCTION_NAME,
$this->secret->getRawBytes(),
Core::KEY_BYTE_SIZE,
Core::ENCRYPTION_INFO_STRING,
$salt
);
return new DerivedKeys($akey, $ekey);
} elseif ($this->secret_type === self::SECRET_TYPE_PASSWORD) {
Core::ensureTrue(\is_string($this->secret));
/* Our PBKDF2 polyfill is vulnerable to a DoS attack documented in
* GitHub issue #230. The fix is to pre-hash the password to ensure
* it is short. We do the prehashing here instead of in pbkdf2() so
* that pbkdf2() still computes the function as defined by the
* standard. */
/**
* @psalm-suppress PossiblyInvalidArgument
*/
$prehash = \hash(Core::HASH_FUNCTION_NAME, $this->secret, true);
$prekey = Core::pbkdf2(
Core::HASH_FUNCTION_NAME,
$prehash,
$salt,
self::PBKDF2_ITERATIONS,
Core::KEY_BYTE_SIZE,
true
);
$akey = Core::HKDF(
Core::HASH_FUNCTION_NAME,
$prekey,
Core::KEY_BYTE_SIZE,
Core::AUTHENTICATION_INFO_STRING,
$salt
);
/* Note the cryptographic re-use of $salt here. */
$ekey = Core::HKDF(
Core::HASH_FUNCTION_NAME,
$prekey,
Core::KEY_BYTE_SIZE,
Core::ENCRYPTION_INFO_STRING,
$salt
);
return new DerivedKeys($akey, $ekey);
} else {
throw new Ex\EnvironmentIsBrokenException('Bad secret type.');
}
}
/**
* Constructor for KeyOrPassword.
*
* @param int $secret_type
* @param mixed $secret (either a Key or a password string)
*/
private function __construct($secret_type, $secret)
{
// The constructor is private, so these should never throw.
if ($secret_type === self::SECRET_TYPE_KEY) {
Core::ensureTrue($secret instanceof Key);
} elseif ($secret_type === self::SECRET_TYPE_PASSWORD) {
Core::ensureTrue(\is_string($secret));
} else {
throw new Ex\EnvironmentIsBrokenException('Bad secret type.');
}
$this->secret_type = $secret_type;
$this->secret = $secret;
}
}

View File

@ -1,145 +0,0 @@
<?php
namespace Defuse\Crypto;
use Defuse\Crypto\Exception as Ex;
final class KeyProtectedByPassword
{
const PASSWORD_KEY_CURRENT_VERSION = "\xDE\xF1\x00\x00";
/**
* @var string
*/
private $encrypted_key = '';
/**
* Creates a random key protected by the provided password.
*
* @param string $password
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return KeyProtectedByPassword
*/
public static function createRandomPasswordProtectedKey($password)
{
$inner_key = Key::createNewRandomKey();
/* The password is hashed as a form of poor-man's domain separation
* between this use of encryptWithPassword() and other uses of
* encryptWithPassword() that the user may also be using as part of the
* same protocol. */
$encrypted_key = Crypto::encryptWithPassword(
$inner_key->saveToAsciiSafeString(),
\hash(Core::HASH_FUNCTION_NAME, $password, true),
true
);
return new KeyProtectedByPassword($encrypted_key);
}
/**
* Loads a KeyProtectedByPassword from its encoded form.
*
* @param string $saved_key_string
*
* @throws Ex\BadFormatException
*
* @return KeyProtectedByPassword
*/
public static function loadFromAsciiSafeString($saved_key_string)
{
$encrypted_key = Encoding::loadBytesFromChecksummedAsciiSafeString(
self::PASSWORD_KEY_CURRENT_VERSION,
$saved_key_string
);
return new KeyProtectedByPassword($encrypted_key);
}
/**
* Encodes the KeyProtectedByPassword into a string of printable ASCII
* characters.
*
* @throws Ex\EnvironmentIsBrokenException
*
* @return string
*/
public function saveToAsciiSafeString()
{
return Encoding::saveBytesToChecksummedAsciiSafeString(
self::PASSWORD_KEY_CURRENT_VERSION,
$this->encrypted_key
);
}
/**
* Decrypts the protected key, returning an unprotected Key object that can
* be used for encryption and decryption.
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*
* @param string $password
* @return Key
*/
public function unlockKey($password)
{
try {
$inner_key_encoded = Crypto::decryptWithPassword(
$this->encrypted_key,
\hash(Core::HASH_FUNCTION_NAME, $password, true),
true
);
return Key::loadFromAsciiSafeString($inner_key_encoded);
} catch (Ex\BadFormatException $ex) {
/* This should never happen unless an attacker replaced the
* encrypted key ciphertext with some other ciphertext that was
* encrypted with the same password. We transform the exception type
* here in order to make the API simpler, avoiding the need to
* document that this method might throw an Ex\BadFormatException. */
throw new Ex\WrongKeyOrModifiedCiphertextException(
"The decrypted key was found to be in an invalid format. " .
"This very likely indicates it was modified by an attacker."
);
}
}
/**
* Changes the password.
*
* @param string $current_password
* @param string $new_password
*
* @throws Ex\EnvironmentIsBrokenException
* @throws Ex\WrongKeyOrModifiedCiphertextException
*
* @return KeyProtectedByPassword
*/
public function changePassword($current_password, $new_password)
{
$inner_key = $this->unlockKey($current_password);
/* The password is hashed as a form of poor-man's domain separation
* between this use of encryptWithPassword() and other uses of
* encryptWithPassword() that the user may also be using as part of the
* same protocol. */
$encrypted_key = Crypto::encryptWithPassword(
$inner_key->saveToAsciiSafeString(),
\hash(Core::HASH_FUNCTION_NAME, $new_password, true),
true
);
$this->encrypted_key = $encrypted_key;
return $this;
}
/**
* Constructor for KeyProtectedByPassword.
*
* @param string $encrypted_key
*/
private function __construct($encrypted_key)
{
$this->encrypted_key = $encrypted_key;
}
}

Some files were not shown because too many files have changed in this diff Show More