Repositories | Polyback | Log in to see private repositories


polyback-website / ac78c54296647694d1132210737d1561aac5f7d1 / api/private/classes/pizzaboxer/ProjectPolygon/Products.php

12,640 bytes | parent directory

<?php

namespace pizzaboxer\ProjectPolygon;

// Buying inside games: a place's products, and catalog items it offers. The place's owner (or the
// item's creator) gets everything that's paid; the site keeps nothing.
class Products
{
	const MAX_PER_PLACE = 100;
	const MAX_PRICE = 1000000;

	static function ForPlace($placeId, $all = false)
	{
		return Database::singleton()->run(
			"SELECT * FROM PlaceProducts WHERE PlaceID = :p" . ($all ? "" : " AND Active = 1") . " ORDER BY Active DESC, ID",
			[":p" => (int) $placeId]
		)->fetchAll(\PDO::FETCH_OBJ);
	}

	// Checks what an owner typed in. Returns an error text, or null if it's fine.
	static function Problem($name, $description, $price)
	{
		if (!is_string($name) || trim($name) === "") return "The product needs a name";
		if (mb_strlen($name) > 50) return "The name can't be longer than 50 characters";
		if (!is_string($description) || mb_strlen($description) > 500) return "The description can't be longer than 500 characters";
		if (Polygon::IsExplicitlyFiltered($name) || Polygon::IsExplicitlyFiltered($description)) return "That contains inappropriate text";
		if (!preg_match('/^[0-9]{1,7}$/', (string) $price) || (int) $price < 1 || (int) $price > self::MAX_PRICE) return "The price has to be from 1 to " . number_format(self::MAX_PRICE) . " Pizzas";
		return null;
	}

	// Adds a product, or changes the place's product of that name. $isPass: kept and tradable
	// (true), used up (false), or as it was (null). Returns an error text or null.
	static function Save($placeId, $name, $description, $price, $isPass = null)
	{
		$name = trim((string) $name);
		if ($problem = self::Problem($name, $description, $price)) return $problem;
		$db = Database::singleton();
		$exists = $db->run("SELECT ID FROM PlaceProducts WHERE PlaceID = :p AND Name = :n", [":p" => (int) $placeId, ":n" => $name])->fetchColumn();
		if (!$exists && $db->run("SELECT COUNT(*) FROM PlaceProducts WHERE PlaceID = :p", [":p" => (int) $placeId])->fetchColumn() >= self::MAX_PER_PLACE)
			return "A place can't have more than " . self::MAX_PER_PLACE . " products";
		$db->run(
			"INSERT INTO PlaceProducts (PlaceID, Name, Description, Price, Created) VALUES (:p, :n, :d, :c, UNIX_TIMESTAMP())
			 ON DUPLICATE KEY UPDATE Description = VALUES(Description), Price = VALUES(Price), Active = 1",
			[":p" => (int) $placeId, ":n" => $name, ":d" => $description, ":c" => (int) $price]
		);
		if ($isPass !== null)
		{
			$id = $db->run("SELECT ID FROM PlaceProducts WHERE PlaceID = :p AND Name = :n", [":p" => (int) $placeId, ":n" => $name])->fetchColumn();
			return self::SetPass($placeId, $id, $isPass);
		}
		return null;
	}

	// Makes a product a pass (kept, tradable) or not. Who bought it already gets their pass; a pass
	// that somebody holds can't stop being one.
	static function SetPass($placeId, $productId, $on)
	{
		$db = Database::singleton();
		$product = $db->run("SELECT * FROM PlaceProducts WHERE ID = :id AND PlaceID = :p", [":id" => (int) $productId, ":p" => (int) $placeId])->fetch(\PDO::FETCH_OBJ);
		if (!$product) return "There's no such product";
		if ($on)
		{
			$db->run("UPDATE PlaceProducts SET IsPass = 1 WHERE ID = :id", [":id" => (int) $product->ID]);
			$db->run(
				"INSERT IGNORE INTO ProductItems (ProductID, HolderID, PurchaseID, Created)
				 SELECT ProductID, UserID, ID, Created FROM GamePurchases WHERE ProductID = :id AND Revoked = 0",
				[":id" => (int) $product->ID]
			);
			return null;
		}
		if ($db->run("SELECT COUNT(*) FROM ProductItems WHERE ProductID = :id", [":id" => (int) $product->ID])->fetchColumn() > 0)
			return "Players hold this pass, so it has to stay one";
		$db->run("UPDATE PlaceProducts SET IsPass = 0 WHERE ID = :id", [":id" => (int) $product->ID]);
		return null;
	}

	// Whether somebody holds a pass (bought or traded, not refunded or taken back).
	static function Holds($userId, $productId)
	{
		return (bool) Database::singleton()->run("SELECT 1 FROM ProductItems WHERE ProductID = :id AND HolderID = :u LIMIT 1",
			[":id" => (int) $productId, ":u" => (int) $userId])->fetchColumn();
	}

	// What's offered to somebody in a game: name, price, seller... or an error text.
	static function Offer($placeId, $productId, $assetId, $userId)
	{
		$db = Database::singleton();
		if ($productId)
		{
			$row = $db->run(
				"SELECT p.ID, p.Name, p.Description, p.Price, p.IsPass, a.creator AS SellerID FROM PlaceProducts p
				 JOIN assets a ON a.id = p.PlaceID WHERE p.ID = :id AND p.PlaceID = :p AND p.Active = 1",
				[":id" => (int) $productId, ":p" => (int) $placeId]
			)->fetch(\PDO::FETCH_OBJ);
			if (!$row) return "This isn't for sale";
			if ($row->IsPass && self::Holds($userId, $row->ID)) return "You already have this";
			$row->ProductID = (int) $row->ID;
			$row->AssetID = null;
		}
		else
		{
			$asset = Catalog::GetAssetInfo((int) $assetId);
			if (!$asset || !$asset->sale || $asset->type == 9 || (isset($asset->approved) && $asset->approved != 1)) return "This isn't for sale";
			if (Catalog::OwnsAsset($userId, $asset->id)) return "You already own this";
			$row = (object) ["Name" => $asset->name, "Description" => $asset->description, "Price" => (int) $asset->price, "SellerID" => (int) $asset->creator,
				"ProductID" => null, "AssetID" => (int) $asset->id];
		}
		$row->Price = (int) $row->Price;
		$row->SellerID = (int) $row->SellerID;
		$row->Balance = (int) $db->run("SELECT currency FROM users WHERE id = :u", [":u" => (int) $userId])->fetchColumn();
		return $row;
	}

	// Pays for an offer. $nonce makes asking twice harmless. Returns the purchase or an error text.
	static function Buy($job, $userId, $offer, $price, $nonce)
	{
		$db = Database::singleton();
		$done = $db->run("SELECT * FROM GamePurchases WHERE Nonce = :n", [":n" => $nonce])->fetch(\PDO::FETCH_OBJ);
		if ($done) return (int) $done->UserID === (int) $userId ? $done : "That didn't work";
		if ($offer->Price !== (int) $price) return "The price has changed";
		$flagged = 0;
		if ($offer->SellerID !== (int) $userId)
		{
			foreach (Users::GetAlternateAccounts($offer->SellerID) as $alt) if ((int) $alt["userid"] === (int) $userId) $flagged = 1;
		}
		$db->pdo->beginTransaction();
		try
		{
			// the buyer first, and only if they can afford it at this very moment
			$paid = $db->run("UPDATE users SET currency = currency - :c WHERE id = :u AND currency >= :c2",
				[":c" => $offer->Price, ":u" => (int) $userId, ":c2" => $offer->Price])->rowCount();
			if (!$paid && $offer->Price > 0)
			{
				$db->pdo->rollBack();
				return "You can't afford this";
			}
			$db->run("UPDATE users SET currency = currency + :c WHERE id = :u", [":c" => $offer->Price, ":u" => $offer->SellerID]);
			$db->run(
				"INSERT INTO GamePurchases (Nonce, PlaceID, JobID, UserID, SellerID, ProductID, AssetID, Amount, Granted, Created)
				 VALUES (:n, :p, :j, :u, :s, :pr, :a, :c, :g, UNIX_TIMESTAMP())",
				[":n" => $nonce, ":p" => (int) $job->PlaceID, ":j" => $job->JobID, ":u" => (int) $userId, ":s" => $offer->SellerID,
				 ":pr" => $offer->ProductID, ":a" => $offer->AssetID, ":c" => $offer->Price, ":g" => $offer->AssetID ? 1 : 0]
			);
			$id = (int) $db->pdo->lastInsertId();
			if ($offer->AssetID)
			{
				$db->run("INSERT INTO ownedAssets (assetId, userId, timestamp) VALUES (:a, :u, UNIX_TIMESTAMP())", [":a" => $offer->AssetID, ":u" => (int) $userId]);
				$db->run("UPDATE assets SET Sales = Sales + 1 WHERE id = :a", [":a" => $offer->AssetID]);
			}
			else
			{
				$db->run("UPDATE PlaceProducts SET Sales = Sales + 1 WHERE ID = :id", [":id" => $offer->ProductID]);
				if (!empty($offer->IsPass))
					$db->run("INSERT INTO ProductItems (ProductID, HolderID, PurchaseID, Created) VALUES (:pr, :u, :id, UNIX_TIMESTAMP())",
						[":pr" => $offer->ProductID, ":u" => (int) $userId, ":id" => $id]);
			}
			if ($offer->SellerID !== (int) $userId)
			{
				$db->run(
					"INSERT INTO transactions (purchaser, seller, assetId, ProductID, amount, flagged, timestamp) VALUES (:u, :s, :a, :pr, :c, :f, UNIX_TIMESTAMP())",
					[":u" => (int) $userId, ":s" => $offer->SellerID, ":a" => $offer->AssetID ?? (int) $job->PlaceID, ":pr" => $offer->ProductID, ":c" => $offer->Price, ":f" => $flagged]
				);
			}
			$db->pdo->commit();
		}
		catch (\PDOException $e)
		{
			$db->pdo->rollBack();
			// the same purchase asked for twice at once: the other one did it
			$done = $db->run("SELECT * FROM GamePurchases WHERE Nonce = :n AND UserID = :u", [":n" => $nonce, ":u" => (int) $userId])->fetch(\PDO::FETCH_OBJ);
			return $done ?: "Something went wrong. You haven't been charged.";
		}
		return $db->run("SELECT * FROM GamePurchases WHERE ID = :id", [":id" => $id])->fetch(\PDO::FETCH_OBJ);
	}

	const REFUNDED = 1;
	const TAKEN_BACK = 2;

	// Gives the buyer back exactly what they paid (not today's price), from the seller, and the
	// purchase no longer counts as owned. Returns an error, or false when it's done.
	static function Refund($placeId, $purchaseId)
	{
		$db = Database::singleton();
		$db->pdo->beginTransaction();
		try
		{
			$p = $db->run("SELECT * FROM GamePurchases WHERE ID = :id AND PlaceID = :p AND ProductID IS NOT NULL FOR UPDATE",
				[":id" => (int) $purchaseId, ":p" => (int) $placeId])->fetch(\PDO::FETCH_OBJ);
			if (!$p || (int) $p->Revoked !== 0)
			{
				$db->pdo->rollBack();
				return "That purchase can't be refunded";
			}
			// a pass is only refunded while the buyer still has it (not after trading it away)
			$isPass = (int) $db->run("SELECT IsPass FROM PlaceProducts WHERE ID = :id", [":id" => (int) $p->ProductID])->fetchColumn();
			if ($isPass)
			{
				$item = $db->run("SELECT ID FROM ProductItems WHERE PurchaseID = :id AND HolderID = :u FOR UPDATE",
					[":id" => (int) $p->ID, ":u" => (int) $p->UserID])->fetchColumn();
				if (!$item)
				{
					$db->pdo->rollBack();
					return "The buyer doesn't have it any more (it was traded away), so it can't be refunded automatically. An administrator can look into it.";
				}
				$db->run("DELETE FROM ProductItems WHERE ID = :id", [":id" => (int) $item]);
			}
			$amount = (int) $p->Amount;
			if ((int) $p->SellerID !== (int) $p->UserID && $amount > 0)
			{
				$taken = $db->run("UPDATE users SET currency = currency - :c WHERE id = :s AND currency >= :c2",
					[":c" => $amount, ":s" => (int) $p->SellerID, ":c2" => $amount])->rowCount();
				if (!$taken)
				{
					$db->pdo->rollBack();
					return "The seller doesn't have the " . number_format($amount) . " Pizzas to refund it";
				}
				$db->run("UPDATE users SET currency = currency + :c WHERE id = :u", [":c" => $amount, ":u" => (int) $p->UserID]);
			}
			$db->run("UPDATE GamePurchases SET Revoked = :r WHERE ID = :id", [":r" => self::REFUNDED, ":id" => (int) $p->ID]);
			$db->run("UPDATE PlaceProducts SET Sales = GREATEST(Sales - 1, 0) WHERE ID = :id", [":id" => (int) $p->ProductID]);
			$db->pdo->commit();
		}
		catch (\PDOException $e)
		{
			$db->pdo->rollBack();
			return "Something went wrong. Nothing was changed.";
		}
		return false;
	}

	// Staff only: no longer owned without a refund, or owned again.
	// (a pass is taken from whoever holds it now; given back, it goes to the buyer)
	static function TakeBack($placeId, $purchaseId, $back)
	{
		$db = Database::singleton();
		$changed = $db->run(
			"UPDATE GamePurchases SET Revoked = :to WHERE ID = :id AND PlaceID = :p AND ProductID IS NOT NULL AND Revoked = :from",
			[":to" => $back ? self::TAKEN_BACK : 0, ":from" => $back ? 0 : self::TAKEN_BACK, ":id" => (int) $purchaseId, ":p" => (int) $placeId]
		)->rowCount();
		if (!$changed) return;
		if ($back)
		{
			$db->run("DELETE FROM ProductItems WHERE PurchaseID = :id", [":id" => (int) $purchaseId]);
		}
		else
		{
			$db->run(
				"INSERT IGNORE INTO ProductItems (ProductID, HolderID, PurchaseID, Created)
				 SELECT g.ProductID, g.UserID, g.ID, UNIX_TIMESTAMP() FROM GamePurchases g JOIN PlaceProducts p ON p.ID = g.ProductID WHERE g.ID = :id AND p.IsPass = 1",
				[":id" => (int) $purchaseId]
			);
		}
	}

	// Paid for in this place, but its scripts haven't handed it out yet.
	static function Waiting($placeId, $userId)
	{
		return Database::singleton()->run(
			"SELECT * FROM GamePurchases WHERE UserID = :u AND PlaceID = :p AND Granted = 0 ORDER BY ID LIMIT 50",
			[":u" => (int) $userId, ":p" => (int) $placeId]
		)->fetchAll(\PDO::FETCH_OBJ);
	}

	static function Receipt($purchase)
	{
		return ["purchaseId" => (int) $purchase->ID, "productId" => (int) $purchase->ProductID, "placeId" => (int) $purchase->PlaceID,
			"userId" => (int) $purchase->UserID, "amount" => (int) $purchase->Amount, "granted" => (bool) $purchase->Granted];
	}
}