Repositories | Polyback | Log in to see private repositories


polyback-website / 8b48bedad56346c44734ee80e6f153429435481c / api/private/classes/pizzaboxer/ProjectPolygon/Trades.php

12,445 bytes | parent directory

<?php

namespace pizzaboxer\ProjectPolygon;

// Trades between players: catalog items they own, passes of places they hold, and Pizzas, each
// way. A place's owner can trade away passes of their own place without limit: those are made when
// the trade happens and can never be refunded. There are no fees.
class Trades
{
	const WAITING = 0;
	const DONE = 1;
	const DECLINED = 2;
	const CANCELLED = 3;
	const FAILED = 4;

	const MAX_THINGS = 8;        // on each side
	const MAX_PIZZAS = 10000000; // on each side
	const MAX_OPEN = 20;         // trades somebody has sent that are still waiting

	// What can change hands: shirts, pants, T-shirts, hats, heads, faces, gear, packages, accessories
	const TRADABLE_TYPES = [2, 8, 11, 12, 17, 18, 19, 32, 41, 42, 43, 44, 45, 46, 47];

	private static function types() { return implode(",", self::TRADABLE_TYPES); }

	// What somebody could give: catalog items, passes they hold, and passes of their own places.
	static function Inventory($userId)
	{
		$db = Database::singleton();
		return (object) [
			"Assets" => $db->run(
				"SELECT o.id AS OwnedID, a.id AS AssetID, a.name AS Name, a.type AS Type FROM ownedAssets o JOIN assets a ON a.id = o.assetId
				 WHERE o.userId = :u AND a.type IN (" . self::types() . ") AND a.approved = 1 ORDER BY o.id DESC",
				[":u" => (int) $userId]
			)->fetchAll(\PDO::FETCH_OBJ),
			"Passes" => $db->run(
				"SELECT i.ID AS ItemID, p.ID AS ProductID, p.Name, p.PlaceID, a.name AS PlaceName FROM ProductItems i
				 JOIN PlaceProducts p ON p.ID = i.ProductID JOIN assets a ON a.id = p.PlaceID
				 WHERE i.HolderID = :u ORDER BY i.ID DESC",
				[":u" => (int) $userId]
			)->fetchAll(\PDO::FETCH_OBJ),
			"OwnPasses" => $db->run(
				"SELECT p.ID AS ProductID, p.Name, p.PlaceID, a.name AS PlaceName FROM PlaceProducts p JOIN assets a ON a.id = p.PlaceID
				 WHERE a.creator = :u AND p.IsPass = 1 ORDER BY p.PlaceID, p.ID",
				[":u" => (int) $userId]
			)->fetchAll(\PDO::FETCH_OBJ),
		];
	}

	private static function ids($list)
	{
		$out = [];
		foreach ((array) $list as $v) if (is_scalar($v) && ctype_digit((string) $v)) $out[(int) $v] = true;
		return array_keys($out);
	}

	private static function pizzas($n)
	{
		if ($n === "" || $n === null) return 0;
		if (!preg_match('/^[0-9]{1,8}$/', (string) $n) || (int) $n > self::MAX_PIZZAS) return false;
		return (int) $n;
	}

	// $give/$get: ["assets" => ownedAssets ids, "items" => ProductItems ids, "new" => product ids of
	// the giver's own places]. Returns the new trade's id or an error text.
	static function Send($senderId, $receiverId, $give, $get, $givePizzas, $getPizzas)
	{
		$db = Database::singleton();
		$senderId = (int) $senderId;
		$receiverId = (int) $receiverId;
		if ($senderId === $receiverId) return "You can't trade with yourself";
		if (!Users::GetInfoFromID($receiverId)) return "There's no such player";
		$givePizzas = self::pizzas($givePizzas);
		$getPizzas = self::pizzas($getPizzas);
		if ($givePizzas === false || $getPizzas === false) return "Pizzas have to be a whole number up to " . number_format(self::MAX_PIZZAS);
		if ($db->run("SELECT COUNT(*) FROM Trades WHERE SenderID = :u AND Status = 0", [":u" => $senderId])->fetchColumn() >= self::MAX_OPEN)
			return "You have " . self::MAX_OPEN . " trades waiting already: cancel some first";

		$things = [];
		foreach ([[true, $senderId, $give], [false, $receiverId, $get]] as [$fromSender, $owner, $list])
		{
			$assets = self::ids($list["assets"] ?? []);
			$items = self::ids($list["items"] ?? []);
			$new = self::ids($list["new"] ?? []);
			if (count($assets) + count($items) + count($new) > self::MAX_THINGS) return "At most " . self::MAX_THINGS . " things on each side";
			foreach ($assets as $id)
			{
				$ok = $db->run("SELECT 1 FROM ownedAssets o JOIN assets a ON a.id = o.assetId WHERE o.id = :id AND o.userId = :u AND a.type IN (" . self::types() . ") AND a.approved = 1",
					[":id" => $id, ":u" => $owner])->fetchColumn();
				if (!$ok) return "One of the items can't be traded";
				$things[] = [$fromSender, $id, null, null];
			}
			foreach ($items as $id)
			{
				if (!$db->run("SELECT 1 FROM ProductItems WHERE ID = :id AND HolderID = :u", [":id" => $id, ":u" => $owner])->fetchColumn()) return "One of the passes can't be traded";
				$things[] = [$fromSender, null, $id, null];
			}
			foreach ($new as $id)
			{
				$ok = $db->run("SELECT 1 FROM PlaceProducts p JOIN assets a ON a.id = p.PlaceID WHERE p.ID = :id AND p.IsPass = 1 AND a.creator = :u", [":id" => $id, ":u" => $owner])->fetchColumn();
				if (!$ok) return "Only a place's owner can trade new passes of it";
				$things[] = [$fromSender, null, null, $id];
			}
		}
		if (!$things && !$givePizzas && !$getPizzas) return "The trade is empty";

		$db->pdo->beginTransaction();
		$db->run("INSERT INTO Trades (SenderID, ReceiverID, SenderPizzas, ReceiverPizzas, Created) VALUES (:s, :r, :sp, :rp, UNIX_TIMESTAMP())",
			[":s" => $senderId, ":r" => $receiverId, ":sp" => $givePizzas, ":rp" => $getPizzas]);
		$tradeId = (int) $db->pdo->lastInsertId();
		foreach ($things as [$fromSender, $asset, $item, $new])
			$db->run("INSERT INTO TradeThings (TradeID, FromSender, OwnedAssetID, ItemID, NewProductID) VALUES (:t, :f, :a, :i, :n)",
				[":t" => $tradeId, ":f" => $fromSender ? 1 : 0, ":a" => $asset, ":i" => $item, ":n" => $new]);
		$db->pdo->commit();
		return $tradeId;
	}

	// Does the trade: everything is checked again at this moment, and either all of it happens or
	// none of it. Returns an error text, or false when it's done.
	static function Accept($tradeId, $receiverId)
	{
		$db = Database::singleton();
		$db->pdo->beginTransaction();
		try
		{
			$t = $db->run("SELECT * FROM Trades WHERE ID = :id AND ReceiverID = :u AND Status = 0 FOR UPDATE", [":id" => (int) $tradeId, ":u" => (int) $receiverId])->fetch(\PDO::FETCH_OBJ);
			if (!$t)
			{
				$db->pdo->rollBack();
				return "That trade isn't waiting for you any more";
			}
			$sender = (int) $t->SenderID;
			$receiver = (int) $t->ReceiverID;
			// both players' rows, always in the same order (no deadlocks between two trades)
			$db->run("SELECT id FROM users WHERE id IN (:a, :b) ORDER BY id FOR UPDATE", [":a" => min($sender, $receiver), ":b" => max($sender, $receiver)]);

			$name = fn($id) => Users::GetNameFromID($id);
			$moves = [];
			$gettingAssets = [$sender => [], $receiver => []];
			$gettingPasses = [$sender => [], $receiver => []];
			foreach ($db->run("SELECT * FROM TradeThings WHERE TradeID = :t", [":t" => (int) $t->ID])->fetchAll(\PDO::FETCH_OBJ) as $thing)
			{
				$from = $thing->FromSender ? $sender : $receiver;
				$to = $thing->FromSender ? $receiver : $sender;
				if ($thing->OwnedAssetID)
				{
					$a = $db->run("SELECT o.id, o.assetId, a.name FROM ownedAssets o JOIN assets a ON a.id = o.assetId WHERE o.id = :id AND o.userId = :u FOR UPDATE",
						[":id" => (int) $thing->OwnedAssetID, ":u" => $from])->fetch(\PDO::FETCH_OBJ);
					if (!$a) throw new TradeProblem($name($from) . " doesn't have one of the items any more");
					if (Catalog::OwnsAsset($to, $a->assetId) || isset($gettingAssets[$to][$a->assetId])) throw new TradeProblem($name($to) . " already has " . $a->name);
					$gettingAssets[$to][$a->assetId] = true;
					$moves[] = ["asset", (int) $a->id, $to];
				}
				else if ($thing->ItemID)
				{
					$i = $db->run("SELECT i.ID, i.ProductID, p.Name FROM ProductItems i JOIN PlaceProducts p ON p.ID = i.ProductID WHERE i.ID = :id AND i.HolderID = :u FOR UPDATE",
						[":id" => (int) $thing->ItemID, ":u" => $from])->fetch(\PDO::FETCH_OBJ);
					if (!$i) throw new TradeProblem($name($from) . " doesn't have one of the passes any more");
					if (Products::Holds($to, $i->ProductID) || isset($gettingPasses[$to][$i->ProductID])) throw new TradeProblem($name($to) . " already has " . $i->Name);
					$gettingPasses[$to][$i->ProductID] = true;
					$moves[] = ["item", (int) $i->ID, $to];
				}
				else
				{
					$p = $db->run("SELECT p.ID, p.Name FROM PlaceProducts p JOIN assets a ON a.id = p.PlaceID WHERE p.ID = :id AND p.IsPass = 1 AND a.creator = :u",
						[":id" => (int) $thing->NewProductID, ":u" => $from])->fetch(\PDO::FETCH_OBJ);
					if (!$p) throw new TradeProblem("One of the passes can't be traded any more");
					if (Products::Holds($to, $p->ID) || isset($gettingPasses[$to][$p->ID])) throw new TradeProblem($name($to) . " already has " . $p->Name);
					$gettingPasses[$to][$p->ID] = true;
					$moves[] = ["new", (int) $p->ID, $to];
				}
			}

			foreach ([[$sender, $receiver, (int) $t->SenderPizzas], [$receiver, $sender, (int) $t->ReceiverPizzas]] as [$payer, $payee, $amount])
			{
				if ($amount <= 0) continue;
				$paid = $db->run("UPDATE users SET currency = currency - :c WHERE id = :u AND currency >= :c2", [":c" => $amount, ":u" => $payer, ":c2" => $amount])->rowCount();
				if (!$paid) throw new TradeProblem($name($payer) . " doesn't have " . number_format($amount) . " Pizzas");
				$db->run("UPDATE users SET currency = currency + :c WHERE id = :u", [":c" => $amount, ":u" => $payee]);
			}
			foreach ($moves as [$kind, $id, $to])
			{
				if ($kind === "asset") $db->run("UPDATE ownedAssets SET userId = :to, wearing = 0 WHERE id = :id", [":to" => $to, ":id" => $id]);
				else if ($kind === "item") $db->run("UPDATE ProductItems SET HolderID = :to WHERE ID = :id", [":to" => $to, ":id" => $id]);
				else $db->run("INSERT INTO ProductItems (ProductID, HolderID, PurchaseID, Created) VALUES (:p, :to, NULL, UNIX_TIMESTAMP())", [":p" => $id, ":to" => $to]);
			}
			$db->run("UPDATE Trades SET Status = :s, Decided = UNIX_TIMESTAMP() WHERE ID = :id", [":s" => self::DONE, ":id" => (int) $t->ID]);
			$db->pdo->commit();
			return false;
		}
		catch (TradeProblem $e)
		{
			$db->pdo->rollBack();
			$db->run("UPDATE Trades SET Status = :s, Note = :n, Decided = UNIX_TIMESTAMP() WHERE ID = :id AND Status = 0",
				[":s" => self::FAILED, ":n" => mb_substr($e->getMessage(), 0, 200), ":id" => (int) $tradeId]);
			return $e->getMessage() . ", so the trade couldn't be done";
		}
		catch (\PDOException $e)
		{
			$db->pdo->rollBack();
			return "Something went wrong. Nothing was traded.";
		}
	}

	static function Decline($tradeId, $receiverId)
	{
		Database::singleton()->run("UPDATE Trades SET Status = :s, Decided = UNIX_TIMESTAMP() WHERE ID = :id AND ReceiverID = :u AND Status = 0",
			[":s" => self::DECLINED, ":id" => (int) $tradeId, ":u" => (int) $receiverId]);
	}

	static function Cancel($tradeId, $senderId)
	{
		Database::singleton()->run("UPDATE Trades SET Status = :s, Decided = UNIX_TIMESTAMP() WHERE ID = :id AND SenderID = :u AND Status = 0",
			[":s" => self::CANCELLED, ":id" => (int) $tradeId, ":u" => (int) $senderId]);
	}

	// Somebody's trades, newest first, each with what each side gives (as names).
	static function ForUser($userId, $limit = 50)
	{
		$db = Database::singleton();
		$trades = $db->run(
			"SELECT t.*, s.username AS SenderName, r.username AS ReceiverName FROM Trades t
			 LEFT JOIN users s ON s.id = t.SenderID LEFT JOIN users r ON r.id = t.ReceiverID
			 WHERE t.SenderID = :u OR t.ReceiverID = :u2 ORDER BY t.Status = 0 DESC, t.ID DESC LIMIT " . (int) $limit,
			[":u" => (int) $userId, ":u2" => (int) $userId]
		)->fetchAll(\PDO::FETCH_OBJ);
		foreach ($trades as $t)
		{
			$t->SenderGives = [];
			$t->ReceiverGives = [];
			$things = $db->run(
				"SELECT th.FromSender, a.name AS AssetName, a.id AS AssetID, ip.Name AS ItemName, ipl.name AS ItemPlace, np.Name AS NewName, npl.name AS NewPlace
				 FROM TradeThings th
				 LEFT JOIN ownedAssets o ON o.id = th.OwnedAssetID LEFT JOIN assets a ON a.id = o.assetId
				 LEFT JOIN ProductItems i ON i.ID = th.ItemID LEFT JOIN PlaceProducts ip ON ip.ID = i.ProductID LEFT JOIN assets ipl ON ipl.id = ip.PlaceID
				 LEFT JOIN PlaceProducts np ON np.ID = th.NewProductID LEFT JOIN assets npl ON npl.id = np.PlaceID
				 WHERE th.TradeID = :t",
				[":t" => (int) $t->ID]
			)->fetchAll(\PDO::FETCH_OBJ);
			foreach ($things as $th)
			{
				if ($th->AssetName !== null) $label = $th->AssetName;
				else if ($th->ItemName !== null) $label = $th->ItemName . " (" . $th->ItemPlace . ")";
				else if ($th->NewName !== null) $label = $th->NewName . " (" . $th->NewPlace . ")";
				else $label = "(no longer there)";
				if ($th->FromSender) $t->SenderGives[] = $label; else $t->ReceiverGives[] = $label;
			}
		}
		return $trades;
	}
}

class TradeProblem extends \Exception {}