Repositories | Polyback | Log in to see private repositories
11,202 bytes | parent directory
<?php
namespace pizzaboxer\ProjectPolygon;
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Thumbnails;
// Friends chat: 1:1 messages between friends (ChatMessages) and friends' presence.
//
// Presence comes from what the site already tracks:
// - users.lastonline: set by Users::UpdatePing() on every signed-in request (pages, APIs,
// the 60 s update-ping and the chat page's polling)
// - GameJobPlayers (Polygon Player games): who is in which running GameJobs server, kept
// by the game server's ticket redeems and player reports
// - users.ClientPresence*: old clients' ClientPresence.ashx pings
class Chat
{
const MAX_LENGTH = 500;
const ONLINE_SECONDS = 120;
const HISTORY_PAGE = 50;
const TYPING_SECONDS = 5;
// rate limit: at most this many messages in the window (seconds)
const RATE_BURST = 6;
const RATE_BURST_WINDOW = 10;
const RATE_MINUTE = 30;
static function AreFriends($UserID, $FriendID)
{
if ($UserID == $FriendID) return false;
return (bool) Database::singleton()->run(
"SELECT 1 FROM friends WHERE status = 1
AND ((requesterId = :a AND receiverId = :b) OR (requesterId = :b AND receiverId = :a)) LIMIT 1",
[":a" => (int) $UserID, ":b" => (int) $FriendID]
)->fetchColumn();
}
// unread messages per friend (only from current friends, so an unfriended sender's
// messages don't keep the badge lit): [friendId => count]
static function GetUnreadCounts($UserID)
{
$rows = Database::singleton()->run(
"SELECT m.SenderID, COUNT(*) FROM ChatMessages m
WHERE m.ReceiverID = :uid AND m.IsRead = 0 AND EXISTS (
SELECT 1 FROM friends f WHERE f.status = 1
AND ((f.requesterId = m.SenderID AND f.receiverId = :uid) OR (f.receiverId = m.SenderID AND f.requesterId = :uid))
)
GROUP BY m.SenderID",
[":uid" => (int) $UserID]
)->fetchAll(\PDO::FETCH_KEY_PAIR);
$counts = [];
foreach ($rows as $sender => $count) $counts[(int) $sender] = (int) $count;
return $counts;
}
static function GetUnreadTotal($UserID)
{
return array_sum(self::GetUnreadCounts($UserID));
}
static function MarkRead($UserID, $FriendID)
{
Database::singleton()->run(
"UPDATE ChatMessages SET IsRead = 1 WHERE ReceiverID = :uid AND IsRead = 0 AND SenderID = :fid",
[":uid" => (int) $UserID, ":fid" => (int) $FriendID]
);
}
// messages between two users, oldest first: newer than $AfterID (polling), or (history,
// $AfterID null) the page before $BeforeID (0: the latest page)
static function GetMessages($UserID, $FriendID, $AfterID = null, $BeforeID = 0)
{
$args = [":a" => (int) $UserID, ":b" => (int) $FriendID, ":limit" => self::HISTORY_PAGE];
if ($AfterID !== null)
{
$condition = "ID > :id";
$order = "ID ASC";
$args[":id"] = (int) $AfterID;
}
else
{
$condition = $BeforeID > 0 ? "ID < :id" : "1";
$order = "ID DESC";
if ($BeforeID > 0) $args[":id"] = (int) $BeforeID;
}
// one index range per direction (Conversation key: SenderID, ReceiverID, ID)
$rows = Database::singleton()->run(
"SELECT * FROM (
(SELECT ID, SenderID, Message, TimeSent FROM ChatMessages WHERE SenderID = :a AND ReceiverID = :b AND {$condition} ORDER BY {$order} LIMIT :limit)
UNION ALL
(SELECT ID, SenderID, Message, TimeSent FROM ChatMessages WHERE SenderID = :b AND ReceiverID = :a AND {$condition} ORDER BY {$order} LIMIT :limit)
) AS conversation ORDER BY {$order} LIMIT :limit",
$args
)->fetchAll(\PDO::FETCH_OBJ);
if ($order == "ID DESC") $rows = array_reverse($rows);
return array_map([self::class, "FormatMessage"], $rows);
}
// message text is HTML-escaped here (the page inserts it as HTML)
static function FormatMessage($row)
{
return [
"id" => (int) $row->ID,
"sender" => (int) $row->SenderID,
"message" => Polygon::FilterText($row->Message),
"time" => (int) $row->TimeSent,
"timeText" => date("j/n/Y g:i A", $row->TimeSent)
];
}
// Validates and stores a message. Returns the message, or a string saying what's wrong.
static function Send($UserID, $FriendID, $Message)
{
// no control or bidi-override characters (newlines and tabs are fine), normalised line
// endings, no more than one blank line in a row
$Message = str_replace(["\r\n", "\r"], "\n", (string) $Message);
$Message = preg_replace('/[^\P{Cc}\n\t]|[\x{202A}-\x{202E}\x{2066}-\x{2069}]/u', "", $Message);
if ($Message === null) return "Your message isn't valid text";
$Message = trim(preg_replace("/\n{3,}/", "\n\n", $Message));
if (!strlen($Message)) return "Your message can't be empty";
if (mb_strlen($Message) > self::MAX_LENGTH) return "Your message can't be longer than " . self::MAX_LENGTH . " characters";
if (!self::AreFriends($UserID, $FriendID)) return "You can only chat with your friends";
$recent = Database::singleton()->run(
"SELECT COUNT(*) AS Minute, COALESCE(SUM(TimeSent > UNIX_TIMESTAMP() - :burst), 0) AS Burst
FROM ChatMessages WHERE SenderID = :uid AND TimeSent > UNIX_TIMESTAMP() - 60",
[":uid" => (int) $UserID, ":burst" => self::RATE_BURST_WINDOW]
)->fetch(\PDO::FETCH_OBJ);
if ($recent->Burst >= self::RATE_BURST || $recent->Minute >= self::RATE_MINUTE)
return "You're sending messages too quickly. Please wait a moment.";
Database::singleton()->run(
"INSERT INTO ChatMessages (SenderID, ReceiverID, Message, TimeSent) VALUES (:uid, :fid, :msg, UNIX_TIMESTAMP())",
[":uid" => (int) $UserID, ":fid" => (int) $FriendID, ":msg" => $Message]
);
$messageId = Database::singleton()->lastInsertId();
// a sent message ends "typing"
self::SetTyping($UserID, $FriendID, false);
return self::FormatMessage((object) [
"ID" => $messageId,
"SenderID" => $UserID,
"Message" => $Message,
"TimeSent" => time()
]);
}
// Typing status: one row per sender -> recipient (ChatTyping), Updated = when the sender
// last said they were typing (0: stopped). It counts for TYPING_SECONDS.
static function SetTyping($UserID, $FriendID, $Typing)
{
if ($Typing)
{
Database::singleton()->run(
"INSERT INTO ChatTyping (SenderID, ReceiverID, Updated) VALUES (:uid, :fid, UNIX_TIMESTAMP())
ON DUPLICATE KEY UPDATE Updated = UNIX_TIMESTAMP()",
[":uid" => (int) $UserID, ":fid" => (int) $FriendID]
);
}
else
{
Database::singleton()->run(
"UPDATE ChatTyping SET Updated = 0 WHERE SenderID = :uid AND ReceiverID = :fid AND Updated > 0",
[":uid" => (int) $UserID, ":fid" => (int) $FriendID]
);
}
}
// ids of the friends typing to this user right now
static function GetTypingTo($UserID)
{
return array_map("intval", Database::singleton()->run(
"SELECT t.SenderID FROM ChatTyping t
WHERE t.ReceiverID = :uid AND t.Updated > UNIX_TIMESTAMP() - :secs AND EXISTS (
SELECT 1 FROM friends f WHERE f.status = 1
AND ((f.requesterId = t.SenderID AND f.receiverId = :uid) OR (f.receiverId = t.SenderID AND f.requesterId = :uid))
)",
[":uid" => (int) $UserID, ":secs" => self::TYPING_SECONDS]
)->fetchAll(\PDO::FETCH_COLUMN));
}
// All of a user's friends with their status:
// status "ingame" (with game name/link, and jobId when the viewer may join that
// server), "online" (seen on the site in the last ONLINE_SECONDS) or "offline".
// Usernames and game names are HTML-escaped.
static function GetFriendsPresence($UserID, $WithAvatars = false)
{
$friends = Database::singleton()->run(
"SELECT users.id, users.username, users.lastonline,
users.ClientPresenceType, users.ClientPresencePing, users.ClientPresenceLocation
FROM friends
INNER JOIN users ON users.id = IF(friends.requesterId = :uid, friends.receiverId, friends.requesterId)
WHERE (friends.requesterId = :uid OR friends.receiverId = :uid) AND friends.status = 1
GROUP BY users.id",
[":uid" => (int) $UserID]
)->fetchAll(\PDO::FETCH_OBJ);
if (!count($friends)) return [];
$friendIds = array_map(fn($f) => (int) $f->id, $friends);
$idList = implode(",", $friendIds); // ints only
// Polygon Player games: the most recent running server each friend is in
$games = [];
$rows = Database::singleton()->run(
"SELECT p.UserID, j.JobID, j.PlaceID, j.Private, j.PrivateMode, j.OwnerID, j.RequestedBy, assets.name AS PlaceName
FROM GameJobPlayers p
INNER JOIN GameJobs j ON j.JobID = p.JobID AND j.Status = 'Ready'
INNER JOIN assets ON assets.id = j.PlaceID
WHERE p.UserID IN ({$idList}) AND p.Active = 1
ORDER BY p.Joined ASC"
)->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) $games[(int) $row->UserID] = $row;
// old clients (ClientPresence.ashx): a place, but no server we could send anyone to
$legacyPlaces = [];
$legacyIds = array_unique(array_map(fn($f) => (int) $f->ClientPresenceLocation, array_filter($friends,
fn($f) => $f->ClientPresenceType == "Visit" && $f->ClientPresenceLocation && $f->ClientPresencePing + 65 > time())));
if (count($legacyIds))
{
$legacyPlaces = Database::singleton()->run(
"SELECT id, name FROM assets WHERE id IN (" . implode(",", $legacyIds) . ")"
)->fetchAll(\PDO::FETCH_KEY_PAIR);
}
$result = [];
foreach ($friends as $friend)
{
$id = (int) $friend->id;
$item = [
"userId" => $id,
"username" => htmlspecialchars($friend->username, ENT_QUOTES),
"status" => "offline",
"lastOnline" => (int) $friend->lastonline,
"lastOnlineText" => $friend->lastonline ? GetReadableTime($friend->lastonline) : "never",
"game" => null
];
if (isset($games[$id]))
{
$job = $games[$id];
$item["status"] = "ingame";
$item["game"] = [
"placeId" => (int) $job->PlaceID,
"name" => Polygon::FilterText($job->PlaceName),
"url" => "/" . encode_asset_name($job->PlaceName) . "-place?id=" . (int) $job->PlaceID,
"jobId" => self::CanJoinJob($job, $UserID, $friendIds) ? $job->JobID : null,
"private" => (bool) $job->Private
];
}
else if (isset($legacyPlaces[(int) $friend->ClientPresenceLocation]) && $friend->ClientPresencePing + 65 > time())
{
$placeId = (int) $friend->ClientPresenceLocation;
$name = $legacyPlaces[$placeId];
$item["status"] = "ingame";
$item["game"] = [
"placeId" => $placeId,
"name" => Polygon::FilterText($name),
"url" => "/" . encode_asset_name($name) . "-place?id=" . $placeId,
"jobId" => null,
"private" => false
];
}
else if ($friend->lastonline + self::ONLINE_SECONDS > time())
{
$item["status"] = "online";
}
if ($WithAvatars) $item["avatar"] = Thumbnails::GetAvatar($id, 110, 110);
$result[] = $item;
}
return $result;
}
// Could the viewer join this server? Same rules as the join API (Games::CanJoinJob):
// public servers yes; friends-only private servers if the viewer is the owner or one of
// the owner's friends; solo private servers only the owner. The join API checks again.
private static function CanJoinJob($Job, $ViewerID, $ViewerFriendIds)
{
if (!$Job->Private) return true;
$owner = (int) ($Job->OwnerID ?? $Job->RequestedBy);
if ($owner == $ViewerID) return true;
if ($Job->PrivateMode !== "Friends") return false;
return in_array($owner, $ViewerFriendIds, true);
}
}