Repositories | Polyback | Log in to see private repositories


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

7,255 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. Returns an error text or null.
	static function Save($placeId, $name, $description, $price)
	{
		$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]
		);
		return null;
	}

	// 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, 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";
			$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 ($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);
	}

	// 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];
	}
}