Moved user related stuff into its own context object.

This commit is contained in:
flash 2023-09-06 13:50:19 +00:00
parent 7190a5f4df
commit 9b2c409a24
37 changed files with 367 additions and 624 deletions

View file

@ -9,7 +9,7 @@ if($msz->isLoggedIn()) {
return; return;
} }
$users = $msz->getUsers(); $users = $msz->getUsersContext()->getUsers();
$sessions = $msz->getSessions(); $sessions = $msz->getSessions();
$loginAttempts = $msz->getLoginAttempts(); $loginAttempts = $msz->getLoginAttempts();

View file

@ -9,7 +9,7 @@ if($msz->isLoggedIn()) {
return; return;
} }
$users = $msz->getUsers(); $users = $msz->getUsersContext()->getUsers();
$recoveryTokens = $msz->getRecoveryTokens(); $recoveryTokens = $msz->getRecoveryTokens();
$loginAttempts = $msz->getLoginAttempts(); $loginAttempts = $msz->getLoginAttempts();

View file

@ -9,8 +9,9 @@ if($msz->isLoggedIn()) {
return; return;
} }
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$roles = $msz->getRoles(); $users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$config = $msz->getConfig(); $config = $msz->getConfig();
$register = !empty($_POST['register']) && is_array($_POST['register']) ? $_POST['register'] : []; $register = !empty($_POST['register']) && is_array($_POST['register']) ? $_POST['register'] : [];

View file

@ -10,7 +10,7 @@ if($msz->isLoggedIn()) {
return; return;
} }
$users = $msz->getUsers(); $users = $msz->getUsersContext()->getUsers();
$sessions = $msz->getSessions(); $sessions = $msz->getSessions();
$tfaSessions = $msz->getTFASessions(); $tfaSessions = $msz->getTFASessions();
$loginAttempts = $msz->getLoginAttempts(); $loginAttempts = $msz->getLoginAttempts();

View file

@ -5,7 +5,7 @@ use stdClass;
use RuntimeException; use RuntimeException;
$forum = $msz->getForum(); $forum = $msz->getForum();
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$categoryId = (int)filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT); $categoryId = (int)filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);
@ -45,8 +45,6 @@ $forumPagination = new Pagination($forum->countTopics(
if(!$forumPagination->hasValidOffset()) if(!$forumPagination->hasValidOffset())
Template::throwError(404); Template::throwError(404);
$userInfos = [];
$userColours = [];
$children = []; $children = [];
$topics = []; $topics = [];
@ -110,15 +108,8 @@ if($categoryInfo->mayHaveChildren()) {
$child->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo); $child->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) { if($lastPostInfo->hasUserId()) {
$lastPostUserId = $lastPostInfo->getUserId(); $child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
if(!array_key_exists($lastPostUserId, $userInfos)) { $child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
$userInfo = $users->getUser($lastPostUserId, 'id');
$userInfos[$lastPostUserId] = $userInfo;
$userColours[$lastPostUserId] = $users->getUserColour($userInfo);
}
$child->lastPost->user = $userInfos[$lastPostUserId];
$child->lastPost->colour = $userColours[$lastPostUserId];
} }
} }
} }
@ -147,15 +138,8 @@ if($categoryInfo->mayHaveTopics()) {
$topic->lastPost = new stdClass; $topic->lastPost = new stdClass;
if($topicInfo->hasUserId()) { if($topicInfo->hasUserId()) {
$lastTopicUserId = $topicInfo->getUserId(); $topic->user = $usersCtx->getUserInfo($topicInfo->getUserId());
if(!array_key_exists($lastTopicUserId, $userInfos)) { $topic->colour = $usersCtx->getUserColour($topic->user);
$userInfo = $users->getUser($lastTopicUserId, 'id');
$userInfos[$lastTopicUserId] = $userInfo;
$userColours[$lastTopicUserId] = $users->getUserColour($userInfo);
}
$topic->user = $userInfos[$lastTopicUserId];
$topic->colour = $userColours[$lastTopicUserId];
} }
try { try {
@ -166,15 +150,8 @@ if($categoryInfo->mayHaveTopics()) {
); );
if($lastPostInfo->hasUserId()) { if($lastPostInfo->hasUserId()) {
$lastPostUserId = $lastPostInfo->getUserId(); $topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
if(!array_key_exists($lastPostUserId, $userInfos)) { $topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
$userInfo = $users->getUser($lastPostUserId, 'id');
$userInfos[$lastPostUserId] = $userInfo;
$userColours[$lastPostUserId] = $users->getUserColour($userInfo);
}
$topic->lastPost->user = $userInfos[$lastPostUserId];
$topic->lastPost->colour = $userColours[$lastPostUserId];
} }
} catch(RuntimeException $ex) {} } catch(RuntimeException $ex) {}
} }

View file

@ -5,7 +5,7 @@ use stdClass;
use RuntimeException; use RuntimeException;
$forum = $msz->getForum(); $forum = $msz->getForum();
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$mode = (string)filter_input(INPUT_GET, 'm'); $mode = (string)filter_input(INPUT_GET, 'm');
$currentUser = $msz->getActiveUser(); $currentUser = $msz->getActiveUser();
@ -46,8 +46,6 @@ if($mode === 'mark') {
if($mode !== '') if($mode !== '')
Template::throwError(404); Template::throwError(404);
$userInfos = [];
$userColours = [];
$categories = $forum->getCategories(hidden: false, asTree: true); $categories = $forum->getCategories(hidden: false, asTree: true);
foreach($categories as $categoryId => $category) { foreach($categories as $categoryId => $category) {
@ -118,15 +116,8 @@ foreach($categories as $categoryId => $category) {
$child->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo); $child->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) { if($lastPostInfo->hasUserId()) {
$lastPostUserId = $lastPostInfo->getUserId(); $child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
if(!array_key_exists($lastPostUserId, $userInfos)) { $child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
$userInfo = $users->getUser($lastPostUserId, 'id');
$userInfos[$lastPostUserId] = $userInfo;
$userColours[$lastPostUserId] = $users->getUserColour($userInfo);
}
$child->lastPost->user = $userInfos[$lastPostUserId];
$child->lastPost->colour = $userColours[$lastPostUserId];
} }
} }
} }
@ -178,15 +169,8 @@ foreach($categories as $categoryId => $category) {
$category->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo); $category->lastPost->topicInfo = $forum->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) { if($lastPostInfo->hasUserId()) {
$lastPostUserId = $lastPostInfo->getUserId(); $category->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
if(!array_key_exists($lastPostUserId, $userInfos)) { $category->lastPost->colour = $usersCtx->getUserColour($category->lastPost->user);
$userInfo = $users->getUser($lastPostInfo->getUserId(), 'id');
$userInfos[$lastPostUserId] = $userInfo;
$userColours[$lastPostUserId] = $users->getUserColour($userInfo);
}
$category->lastPost->user = $userInfos[$lastPostUserId];
$category->lastPost->colour = $userColours[$lastPostUserId];
} }
} }
} }

View file

@ -7,7 +7,7 @@ if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIE
Template::throwError(403); Template::throwError(403);
$forum = $msz->getForum(); $forum = $msz->getForum();
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$config = $cfg->getValues([ $config = $cfg->getValues([
['forum_leader.first_year:i', 2018], ['forum_leader.first_year:i', 2018],
['forum_leader.first_month:i', 12], ['forum_leader.first_month:i', 12],
@ -66,10 +66,7 @@ foreach($rankings as $ranking) {
$ranking->user = $ranking->colour = null; $ranking->user = $ranking->colour = null;
if($ranking->userId !== '') if($ranking->userId !== '')
try { $ranking->user = $usersCtx->getUserInfo($ranking->userId);
$ranking->user = $users->getUser($ranking->userId);
$ranking->colour = $users->getUserColour($ranking->user);
} catch(RuntimeException $ex) {}
} }
$name = 'All Time'; $name = 'All Time';

View file

@ -16,10 +16,8 @@ if($msz->hasActiveBan())
Template::throwError(403); Template::throwError(403);
$forum = $msz->getForum(); $forum = $msz->getForum();
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$userInfos = [];
$userColours = [];
$userPostsCounts = []; $userPostsCounts = [];
$forumPostingModes = [ $forumPostingModes = [
@ -277,16 +275,12 @@ if($mode === 'edit') { // $post is pretty much sure to be populated at this poin
$post->info = $postInfo; $post->info = $postInfo;
if($postInfo->hasUserId()) { if($postInfo->hasUserId()) {
$postUserId = $postInfo->getUserId(); $post->user = $usersCtx->getUserInfo($postInfo->getUserId());
if(!array_key_exists($postUserId, $userInfos)) { $post->colour = $usersCtx->getUserColour($post->user);
$userInfo = $users->getUser($postUserId, 'id');
$userInfos[$postUserId] = $userInfo;
$userColours[$postUserId] = $users->getUserColour($userInfo);
$userPostsCounts[$postUserId] = $forum->countPosts(userInfo: $userInfo, deleted: false);
}
$post->user = $userInfos[$postUserId]; $postUserId = $postInfo->getUserId();
$post->colour = $userColours[$postUserId]; if(!array_key_exists($postUserId, $userPostsCounts))
$userPostsCounts[$postUserId] = $forum->countPosts(userInfo: $post->user, deleted: false);
$post->postsCount = $userPostsCounts[$postUserId]; $post->postsCount = $userPostsCounts[$postUserId];
} }
@ -308,7 +302,7 @@ Template::render('forum.posting', [
'posting_breadcrumbs' => $forum->getCategoryAncestry($categoryInfo), 'posting_breadcrumbs' => $forum->getCategoryAncestry($categoryInfo),
'global_accent_colour' => $forum->getCategoryColour($categoryInfo), 'global_accent_colour' => $forum->getCategoryColour($categoryInfo),
'posting_user' => $currentUser, 'posting_user' => $currentUser,
'posting_user_colour' => $userColours[$currentUser->getId()] ?? $users->getUserColour($currentUser), 'posting_user_colour' => $usersCtx->getUserColour($currentUser),
'posting_user_posts_count' => $userPostsCounts[$currentUser->getId()] ?? $forum->countPosts(userInfo: $currentUser, deleted: false), 'posting_user_posts_count' => $userPostsCounts[$currentUser->getId()] ?? $forum->countPosts(userInfo: $currentUser, deleted: false),
'posting_user_preferred_parser' => $selectedParser, 'posting_user_preferred_parser' => $selectedParser,
'posting_forum' => $categoryInfo, 'posting_forum' => $categoryInfo,

View file

@ -5,7 +5,7 @@ use stdClass;
use RuntimeException; use RuntimeException;
$forum = $msz->getForum(); $forum = $msz->getForum();
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0; $postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0;
$topicId = !empty($_GET['t']) && is_string($_GET['t']) ? (int)$_GET['t'] : 0; $topicId = !empty($_GET['t']) && is_string($_GET['t']) ? (int)$_GET['t'] : 0;
@ -284,8 +284,6 @@ if(empty($postInfos))
$originalPostInfo = $forum->getPost(topicInfo: $topicInfo); $originalPostInfo = $forum->getPost(topicInfo: $topicInfo);
$userInfos = [];
$userColours = [];
$userPostsCounts = []; $userPostsCounts = [];
$posts = []; $posts = [];
@ -294,16 +292,12 @@ foreach($postInfos as $postInfo) {
$post->info = $postInfo; $post->info = $postInfo;
if($postInfo->hasUserId()) { if($postInfo->hasUserId()) {
$postUserId = $postInfo->getUserId(); $post->user = $usersCtx->getUserInfo($postInfo->getUserId());
if(!array_key_exists($postUserId, $userInfos)) { $post->colour = $usersCtx->getUserColour($post->user);
$userInfo = $users->getUser($postUserId, 'id');
$userInfos[$postUserId] = $userInfo;
$userColours[$postUserId] = $users->getUserColour($userInfo);
$userPostsCounts[$postUserId] = $forum->countPosts(userInfo: $userInfo, deleted: false);
}
$post->user = $userInfos[$postUserId]; $postUserId = $postInfo->getUserId();
$post->colour = $userColours[$postUserId]; if(!array_key_exists($postUserId, $userPostsCounts))
$userPostsCounts[$postUserId] = $forum->countPosts(userInfo: $post->user, deleted: false);
$post->postsCount = $userPostsCounts[$postUserId]; $post->postsCount = $userPostsCounts[$postUserId];
} }

View file

@ -7,6 +7,8 @@ if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
Template::throwError(403); Template::throwError(403);
$changelog = $msz->getChangelog(); $changelog = $msz->getChangelog();
$usersCtx = $msz->getUsersContext();
$changelogPagination = new Pagination($changelog->countChanges(), 30); $changelogPagination = new Pagination($changelog->countChanges(), 30);
if(!$changelogPagination->hasValidOffset()) if(!$changelogPagination->hasValidOffset())
@ -14,30 +16,15 @@ if(!$changelogPagination->hasValidOffset())
$changeInfos = $changelog->getChanges(pagination: $changelogPagination); $changeInfos = $changelog->getChanges(pagination: $changelogPagination);
$changes = []; $changes = [];
$userInfos = [];
$userColours = [];
foreach($changeInfos as $changeInfo) { foreach($changeInfos as $changeInfo) {
$userId = $changeInfo->getUserId(); $userInfo = $changeInfo->hasUserId() ? $usersCtx->getUserInfo($changeInfo->getUserId()) : null;
if(array_key_exists($userId, $userInfos)) {
$userInfo = $userInfos[$userId];
} else {
try {
$userInfo = $users->getUser($userId, 'id');
$userColours[$userId] = $users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
}
$userInfos[$userId] = $userInfo;
}
$changes[] = [ $changes[] = [
'change' => $changeInfo, 'change' => $changeInfo,
'tags' => $changelog->getTags(changeInfo: $changeInfo), 'tags' => $changelog->getTags(changeInfo: $changeInfo),
'user' => $userInfo, 'user' => $userInfo,
'user_colour' => $userColours[$userId] ?? \Index\Colour\Colour::none(), 'user_colour' => $usersCtx->getUserColour($userInfo),
]; ];
} }

View file

@ -6,7 +6,7 @@ use Misuzu\Pagination;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_LOGS_VIEW)) if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_LOGS_VIEW))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$auditLog = $msz->getAuditLog(); $auditLog = $msz->getAuditLog();
$pagination = new Pagination($auditLog->countLogs(), 50); $pagination = new Pagination($auditLog->countLogs(), 50);
@ -21,8 +21,8 @@ foreach($logs as $log)
if($log->hasUserId()) { if($log->hasUserId()) {
$userId = $log->getUserId(); $userId = $log->getUserId();
if(!array_key_exists($userId, $userInfos)) { if(!array_key_exists($userId, $userInfos)) {
$userInfos[$userId] = $users->getUser($userId, 'id'); $userInfos[$userId] = $usersCtx->getUserInfo($userId);
$userColours[$userId] = $users->getUserColour($userInfos[$userId]); $userColours[$userId] = $usersCtx->getUserColour($userId);
} }
} }

View file

@ -8,7 +8,8 @@ use Index\DateTime;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_BANS_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_BANS_MANAGE))
Template::throwError(403); Template::throwError(403);
$bans = $msz->getBans(); $usersCtx = $msz->getUsersContext();
$bans = $usersCtx->getBans();
if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) { if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
if(!CSRF::validateRequest()) if(!CSRF::validateRequest())
@ -26,10 +27,8 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete'))
return; return;
} }
$users = $msz->getUsers();
try { try {
$userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id'); $userInfo = $usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
Template::throwError(404); Template::throwError(404);
} }

View file

@ -6,28 +6,19 @@ use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_BANS_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_BANS_MANAGE))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$bans = $usersCtx->getBans();
$userInfos = [
$msz->getActiveUser()->getId() => $msz->getActiveUser(),
];
$userColours = [
$msz->getActiveUser()->getId() => $users->getUserColour($msz->getActiveUser()),
];
$filterUser = null; $filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) { if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT); $filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try { try {
$filterUser = $users->getUser($filterUserId, 'id'); $filterUser = $usersCtx->getUserInfo($filterUserId);
$userInfos[$filterUserId] = $filterUser;
$userColours[$filterUserId] = $users->getUserColour($filterUser);
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
Template::throwError(404); Template::throwError(404);
} }
} }
$bans = $msz->getBans();
$pagination = new Pagination($bans->countBans(userInfo: $filterUser), 10); $pagination = new Pagination($bans->countBans(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset()) if(!$pagination->hasValidOffset())
@ -37,29 +28,15 @@ $banList = [];
$banInfos = $bans->getBans(userInfo: $filterUser, activeFirst: true, pagination: $pagination); $banInfos = $bans->getBans(userInfo: $filterUser, activeFirst: true, pagination: $pagination);
foreach($banInfos as $banInfo) { foreach($banInfos as $banInfo) {
if(array_key_exists($banInfo->getUserId(), $userInfos)) $userInfo = $usersCtx->getUserInfo($banInfo->getUserId());
$userInfo = $userInfos[$banInfo->getUserId()]; $userColour = $usersCtx->getUserColour($userInfo);
else
$userInfos[$banInfo->getUserId()] = $userInfo = $users->getUser($banInfo->getUserId(), 'id');
if(array_key_exists($userInfo->getId(), $userColours))
$userColour = $userColours[$userInfo->getId()];
else
$userColours[$userInfo->getId()] = $userColour = $users->getUserColour($userInfo);
if(!$banInfo->hasModId()) { if(!$banInfo->hasModId()) {
$modInfo = null; $modInfo = null;
$modColour = null; $modColour = null;
} else { } else {
if(array_key_exists($banInfo->getModId(), $userInfos)) $modInfo = $usersCtx->getUserInfo($banInfo->getModId());
$modInfo = $userInfos[$banInfo->getModId()]; $modColour = $usersCtx->getUserColour($modInfo);
else
$userInfos[$banInfo->getModId()] = $modInfo = $users->getUser($banInfo->getModId(), 'id');
if(array_key_exists($modInfo->getId(), $userColours))
$modColour = $userColours[$modInfo->getId()];
else
$userColours[$modInfo->getId()] = $modColour = $users->getUserColour($modInfo);
} }
$banList[] = [ $banList[] = [

View file

@ -4,8 +4,9 @@ namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_USERS_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_USERS_MANAGE))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$roles = $msz->getRoles(); $users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$pagination = new Pagination($users->countUsers(), 30); $pagination = new Pagination($users->countUsers(), 30);
if(!$pagination->hasValidOffset()) if(!$pagination->hasValidOffset())

View file

@ -12,14 +12,14 @@ $hasUserId = filter_has_var(INPUT_GET, 'u');
if((!$hasNoteId && !$hasUserId) || ($hasNoteId && $hasUserId)) if((!$hasNoteId && !$hasUserId) || ($hasNoteId && $hasUserId))
Template::throwError(400); Template::throwError(400);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$modNotes = $msz->getModNotes(); $modNotes = $usersCtx->getModNotes();
if($hasUserId) { if($hasUserId) {
$isNew = true; $isNew = true;
try { try {
$userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id'); $userInfo = $usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT));
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
Template::throwError(404); Template::throwError(404);
} }
@ -44,8 +44,8 @@ if($hasUserId) {
return; return;
} }
$userInfo = $users->getUser($noteInfo->getUserId(), 'id'); $userInfo = $usersCtx->getUserInfo($noteInfo->getUserId());
$authorInfo = $noteInfo->hasAuthorId() ? $users->getUser($noteInfo->getAuthorId(), 'id') : null; $authorInfo = $noteInfo->hasAuthorId() ? $usersCtx->getUserInfo($noteInfo->getAuthorId()) : null;
} }
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) { while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
@ -78,7 +78,7 @@ Template::render('manage.users.note', [
'note_new' => $isNew, 'note_new' => $isNew,
'note_info' => $noteInfo ?? null, 'note_info' => $noteInfo ?? null,
'note_user' => $userInfo, 'note_user' => $userInfo,
'note_user_colour' => $users->getUserColour($userInfo), 'note_user_colour' => $usersCtx->getUserColour($userInfo),
'note_author' => $authorInfo, 'note_author' => $authorInfo,
'note_author_colour' => $users->getUserColour($authorInfo), 'note_author_colour' => $usersCtx->getUserColour($authorInfo),
]); ]);

View file

@ -6,28 +6,19 @@ use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_NOTES_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_NOTES_MANAGE))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$modNotes = $usersCtx->getModNotes();
$userInfos = [
$msz->getActiveUser()->getId() => $msz->getActiveUser(),
];
$userColours = [
$msz->getActiveUser()->getId() => $users->getUserColour($msz->getActiveUser()),
];
$filterUser = null; $filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) { if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT); $filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try { try {
$filterUser = $users->getUser($filterUserId, 'id'); $filterUser = $usersCtx->getUserInfo($filterUserId);
$userInfos[$filterUserId] = $filterUser;
$userColours[$filterUserId] = $users->getUserColour($filterUser);
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
Template::throwError(404); Template::throwError(404);
} }
} }
$modNotes = $msz->getModNotes();
$pagination = new Pagination($modNotes->countNotes(userInfo: $filterUser), 10); $pagination = new Pagination($modNotes->countNotes(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset()) if(!$pagination->hasValidOffset())
@ -37,29 +28,15 @@ $notes = [];
$noteInfos = $modNotes->getNotes(userInfo: $filterUser, pagination: $pagination); $noteInfos = $modNotes->getNotes(userInfo: $filterUser, pagination: $pagination);
foreach($noteInfos as $noteInfo) { foreach($noteInfos as $noteInfo) {
if(array_key_exists($noteInfo->getUserId(), $userInfos)) $userInfo = $usersCtx->getUserInfo($noteInfo->getUserId());
$userInfo = $userInfos[$noteInfo->getUserId()]; $userColour = $usersCtx->getUserColour($userInfo);
else
$userInfos[$noteInfo->getUserId()] = $userInfo = $users->getUser($noteInfo->getUserId(), 'id');
if(array_key_exists($userInfo->getId(), $userColours))
$userColour = $userColours[$userInfo->getId()];
else
$userColours[$userInfo->getId()] = $userColour = $users->getUserColour($userInfo);
if(!$noteInfo->hasAuthorId()) { if(!$noteInfo->hasAuthorId()) {
$authorInfo = null; $authorInfo = null;
$authorColour = null; $authorColour = null;
} else { } else {
if(array_key_exists($noteInfo->getAuthorId(), $userInfos)) $authorInfo = $usersCtx->getUserInfo($noteInfo->getAuthorId());
$authorInfo = $userInfos[$noteInfo->getAuthorId()]; $authorColour = $usersCtx->getUserColour($authorInfo);
else
$userInfos[$noteInfo->getAuthorId()] = $modInfo = $users->getUser($noteInfo->getAuthorId(), 'id');
if(array_key_exists($authorInfo->getId(), $userColours))
$authorColour = $userColours[$authorInfo->getId()];
else
$userColours[$authorInfo->getId()] = $authorColour = $users->getUserColour($authorInfo);
} }
$notes[] = [ $notes[] = [

View file

@ -10,8 +10,9 @@ $viewerPerms = $msz->getAuthInfo()->getPerms('user');
if(!$viewerPerms->check(Perm::U_ROLES_MANAGE)) if(!$viewerPerms->check(Perm::U_ROLES_MANAGE))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$roles = $msz->getRoles(); $users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$perms = $msz->getPerms(); $perms = $msz->getPerms();
if(filter_has_var(INPUT_GET, 'r')) { if(filter_has_var(INPUT_GET, 'r')) {

View file

@ -4,7 +4,7 @@ namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_ROLES_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_ROLES_MANAGE))
Template::throwError(403); Template::throwError(403);
$roles = $msz->getRoles(); $roles = $msz->getUsersContext()->getRoles();
$pagination = new Pagination($roles->countRoles(), 10); $pagination = new Pagination($roles->countRoles(), 10);
if(!$pagination->hasValidOffset()) if(!$pagination->hasValidOffset())

View file

@ -11,8 +11,9 @@ $viewerPerms = $msz->getAuthInfo()->getPerms('user');
if(!$msz->isLoggedIn()) if(!$msz->isLoggedIn())
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$roles = $msz->getRoles(); $users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$perms = $msz->getPerms(); $perms = $msz->getPerms();
$currentUser = $msz->getActiveUser(); $currentUser = $msz->getActiveUser();

View file

@ -6,7 +6,9 @@ use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_WARNINGS_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
Template::throwError(403); Template::throwError(403);
$warns = $msz->getWarnings(); $usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$warns = $usersCtx->getWarnings();
if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) { if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
if(!CSRF::validateRequest()) if(!CSRF::validateRequest())
@ -24,8 +26,6 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete'))
return; return;
} }
$users = $msz->getUsers();
try { try {
$userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id'); $userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {

View file

@ -6,28 +6,19 @@ use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_WARNINGS_MANAGE)) if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
Template::throwError(403); Template::throwError(403);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$warns = $usersCtx->getWarnings();
$userInfos = [
$msz->getActiveUser()->getId() => $msz->getActiveUser(),
];
$userColours = [
$msz->getActiveUser()->getId() => $users->getUserColour($msz->getActiveUser()),
];
$filterUser = null; $filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) { if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT); $filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try { try {
$filterUser = $users->getUser($filterUserId, 'id'); $filterUser = $usersCtx->getUserInfo($filterUserId);
$userInfos[$filterUserId] = $filterUser;
$userColours[$filterUserId] = $users->getUserColour($filterUser);
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
Template::throwError(404); Template::throwError(404);
} }
} }
$warns = $msz->getWarnings();
$pagination = new Pagination($warns->countWarnings(userInfo: $filterUser), 10); $pagination = new Pagination($warns->countWarnings(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset()) if(!$pagination->hasValidOffset())
@ -37,29 +28,15 @@ $warnList = [];
$warnInfos = $warns->getWarnings(userInfo: $filterUser, pagination: $pagination); $warnInfos = $warns->getWarnings(userInfo: $filterUser, pagination: $pagination);
foreach($warnInfos as $warnInfo) { foreach($warnInfos as $warnInfo) {
if(array_key_exists($warnInfo->getUserId(), $userInfos)) $userInfo = $usersCtx->getUserInfo($warnInfo->getUserId());
$userInfo = $userInfos[$warnInfo->getUserId()]; $userColour = $usersCtx->getUserColour($userInfo);
else
$userInfos[$warnInfo->getUserId()] = $userInfo = $users->getUser($warnInfo->getUserId(), 'id');
if(array_key_exists($userInfo->getId(), $userColours))
$userColour = $userColours[$userInfo->getId()];
else
$userColours[$userInfo->getId()] = $userColour = $users->getUserColour($userInfo);
if(!$warnInfo->hasModId()) { if(!$warnInfo->hasModId()) {
$modInfo = null; $modInfo = null;
$modColour = null; $modColour = null;
} else { } else {
if(array_key_exists($warnInfo->getModId(), $userInfos)) $modInfo = $usersCtx->getUserInfo($warnInfo->getModId());
$modInfo = $userInfos[$warnInfo->getModId()]; $modColour = $usersCtx->getUserColour($modInfo);
else
$userInfos[$warnInfo->getModId()] = $modInfo = $users->getUser($warnInfo->getModId(), 'id');
if(array_key_exists($modInfo->getId(), $userColours))
$modColour = $userColours[$modInfo->getId()];
else
$userColours[$modInfo->getId()] = $modColour = $users->getUserColour($modInfo);
} }
$warnList[] = [ $warnList[] = [

View file

@ -8,9 +8,10 @@ if(!$msz->isLoggedIn())
// TODO: restore forum-topics and forum-posts orderings // TODO: restore forum-topics and forum-posts orderings
$users = $msz->getUsers();
$roles = $msz->getRoles();
$forum = $msz->getForum(); $forum = $msz->getForum();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$roleId = filter_has_var(INPUT_GET, 'r') ? (string)filter_input(INPUT_GET, 'r') : null; $roleId = filter_has_var(INPUT_GET, 'r') ? (string)filter_input(INPUT_GET, 'r') : null;
$orderBy = strtolower((string)filter_input(INPUT_GET, 'ss')); $orderBy = strtolower((string)filter_input(INPUT_GET, 'ss'));
@ -91,7 +92,7 @@ $userInfos = $users->getUsers(
foreach($userInfos as $userInfo) foreach($userInfos as $userInfo)
$userList[] = [ $userList[] = [
'info' => $userInfo, 'info' => $userInfo,
'colour' => $users->getUserColour($userInfo), 'colour' => $usersCtx->getUserColour($userInfo),
'ftopics' => $forum->countTopics(userInfo: $userInfo, deleted: false), 'ftopics' => $forum->countTopics(userInfo: $userInfo, deleted: false),
'fposts' => $forum->countPosts(userInfo: $userInfo, deleted: false), 'fposts' => $forum->countPosts(userInfo: $userInfo, deleted: false),
]; ];

View file

@ -15,7 +15,8 @@ $userId = !empty($_GET['u']) && is_string($_GET['u']) ? trim($_GET['u']) : 0;
$profileMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : ''; $profileMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
$isEditing = !empty($_GET['edit']) && is_string($_GET['edit']) ? (bool)$_GET['edit'] : !empty($_POST) && is_array($_POST); $isEditing = !empty($_GET['edit']) && is_string($_GET['edit']) ? (bool)$_GET['edit'] : !empty($_POST) && is_array($_POST);
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$forum = $msz->getForum(); $forum = $msz->getForum();
$viewerInfo = $msz->getActiveUser(); $viewerInfo = $msz->getActiveUser();
@ -23,7 +24,7 @@ $viewingAsGuest = $viewerInfo === null;
$viewerId = $viewingAsGuest ? '0' : $viewerInfo->getId(); $viewerId = $viewingAsGuest ? '0' : $viewerInfo->getId();
try { try {
$userInfo = $users->getUser($userId, 'profile'); $userInfo = $usersCtx->getUserInfo($userId, 'profile');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
http_response_code(404); http_response_code(404);
Template::render('profile.index', [ Template::render('profile.index', [
@ -62,8 +63,8 @@ switch($profileMode) {
$notices = []; $notices = [];
$userRank = $users->getUserRank($userInfo); $userRank = $usersCtx->getUserRank($userInfo);
$viewerRank = $viewingAsGuest ? 0 : $users->getUserRank($viewerInfo); $viewerRank = $usersCtx->getUserRank($viewerInfo);
$viewerPerms = $msz->getAuthInfo()->getPerms('user'); $viewerPerms = $msz->getAuthInfo()->getPerms('user');
@ -292,7 +293,7 @@ $profileStats->forum_post_count = $forum->countPosts(userInfo: $userInfo, delete
$profileStats->comments_count = $msz->getComments()->countPosts(userInfo: $userInfo, deleted: false); $profileStats->comments_count = $msz->getComments()->countPosts(userInfo: $userInfo, deleted: false);
if(!$viewingAsGuest) { if(!$viewingAsGuest) {
Template::set('profile_warnings', $msz->getWarnings()->getWarningsWithDefaultBacklog($userInfo)); Template::set('profile_warnings', $usersCtx->getWarnings()->getWarningsWithDefaultBacklog($userInfo));
if((!$isBanned || $canEdit)) { if((!$isBanned || $canEdit)) {
$unranked = $cfg->getValues([ $unranked = $cfg->getValues([
@ -366,7 +367,7 @@ if(!$viewingAsGuest) {
Template::render('profile.index', [ Template::render('profile.index', [
'profile_viewer' => $viewerInfo, 'profile_viewer' => $viewerInfo,
'profile_user' => $userInfo, 'profile_user' => $userInfo,
'profile_colour' => $users->getUserColour($userInfo), 'profile_colour' => $usersCtx->getUserColour($userInfo),
'profile_stats' => $profileStats, 'profile_stats' => $profileStats,
'profile_mode' => $profileMode, 'profile_mode' => $profileMode,
'profile_notices' => $notices, 'profile_notices' => $notices,

View file

@ -38,14 +38,12 @@ Template::addFunction('search_merge_query', function($attrs) use (&$searchQueryE
return rawurlencode(implode(' ', $existing)); return rawurlencode(implode(' ', $existing));
}); });
if(!empty($searchQuery)) { if(!empty($searchQuery)) {
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$forum = $msz->getForum(); $forum = $msz->getForum();
$news = $msz->getNews(); $news = $msz->getNews();
$comments = $msz->getComments(); $comments = $msz->getComments();
$userInfos = [];
$userColours = [];
$searchQueryAttributes = ['type', 'author', 'after']; $searchQueryAttributes = ['type', 'author', 'after'];
$searchQueryParts = explode(' ', $searchQuery); $searchQueryParts = explode(' ', $searchQuery);
foreach($searchQueryParts as $queryPart) { foreach($searchQueryParts as $queryPart) {
@ -70,7 +68,7 @@ if(!empty($searchQuery)) {
if(!empty($searchQueryEvaluated['author'])) if(!empty($searchQueryEvaluated['author']))
try { try {
$searchQueryEvaluated['author'] = $users->getUser($searchQueryEvaluated['author'], 'search'); $searchQueryEvaluated['author'] = $usersCtx->getUserInfo($searchQueryEvaluated['author'], 'search');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
unset($searchQueryEvaluated['author']); unset($searchQueryEvaluated['author']);
} }
@ -95,15 +93,8 @@ if(!empty($searchQuery)) {
$topic->lastPost = new stdClass; $topic->lastPost = new stdClass;
if($topicInfo->hasUserId()) { if($topicInfo->hasUserId()) {
$lastTopicUserId = $topicInfo->getUserId(); $topic->user = $usersCtx->getUserInfo($topicInfo->getUserId(), 'id');
if(!array_key_exists($lastTopicUserId, $userInfos)) { $topic->colour = $usersCtx->getUserColour($topic->user);
$userInfo = $users->getUser($lastTopicUserId, 'id');
$userInfos[$lastTopicUserId] = $userInfo;
$userColours[$lastTopicUserId] = $users->getUserColour($userInfo);
}
$topic->user = $userInfos[$lastTopicUserId];
$topic->colour = $userColours[$lastTopicUserId];
} }
try { try {
@ -114,15 +105,8 @@ if(!empty($searchQuery)) {
); );
if($lastPostInfo->hasUserId()) { if($lastPostInfo->hasUserId()) {
$lastPostUserId = $lastPostInfo->getUserId(); $topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId(), 'id');
if(!array_key_exists($lastPostUserId, $userInfos)) { $topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
$userInfo = $users->getUser($lastPostUserId, 'id');
$userInfos[$lastPostUserId] = $userInfo;
$userColours[$lastPostUserId] = $users->getUserColour($userInfo);
}
$topic->lastPost->user = $userInfos[$lastPostUserId];
$topic->lastPost->colour = $userColours[$lastPostUserId];
} }
} catch(RuntimeException $ex) {} } catch(RuntimeException $ex) {}
} }
@ -135,17 +119,9 @@ if(!empty($searchQuery)) {
$post->info = $postInfo; $post->info = $postInfo;
if($postInfo->hasUserId()) { if($postInfo->hasUserId()) {
$postUserId = $postInfo->getUserId(); $post->user = $usersCtx->getUserInfo($postInfo->getUserId(), 'id');
if(!array_key_exists($postUserId, $userInfos)) { $post->colour = $usersCtx->getUserColour($post->user);
$userInfo = $users->getUser($postUserId, 'id'); $post->postsCount = $forum->countPosts(userInfo: $post->user, deleted: false);
$userInfos[$postUserId] = $userInfo;
$userColours[$postUserId] = $users->getUserColour($userInfo);
$userPostsCounts[$postUserId] = $forum->countPosts(userInfo: $userInfo, deleted: false);
}
$post->user = $userInfos[$postUserId];
$post->colour = $userColours[$postUserId];
$post->postsCount = null;
} }
// can't be bothered sorry // can't be bothered sorry
@ -161,19 +137,8 @@ if(!empty($searchQuery)) {
foreach($newsPostInfos as $postInfo) { foreach($newsPostInfos as $postInfo) {
$userId = $postInfo->getUserId(); $userId = $postInfo->getUserId();
$categoryId = $postInfo->getCategoryId(); $categoryId = $postInfo->getCategoryId();
$userInfo = $postInfo->hasUserId() ? $usersCtx->getUserInfo($postInfo->getUserId()) : null;
if(array_key_exists($userId, $userInfos)) { $userColour = $usersCtx->getUserColour($userInfo);
$userInfo = $userInfos[$userId];
} else {
try {
$userInfo = $users->getUser($userId, 'id');
$userColours[$userId] = $users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
}
$userInfos[$userId] = $userInfo;
}
if(array_key_exists($categoryId, $newsCategoryInfos)) if(array_key_exists($categoryId, $newsCategoryInfos))
$categoryInfo = $newsCategoryInfos[$categoryId]; $categoryInfo = $newsCategoryInfos[$categoryId];
@ -187,7 +152,7 @@ if(!empty($searchQuery)) {
'post' => $postInfo, 'post' => $postInfo,
'category' => $categoryInfo, 'category' => $categoryInfo,
'user' => $userInfo, 'user' => $userInfo,
'user_colour' => $userColours[$userId] ?? \Index\Colour\Colour::none(), 'user_colour' => $userColour,
'comments_count' => $commentsCount, 'comments_count' => $commentsCount,
]; ];
} }
@ -198,12 +163,7 @@ if(!empty($searchQuery)) {
foreach($memberInfos as $memberInfo) { foreach($memberInfos as $memberInfo) {
$members[] = $member = new stdClass; $members[] = $member = new stdClass;
$member->info = $memberInfo; $member->info = $memberInfo;
$member->colour = $usersCtx->getUserColour($memberInfo);
$memberId = $memberInfo->getId();
if(!array_key_exists($memberId, $userColours))
$userColours[$memberId] = $users->getUserColour($memberId);
$member->colour = $userColours[$memberId];
$member->ftopics = $forum->countTopics(userInfo: $memberInfo, deleted: false); $member->ftopics = $forum->countTopics(userInfo: $memberInfo, deleted: false);
$member->fposts = $forum->countPosts(userInfo: $memberInfo, deleted: false); $member->fposts = $forum->countPosts(userInfo: $memberInfo, deleted: false);
} }

View file

@ -10,8 +10,9 @@ if(!$msz->isLoggedIn())
Template::throwError(401); Template::throwError(401);
$errors = []; $errors = [];
$users = $msz->getUsers(); $usersCtx = $msz->getUsersContext();
$roles = $msz->getRoles(); $users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$userInfo = $msz->getActiveUser(); $userInfo = $msz->getActiveUser();
$isRestricted = $msz->hasActiveBan(); $isRestricted = $msz->hasActiveBan();
$isVerifiedRequest = CSRF::validateRequest(); $isVerifiedRequest = CSRF::validateRequest();

View file

@ -57,7 +57,7 @@ $sessionInfo = null;
$userInfoReal = null; $userInfoReal = null;
if($tokenInfo->hasUserId() && $tokenInfo->hasSessionToken()) { if($tokenInfo->hasUserId() && $tokenInfo->hasSessionToken()) {
$users = $msz->getUsers(); $users = $msz->getUsersContext()->getUsers();
$sessions = $msz->getSessions(); $sessions = $msz->getSessions();
$tokenBuilder = new AuthTokenBuilder($tokenInfo); $tokenBuilder = new AuthTokenBuilder($tokenInfo);

View file

@ -25,6 +25,10 @@ class ChangeInfo {
return $this->id; return $this->id;
} }
public function hasUserId(): bool {
return $this->userId !== null;
}
public function getUserId(): ?string { public function getUserId(): ?string {
return $this->userId; return $this->userId;
} }

View file

@ -15,31 +15,16 @@ use Misuzu\Feeds\Feed;
use Misuzu\Feeds\FeedItem; use Misuzu\Feeds\FeedItem;
use Misuzu\Feeds\AtomFeedSerializer; use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer; use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
final class ChangelogRoutes implements IRouteHandler { final class ChangelogRoutes implements IRouteHandler {
private IConfig $config;
private Changelog $changelog;
private Users $users;
private AuthInfo $authInfo;
private Comments $comments;
private array $userInfos = [];
private array $userColours = [];
public function __construct( public function __construct(
IConfig $config, private IConfig $config,
Changelog $changelog, private Changelog $changelog,
Users $users, private UsersContext $usersCtx,
AuthInfo $authInfo, private AuthInfo $authInfo,
Comments $comments private Comments $comments
) { ) {}
$this->config = $config;
$this->changelog = $changelog;
$this->users = $users;
$this->authInfo = $authInfo;
$this->comments = $comments;
}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
$router->get('/changelog', $this->getIndex(...)); $router->get('/changelog', $this->getIndex(...));
@ -62,7 +47,7 @@ final class ChangelogRoutes implements IRouteHandler {
} }
private function getCommentsInfo(string $categoryName): object { private function getCommentsInfo(string $categoryName): object {
$comments = new CommentsEx($this->authInfo, $this->comments, $this->users, $this->userInfos, $this->userColours); $comments = new CommentsEx($this->authInfo, $this->comments, $this->usersCtx);
return $comments->getCommentsForLayout($categoryName); return $comments->getCommentsForLayout($categoryName);
} }
@ -85,7 +70,7 @@ final class ChangelogRoutes implements IRouteHandler {
$filterUser = null; $filterUser = null;
else else
try { try {
$filterUser = $this->users->getUser($filterUser, 'id'); $filterUser = $this->usersCtx->getUserInfo($filterUser);
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
return 404; return 404;
} }
@ -110,28 +95,12 @@ final class ChangelogRoutes implements IRouteHandler {
$changes = []; $changes = [];
foreach($changeInfos as $changeInfo) { foreach($changeInfos as $changeInfo) {
$userId = $changeInfo->getUserId(); $userInfo = $changeInfo->hasUserId() ? $this->usersCtx->getUserInfo($changeInfo->getUserId()) : null;
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
$userColour = $this->userColours[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
$userColour = null;
}
$this->userInfos[$userId] = $userInfo;
$this->userColours[$userId] = $userColour;
}
$changes[] = [ $changes[] = [
'change' => $changeInfo, 'change' => $changeInfo,
'user' => $userInfo, 'user' => $userInfo,
'user_colour' => $userColour, 'user_colour' => $this->usersCtx->getUserColour($userInfo),
]; ];
} }
@ -153,20 +122,13 @@ final class ChangelogRoutes implements IRouteHandler {
} }
$tagInfos = $this->changelog->getTags(changeInfo: $changeInfo); $tagInfos = $this->changelog->getTags(changeInfo: $changeInfo);
$userInfo = $changeInfo->hasUserId() ? $this->usersCtx->getUserInfo($changeInfo->getUserId()) : null;
try {
$userInfo = $this->users->getUser($changeInfo->getUserId(), 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
$userColour = null;
}
return Template::renderRaw('changelog.change', [ return Template::renderRaw('changelog.change', [
'change_info' => $changeInfo, 'change_info' => $changeInfo,
'change_tags' => $tagInfos, 'change_tags' => $tagInfos,
'change_user_info' => $userInfo, 'change_user_info' => $userInfo,
'change_user_colour' => $userColour, 'change_user_colour' => $this->usersCtx->getUserColour($userInfo),
'comments_info' => $this->getCommentsInfo($changeInfo->getCommentsCategoryName()), 'comments_info' => $this->getCommentsInfo($changeInfo->getCommentsCategoryName()),
]); ]);
} }

View file

@ -6,15 +6,13 @@ use RuntimeException;
use Misuzu\MisuzuContext; use Misuzu\MisuzuContext;
use Misuzu\Perm; use Misuzu\Perm;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
class CommentsEx { class CommentsEx {
public function __construct( public function __construct(
private AuthInfo $authInfo, private AuthInfo $authInfo,
private Comments $comments, private Comments $comments,
private Users $users, private UsersContext $usersCtx
private array $userInfos = [],
private array $userColours = []
) {} ) {}
public function getCommentsForLayout(CommentsCategoryInfo|string $category): object { public function getCommentsForLayout(CommentsCategoryInfo|string $category): object {
@ -24,7 +22,7 @@ class CommentsEx {
$hasUser = $this->authInfo->isLoggedIn(); $hasUser = $this->authInfo->isLoggedIn();
$info->user = $hasUser ? $this->authInfo->getUserInfo() : null; $info->user = $hasUser ? $this->authInfo->getUserInfo() : null;
$info->colour = $hasUser ? $this->users->getUserColour($info->user) : null; $info->colour = $this->usersCtx->getUserColour($info->user);
$info->perms = $this->authInfo->getPerms('global')->checkMany([ $info->perms = $this->authInfo->getPerms('global')->checkMany([
'can_post' => Perm::G_COMMENTS_CREATE, 'can_post' => Perm::G_COMMENTS_CREATE,
'can_delete' => Perm::G_COMMENTS_DELETE_OWN | Perm::G_COMMENTS_DELETE_ANY, 'can_delete' => Perm::G_COMMENTS_DELETE_OWN | Perm::G_COMMENTS_DELETE_ANY,
@ -44,32 +42,12 @@ class CommentsEx {
} }
public function decorateComment(CommentsPostInfo $postInfo): object { public function decorateComment(CommentsPostInfo $postInfo): object {
if($postInfo->hasUserId()) { $userInfo = $postInfo->hasUserId() ? $this->usersCtx->getUserInfo($postInfo->getUserId()) : null;
$userId = $postInfo->getUserId();
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
$userColour = $this->userColours[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
$userColour = null;
}
$this->userInfos[$userId] = $userInfo;
$this->userColours[$userId] = $userColour;
}
} else {
$userInfo = null;
$userColour = null;
}
$info = new stdClass; $info = new stdClass;
$info->post = $postInfo; $info->post = $postInfo;
$info->user = $userInfo; $info->user = $userInfo;
$info->colour = $userColour; $info->colour = $this->usersCtx->getUserColour($userInfo);
$info->vote = $this->comments->getPostVote($postInfo, $userInfo); $info->vote = $this->comments->getPostVote($postInfo, $userInfo);
$info->replies = []; $info->replies = [];

View file

@ -15,37 +15,19 @@ use Misuzu\Comments\Comments;
use Misuzu\Config\IConfig; use Misuzu\Config\IConfig;
use Misuzu\Counters\Counters; use Misuzu\Counters\Counters;
use Misuzu\News\News; use Misuzu\News\News;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
class HomeRoutes implements IRouteHandler { class HomeRoutes implements IRouteHandler {
private IConfig $config;
private IDbConnection $dbConn;
private AuthInfo $authInfo;
private Changelog $changelog;
private Comments $comments;
private Counters $counters;
private News $news;
private Users $users;
public function __construct( public function __construct(
IConfig $config, private IConfig $config,
IDbConnection $dbConn, private IDbConnection $dbConn,
AuthInfo $authInfo, private AuthInfo $authInfo,
Changelog $changelog, private Changelog $changelog,
Comments $comments, private Comments $comments,
Counters $counters, private Counters $counters,
News $news, private News $news,
Users $users private UsersContext $usersCtx
) { ) {}
$this->config = $config;
$this->dbConn = $dbConn;
$this->authInfo = $authInfo;
$this->changelog = $changelog;
$this->comments = $comments;
$this->counters = $counters;
$this->news = $news;
$this->users = $users;
}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
$router->get('/', $this->getIndex(...)); $router->get('/', $this->getIndex(...));
@ -70,15 +52,13 @@ class HomeRoutes implements IRouteHandler {
} }
private function getOnlineUsers(): array { private function getOnlineUsers(): array {
return $this->users->getUsers( return $this->usersCtx->getUsers()->getUsers(
lastActiveInMinutes: 5, lastActiveInMinutes: 5,
deleted: false, deleted: false,
orderBy: 'random', orderBy: 'random',
); );
} }
private array $userInfos = [];
private array $userColours = [];
private array $newsCategoryInfos = []; private array $newsCategoryInfos = [];
private function getFeaturedNewsPosts(int $amount, bool $decorate): array { private function getFeaturedNewsPosts(int $amount, bool $decorate): array {
@ -93,24 +73,8 @@ class HomeRoutes implements IRouteHandler {
$posts = []; $posts = [];
foreach($postInfos as $postInfo) { foreach($postInfos as $postInfo) {
$userId = $postInfo->getUserId();
$categoryId = $postInfo->getCategoryId(); $categoryId = $postInfo->getCategoryId();
$userInfo = $postInfo->hasUserId() ? $this->usersCtx->getUserInfo($postInfo->getUserId()) : null;
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
$userColour = $this->userColours[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
$userColour = null;
}
$this->userInfos[$userId] = $userInfo;
$this->userColours[$userId] = $userColour;
}
if(array_key_exists($categoryId, $this->newsCategoryInfos)) if(array_key_exists($categoryId, $this->newsCategoryInfos))
$categoryInfo = $this->newsCategoryInfos[$categoryId]; $categoryInfo = $this->newsCategoryInfos[$categoryId];
@ -124,7 +88,7 @@ class HomeRoutes implements IRouteHandler {
'post' => $postInfo, 'post' => $postInfo,
'category' => $categoryInfo, 'category' => $categoryInfo,
'user' => $userInfo, 'user' => $userInfo,
'user_colour' => $userColour, 'user_colour' => $this->usersCtx->getUserColour($userInfo),
'comments_count' => $commentsCount, 'comments_count' => $commentsCount,
]; ];
} }
@ -213,11 +177,11 @@ class HomeRoutes implements IRouteHandler {
$stats['users:online:recent'] = count($onlineUserInfos); $stats['users:online:recent'] = count($onlineUserInfos);
$birthdays = []; $birthdays = [];
$birthdayInfos = $this->users->getUsers(deleted: false, birthdate: DateTime::now(), orderBy: 'random'); $birthdayInfos = $this->usersCtx->getUsers()->getUsers(deleted: false, birthdate: DateTime::now(), orderBy: 'random');
foreach($birthdayInfos as $birthdayInfo) foreach($birthdayInfos as $birthdayInfo)
$birthdays[] = [ $birthdays[] = [
'info' => $birthdayInfo, 'info' => $birthdayInfo,
'colour' => $this->users->getUserColour($birthdayInfo), 'colour' => $this->usersCtx->getUserColour($birthdayInfo),
]; ];
$newestMember = []; $newestMember = [];
@ -225,10 +189,8 @@ class HomeRoutes implements IRouteHandler {
$newestMemberId = $this->config->getString('users.newest'); $newestMemberId = $this->config->getString('users.newest');
if(!empty($newestMemberId)) if(!empty($newestMemberId))
try { try {
$newestMemberInfo = $this->users->getUser($newestMemberId, 'id'); $newestMember['info'] = $this->usersCtx->getUserInfo($newestMemberId);
$newestMemberColour = $this->users->getUserColour($newestMemberInfo); $newestMember['colour'] = $this->usersCtx->getUserColour($newestMemberId);
$newestMember['info'] = $newestMemberInfo;
$newestMember['colour'] = $newestMemberColour;
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
$newestMember = []; $newestMember = [];
$this->config->removeValues('users.newest'); $this->config->removeValues('users.newest');

View file

@ -32,13 +32,9 @@ use Misuzu\Perms\Permissions;
use Misuzu\Profile\ProfileFields; use Misuzu\Profile\ProfileFields;
use Misuzu\Satori\SatoriRoutes; use Misuzu\Satori\SatoriRoutes;
use Misuzu\SharpChat\SharpChatRoutes; use Misuzu\SharpChat\SharpChatRoutes;
use Misuzu\Users\Bans; use Misuzu\Users\UsersContext;
use Misuzu\Users\BanInfo; use Misuzu\Users\BanInfo;
use Misuzu\Users\ModNotes;
use Misuzu\Users\Roles;
use Misuzu\Users\Users;
use Misuzu\Users\UserInfo; use Misuzu\Users\UserInfo;
use Misuzu\Users\Warnings;
use Misuzu\Users\Assets\AssetsRoutes; use Misuzu\Users\Assets\AssetsRoutes;
// this class should function as the root for everything going forward // this class should function as the root for everything going forward
@ -51,49 +47,51 @@ class MisuzuContext {
private IDbConnection $dbConn; private IDbConnection $dbConn;
private IConfig $config; private IConfig $config;
private HttpFx $router; private HttpFx $router;
private SasaeEnvironment $templating;
private AuditLog $auditLog; private AuditLog $auditLog;
private Counters $counters;
private Emotes $emotes; private Emotes $emotes;
private Changelog $changelog; private Changelog $changelog;
private News $news; private News $news;
private Comments $comments; private Comments $comments;
private Sessions $sessions;
private LoginAttempts $loginAttempts; private LoginAttempts $loginAttempts;
private RecoveryTokens $recoveryTokens; private RecoveryTokens $recoveryTokens;
private ModNotes $modNotes;
private Bans $bans;
private Warnings $warnings;
private TwoFactorAuthSessions $tfaSessions; private TwoFactorAuthSessions $tfaSessions;
private Roles $roles;
private Users $users; private UsersContext $usersCtx;
private Sessions $sessions;
private Counters $counters;
private ProfileFields $profileFields; private ProfileFields $profileFields;
private Forum $forum; private Forum $forum;
private Permissions $perms; private Permissions $perms;
private AuthInfo $authInfo; private AuthInfo $authInfo;
private SasaeEnvironment $templating;
public function __construct(IDbConnection $dbConn, IConfig $config) { public function __construct(IDbConnection $dbConn, IConfig $config) {
$this->dbConn = $dbConn; $this->dbConn = $dbConn;
$this->config = $config; $this->config = $config;
$this->usersCtx = new UsersContext($this->dbConn);
$this->perms = new Permissions($this->dbConn); $this->perms = new Permissions($this->dbConn);
$this->authInfo = new AuthInfo($this->perms); $this->authInfo = new AuthInfo($this->perms);
$this->auditLog = new AuditLog($this->dbConn); $this->auditLog = new AuditLog($this->dbConn);
$this->bans = new Bans($this->dbConn);
$this->changelog = new Changelog($this->dbConn); $this->changelog = new Changelog($this->dbConn);
$this->comments = new Comments($this->dbConn); $this->comments = new Comments($this->dbConn);
$this->counters = new Counters($this->dbConn); $this->counters = new Counters($this->dbConn);
$this->emotes = new Emotes($this->dbConn); $this->emotes = new Emotes($this->dbConn);
$this->forum = new Forum($this->dbConn); $this->forum = new Forum($this->dbConn);
$this->loginAttempts = new LoginAttempts($this->dbConn); $this->loginAttempts = new LoginAttempts($this->dbConn);
$this->modNotes = new ModNotes($this->dbConn);
$this->news = new News($this->dbConn); $this->news = new News($this->dbConn);
$this->profileFields = new ProfileFields($this->dbConn); $this->profileFields = new ProfileFields($this->dbConn);
$this->recoveryTokens = new RecoveryTokens($this->dbConn); $this->recoveryTokens = new RecoveryTokens($this->dbConn);
$this->roles = new Roles($this->dbConn);
$this->sessions = new Sessions($this->dbConn); $this->sessions = new Sessions($this->dbConn);
$this->tfaSessions = new TwoFactorAuthSessions($this->dbConn); $this->tfaSessions = new TwoFactorAuthSessions($this->dbConn);
$this->users = new Users($this->dbConn);
$this->warnings = new Warnings($this->dbConn);
} }
public function getDbConn(): IDbConnection { public function getDbConn(): IDbConnection {
@ -149,30 +147,10 @@ class MisuzuContext {
return $this->recoveryTokens; return $this->recoveryTokens;
} }
public function getModNotes(): ModNotes {
return $this->modNotes;
}
public function getBans(): Bans {
return $this->bans;
}
public function getWarnings(): Warnings {
return $this->warnings;
}
public function getTFASessions(): TwoFactorAuthSessions { public function getTFASessions(): TwoFactorAuthSessions {
return $this->tfaSessions; return $this->tfaSessions;
} }
public function getRoles(): Roles {
return $this->roles;
}
public function getUsers(): Users {
return $this->users;
}
public function getSessions(): Sessions { public function getSessions(): Sessions {
return $this->sessions; return $this->sessions;
} }
@ -193,6 +171,10 @@ class MisuzuContext {
return $this->perms; return $this->perms;
} }
public function getUsersContext(): UsersContext {
return $this->usersCtx;
}
public function createAuthTokenPacker(): AuthTokenPacker { public function createAuthTokenPacker(): AuthTokenPacker {
return new AuthTokenPacker($this->config->getString('auth.secret', 'meow')); return new AuthTokenPacker($this->config->getString('auth.secret', 'meow'));
} }
@ -210,8 +192,6 @@ class MisuzuContext {
return $this->authInfo->getUserInfo(); return $this->authInfo->getUserInfo();
} }
private array $activeBansCache = [];
public function tryGetActiveBan(UserInfo|string|null $userInfo = null): ?BanInfo { public function tryGetActiveBan(UserInfo|string|null $userInfo = null): ?BanInfo {
if($userInfo === null) { if($userInfo === null) {
if($this->isLoggedIn()) if($this->isLoggedIn())
@ -219,11 +199,7 @@ class MisuzuContext {
else return null; else return null;
} }
$userId = (string)$userInfo->getId(); return $this->usersCtx->tryGetActiveBan($userInfo);
if(!array_key_exists($userId, $this->activeBansCache))
$this->activeBansCache[$userId] = $this->bans->tryGetActiveBan($userId);
return $this->activeBansCache[$userId];
} }
public function hasActiveBan(UserInfo|string|null $userInfo = null): bool { public function hasActiveBan(UserInfo|string|null $userInfo = null): bool {
@ -321,35 +297,54 @@ class MisuzuContext {
private function registerHttpRoutes(): void { private function registerHttpRoutes(): void {
$this->router->register(new HomeRoutes( $this->router->register(new HomeRoutes(
$this->config, $this->dbConn, $this->authInfo, $this->config,
$this->changelog, $this->comments, $this->counters, $this->news, $this->dbConn,
$this->users $this->authInfo,
$this->changelog,
$this->comments,
$this->counters,
$this->news,
$this->usersCtx
)); ));
$this->router->register(new AssetsRoutes($this->authInfo, $this->bans, $this->users)); $this->router->register(new AssetsRoutes(
$this->authInfo,
$this->usersCtx
));
$this->router->register(new InfoRoutes); $this->router->register(new InfoRoutes);
$this->router->register(new NewsRoutes( $this->router->register(new NewsRoutes(
$this->config, $this->authInfo, $this->config,
$this->news, $this->users, $this->comments $this->authInfo,
$this->news,
$this->usersCtx,
$this->comments
)); ));
$this->router->register(new ChangelogRoutes( $this->router->register(new ChangelogRoutes(
$this->config, $this->changelog, $this->config,
$this->users, $this->authInfo, $this->comments $this->changelog,
$this->usersCtx,
$this->authInfo,
$this->comments
)); ));
$this->router->register(new SharpChatRoutes( $this->router->register(new SharpChatRoutes(
$this->config->scopeTo('sockChat'), $this->config->scopeTo('sockChat'),
$this->bans, $this->emotes, $this->users, $this->usersCtx,
$this->sessions, $this->perms, $this->authInfo, $this->emotes,
$this->sessions,
$this->perms,
$this->authInfo,
$this->createAuthTokenPacker(...) $this->createAuthTokenPacker(...)
)); ));
$this->router->register(new SatoriRoutes( $this->router->register(new SatoriRoutes(
$this->dbConn, $this->config->scopeTo('satori'), $this->dbConn,
$this->users, $this->profileFields $this->config->scopeTo('satori'),
$this->usersCtx,
$this->profileFields
)); ));
// below is still only otherwise available as stinky php files // below is still only otherwise available as stinky php files

View file

@ -20,29 +20,17 @@ use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer; use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\News\News; use Misuzu\News\News;
use Misuzu\News\NewsCategoryInfo; use Misuzu\News\NewsCategoryInfo;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
use Misuzu\Parsers\Parser; use Misuzu\Parsers\Parser;
class NewsRoutes implements IRouteHandler { class NewsRoutes implements IRouteHandler {
private IConfig $config;
private AuthInfo $authInfo;
private News $news;
private Users $users;
private Comments $comments;
public function __construct( public function __construct(
IConfig $config, private IConfig $config,
AuthInfo $authInfo, private AuthInfo $authInfo,
News $news, private News $news,
Users $users, private UsersContext $usersCtx,
Comments $comments private Comments $comments
) { ) {}
$this->config = $config;
$this->authInfo = $authInfo;
$this->news = $news;
$this->users = $users;
$this->comments = $comments;
}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
$router->get('/news', $this->getIndex(...)); $router->get('/news', $this->getIndex(...));
@ -114,8 +102,6 @@ class NewsRoutes implements IRouteHandler {
}); });
} }
private array $userInfos = [];
private array $userColours = [];
private array $categoryInfos = []; private array $categoryInfos = [];
private function getNewsPostsForView(Pagination $pagination, ?NewsCategoryInfo $categoryInfo = null): array { private function getNewsPostsForView(Pagination $pagination, ?NewsCategoryInfo $categoryInfo = null): array {
@ -127,32 +113,8 @@ class NewsRoutes implements IRouteHandler {
); );
foreach($postInfos as $postInfo) { foreach($postInfos as $postInfo) {
$userId = $postInfo->getUserId();
$categoryId = $postInfo->getCategoryId(); $categoryId = $postInfo->getCategoryId();
$userInfo = $postInfo->hasUserId() ? $this->usersCtx->getUserInfo($postInfo->getUserId()) : null;
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
} catch(RuntimeException $ex) {
$userInfo = null;
}
$this->userInfos[$userId] = $userInfo;
}
if(array_key_exists($userId, $this->userColours)) {
$userColour = $this->userColours[$userId];
} else {
try {
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userColour = null;
}
$this->userColours[$userId] = $userColour;
}
if(array_key_exists($categoryId, $this->categoryInfos)) if(array_key_exists($categoryId, $this->categoryInfos))
$categoryInfo = $this->categoryInfos[$categoryId]; $categoryInfo = $this->categoryInfos[$categoryId];
@ -167,7 +129,7 @@ class NewsRoutes implements IRouteHandler {
'post' => $postInfo, 'post' => $postInfo,
'category' => $categoryInfo, 'category' => $categoryInfo,
'user' => $userInfo, 'user' => $userInfo,
'user_colour' => $userColour, 'user_colour' => $this->usersCtx->getUserColour($userInfo),
'comments_count' => $commentsCount, 'comments_count' => $commentsCount,
]; ];
} }
@ -186,18 +148,7 @@ class NewsRoutes implements IRouteHandler {
foreach($postInfos as $postInfo) { foreach($postInfos as $postInfo) {
$userId = $postInfo->getUserId(); $userId = $postInfo->getUserId();
$categoryId = $postInfo->getCategoryId(); $categoryId = $postInfo->getCategoryId();
$userInfo = $postInfo->hasUserId() ? $this->usersCtx->getUserInfo($postInfo->getUserId()) : null;
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
} catch(RuntimeException $ex) {
$userInfo = null;
}
$this->userInfos[$userId] = $userInfo;
}
$posts[] = [ $posts[] = [
'post' => $postInfo, 'post' => $postInfo,
@ -293,21 +244,14 @@ class NewsRoutes implements IRouteHandler {
$this->news->updatePostCommentCategory($postInfo, $commentsCategory); $this->news->updatePostCommentCategory($postInfo, $commentsCategory);
} }
$userInfo = null; $userInfo = $postInfo->hasUserId() ? $this->usersCtx->getUserInfo($postInfo->getUserId()) : null;
$userColour = null; $comments = new CommentsEx($this->authInfo, $this->comments, $this->usersCtx);
if($postInfo->hasUserId())
try {
$userInfo = $this->users->getUser($postInfo->getUserId(), 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {}
$comments = new CommentsEx($this->authInfo, $this->comments, $this->users);
return Template::renderRaw('news.post', [ return Template::renderRaw('news.post', [
'post_info' => $postInfo, 'post_info' => $postInfo,
'post_category_info' => $categoryInfo, 'post_category_info' => $categoryInfo,
'post_user_info' => $userInfo, 'post_user_info' => $userInfo,
'post_user_colour' => $userColour, 'post_user_colour' => $this->usersCtx->getUserColour($userInfo),
'comments_info' => $comments->getCommentsForLayout($commentsCategory), 'comments_info' => $comments->getCommentsForLayout($commentsCategory),
]); ]);
} }

View file

@ -10,25 +10,15 @@ use Index\Routing\IRouteHandler;
use Misuzu\Pagination; use Misuzu\Pagination;
use Misuzu\Config\IConfig; use Misuzu\Config\IConfig;
use Misuzu\Profile\ProfileFields; use Misuzu\Profile\ProfileFields;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
final class SatoriRoutes implements IRouteHandler { final class SatoriRoutes implements IRouteHandler {
private IDbConnection $dbConn;
private IConfig $config;
private Users $users;
private ProfileFields $profileFields;
public function __construct( public function __construct(
IDbConnection $dbConn, private IDbConnection $dbConn,
IConfig $config, private IConfig $config,
Users $users, private UsersContext $usersCtx,
ProfileFields $profileFields private ProfileFields $profileFields
) { ) {}
$this->dbConn = $dbConn;
$this->config = $config;
$this->users = $users;
$this->profileFields = $profileFields;
}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
// Simplify default error pages // Simplify default error pages
@ -145,7 +135,7 @@ final class SatoriRoutes implements IRouteHandler {
$backlogDays = $this->config->getInteger('users.backlog', 7); $backlogDays = $this->config->getInteger('users.backlog', 7);
$startId = (string)$request->getParam('start', FILTER_SANITIZE_NUMBER_INT); $startId = (string)$request->getParam('start', FILTER_SANITIZE_NUMBER_INT);
$userInfos = $this->users->getUsers( $userInfos = $this->usersCtx->getUsers()->getUsers(
after: $startId, after: $startId,
newerThanDays: $backlogDays, newerThanDays: $backlogDays,
orderBy: 'id', orderBy: 'id',

View file

@ -13,37 +13,20 @@ use Misuzu\Config\IConfig;
use Misuzu\Emoticons\Emotes; use Misuzu\Emoticons\Emotes;
use Misuzu\Perms\Permissions; use Misuzu\Perms\Permissions;
use Misuzu\Users\Bans; use Misuzu\Users\Bans;
use Misuzu\Users\Users; use Misuzu\Users\UsersContext;
final class SharpChatRoutes implements IRouteHandler { final class SharpChatRoutes implements IRouteHandler {
private IConfig $config;
private Bans $bans;
private Emotes $emotes;
private Users $users;
private Sessions $sessions;
private Permissions $perms;
private AuthInfo $authInfo;
private Closure $createAuthTokenPacker;
private string $hashKey; private string $hashKey;
public function __construct( public function __construct(
IConfig $config, private IConfig $config,
Bans $bans, private UsersContext $usersCtx,
Emotes $emotes, private Emotes $emotes,
Users $users, private Sessions $sessions,
Sessions $sessions, private Permissions $perms,
Permissions $perms, private AuthInfo $authInfo,
AuthInfo $authInfo, private Closure $createAuthTokenPacker // this sucks lol
Closure $createAuthTokenPacker // this sucks lol
) { ) {
$this->config = $config;
$this->bans = $bans;
$this->emotes = $emotes;
$this->users = $users;
$this->sessions = $sessions;
$this->perms = $perms;
$this->authInfo = $authInfo;
$this->createAuthTokenPacker = $createAuthTokenPacker;
$this->hashKey = $this->config->getString('hashKey', 'woomy'); $this->hashKey = $this->config->getString('hashKey', 'woomy');
} }
@ -157,7 +140,7 @@ final class SharpChatRoutes implements IRouteHandler {
if($sessionInfo->getUserId() !== $tokenInfo->getUserId()) if($sessionInfo->getUserId() !== $tokenInfo->getUserId())
return ['ok' => false, 'err' => 'user']; return ['ok' => false, 'err' => 'user'];
$userInfo = $this->users->getUser($sessionInfo->getUserId(), 'id'); $userInfo = $this->usersCtx->getUsers()->getUser($sessionInfo->getUserId(), 'id');
$userId = $tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser() $userId = $tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser()
? $tokenInfo->getImpersonatedUserId() ? $tokenInfo->getImpersonatedUserId()
: $userInfo->getId(); : $userInfo->getId();
@ -197,7 +180,7 @@ final class SharpChatRoutes implements IRouteHandler {
return 403; return 403;
foreach($bumpList as $userId => $ipAddr) foreach($bumpList as $userId => $ipAddr)
$this->users->recordUserActivity($userId, remoteAddr: $ipAddr); $this->usersCtx->getUsers()->recordUserActivity($userId, remoteAddr: $ipAddr);
} }
public function postVerify($response, $request) { public function postVerify($response, $request) {
@ -249,12 +232,12 @@ final class SharpChatRoutes implements IRouteHandler {
$this->sessions->recordSessionActivity(sessionInfo: $sessionInfo, remoteAddr: $ipAddress); $this->sessions->recordSessionActivity(sessionInfo: $sessionInfo, remoteAddr: $ipAddress);
$userInfo = $this->users->getUser($sessionInfo->getUserId(), 'id'); $userInfo = $this->usersCtx->getUsers()->getUser($sessionInfo->getUserId(), 'id');
if($tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser()) { if($tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser()) {
$userInfoReal = $userInfo; $userInfoReal = $userInfo;
try { try {
$userInfo = $this->users->getUser($tokenInfo->getImpersonatedUserId(), 'id'); $userInfo = $this->usersCtx->getUsers()->getUser($tokenInfo->getImpersonatedUserId(), 'id');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
$userInfo = $userInfoReal; $userInfo = $userInfoReal;
} }
@ -263,9 +246,9 @@ final class SharpChatRoutes implements IRouteHandler {
return ['success' => false, 'reason' => 'unsupported']; return ['success' => false, 'reason' => 'unsupported'];
} }
$this->users->recordUserActivity($userInfo, remoteAddr: $ipAddress); $this->usersCtx->getUsers()->recordUserActivity($userInfo, remoteAddr: $ipAddress);
$userColour = $this->users->getUserColour($userInfo); $userColour = $this->usersCtx->getUsers()->getUserColour($userInfo);
$userRank = $this->users->getUserRank($userInfo); $userRank = $this->usersCtx->getUsers()->getUserRank($userInfo);
return [ return [
'success' => true, 'success' => true,
@ -290,18 +273,14 @@ final class SharpChatRoutes implements IRouteHandler {
return 403; return 403;
$list = []; $list = [];
$bans = $this->bans->getBans(activeOnly: true); $bans = $this->usersCtx->getBans()->getBans(activeOnly: true);
$userInfos = [];
foreach($bans as $banInfo) { foreach($bans as $banInfo) {
$userId = $banInfo->getUserId(); $userId = $banInfo->getUserId();
if(array_key_exists($userId, $userInfos)) $userInfo = $this->usersCtx->getUserInfo($userId);
$userInfo = $userInfos[$userId]; $userColour = $this->usersCtx->getUserColour($userInfo);
else
$userInfos[$userId] = $userInfo = $this->users->getUser($userId, 'id');
$userColour = $this->users->getUserColour($userInfo);
$isPerma = $banInfo->isPermanent(); $isPerma = $banInfo->isPermanent();
$list[] = [ $list[] = [
'is_ban' => true, 'is_ban' => true,
'user_id' => $userId, 'user_id' => $userId,
@ -332,13 +311,13 @@ final class SharpChatRoutes implements IRouteHandler {
if($userIdIsName) if($userIdIsName)
try { try {
$userInfo = $this->users->getUser($userId, 'name'); $userInfo = $this->usersCtx->getUsers()->getUser($userId, 'name');
$userId = (string)$userInfo->getId(); $userId = (string)$userInfo->getId();
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
$userId = ''; $userId = '';
} }
$banInfo = $this->bans->tryGetActiveBan($userId); $banInfo = $this->usersCtx->getBans()->tryGetActiveBan($userId);
if($banInfo === null) if($banInfo === null)
return ['is_ban' => false]; return ['is_ban' => false];
@ -400,19 +379,19 @@ final class SharpChatRoutes implements IRouteHandler {
$modId = 69; $modId = 69;
try { try {
$modInfo = $this->users->getUser($modId, 'id'); $modInfo = $this->usersCtx->getUsers()->getUser($modId, 'id');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
return 404; return 404;
} }
try { try {
$userInfo = $this->users->getUser($userId, 'id'); $userInfo = $this->usersCtx->getUsers()->getUser($userId, 'id');
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
return 404; return 404;
} }
try { try {
$this->bans->createBan( $this->usersCtx->getBans()->createBan(
$userInfo, $userInfo,
$expires, $expires,
$reason, $reason,
@ -442,11 +421,11 @@ final class SharpChatRoutes implements IRouteHandler {
if($type !== 'user') if($type !== 'user')
return 404; return 404;
$banInfo = $this->bans->tryGetActiveBan($subject); $banInfo = $this->usersCtx->getBans()->tryGetActiveBan($subject);
if($banInfo === null) if($banInfo === null)
return 404; return 404;
$this->bans->deleteBans($banInfo); $this->usersCtx->getBans()->deleteBans($banInfo);
return 204; return 204;
} }

View file

@ -7,20 +7,14 @@ use Index\Routing\IRouter;
use Index\Routing\IRouteHandler; use Index\Routing\IRouteHandler;
use Misuzu\Perm; use Misuzu\Perm;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Users\Bans; use Misuzu\Users\UsersContext;
use Misuzu\Users\Users;
use Misuzu\Users\UserInfo; use Misuzu\Users\UserInfo;
class AssetsRoutes implements IRouteHandler { class AssetsRoutes implements IRouteHandler {
private AuthInfo $authInfo; public function __construct(
private Bans $bans; private AuthInfo $authInfo,
private Users $users; private UsersContext $usersCtx
) {}
public function __construct(AuthInfo $authInfo, Bans $bans, Users $users) {
$this->authInfo = $authInfo;
$this->bans = $bans;
$this->users = $users;
}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
$router->get('/assets/avatar', $this->getAvatar(...)); $router->get('/assets/avatar', $this->getAvatar(...));
@ -31,7 +25,7 @@ class AssetsRoutes implements IRouteHandler {
} }
private function canViewAsset($request, UserInfo $assetUser): bool { private function canViewAsset($request, UserInfo $assetUser): bool {
if($this->bans->countActiveBans($assetUser)) if($this->usersCtx->getBans()->countActiveBans($assetUser))
// allow staff viewing profile to still see banned user assets // allow staff viewing profile to still see banned user assets
return $this->authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE) return $this->authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE)
&& parse_url($request->getHeaderFirstLine('Referer'), PHP_URL_PATH) === url('user-profile'); && parse_url($request->getHeaderFirstLine('Referer'), PHP_URL_PATH) === url('user-profile');
@ -44,7 +38,7 @@ class AssetsRoutes implements IRouteHandler {
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC); $assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC);
try { try {
$userInfo = $this->users->getUser($userId, 'id'); $userInfo = $this->usersCtx->getUserInfo($userId);
if(!$this->canViewAsset($request, $userInfo)) { if(!$this->canViewAsset($request, $userInfo)) {
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/banned-avatar.png', MSZ_PUBLIC); $assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/banned-avatar.png', MSZ_PUBLIC);
@ -63,7 +57,7 @@ class AssetsRoutes implements IRouteHandler {
$userId = pathinfo($fileName, PATHINFO_FILENAME); $userId = pathinfo($fileName, PATHINFO_FILENAME);
try { try {
$userInfo = $this->users->getUser($userId, 'id'); $userInfo = $this->usersCtx->getUserInfo($userId);
} catch(RuntimeException $ex) { } catch(RuntimeException $ex) {
} catch(InvalidArgumentException $ex) {} } catch(InvalidArgumentException $ex) {}

View file

@ -234,10 +234,7 @@ class Users {
'recovery' => self::GET_USER_MAIL, 'recovery' => self::GET_USER_MAIL,
]; ];
public function getUser(string $value, int|string $select = self::GET_USER_ID): UserInfo { public static function resolveGetUserSelectAlias(int|string $select): int {
if($value === '')
throw new InvalidArgumentException('$value may not be empty.');
if(is_string($select)) { if(is_string($select)) {
if(!array_key_exists($select, self::GET_USER_SELECT_ALIASES)) if(!array_key_exists($select, self::GET_USER_SELECT_ALIASES))
throw new InvalidArgumentException('Invalid $select alias.'); throw new InvalidArgumentException('Invalid $select alias.');
@ -245,6 +242,14 @@ class Users {
} elseif($select === 0) } elseif($select === 0)
throw new InvalidArgumentException('$select may not be zero.'); throw new InvalidArgumentException('$select may not be zero.');
return $select;
}
public function getUser(string $value, int|string $select = self::GET_USER_ID): UserInfo {
if($value === '')
throw new InvalidArgumentException('$value may not be empty.');
$select = self::resolveGetUserSelectAlias($select);
$selectId = ($select & self::GET_USER_ID) > 0; $selectId = ($select & self::GET_USER_ID) > 0;
$selectName = ($select & self::GET_USER_NAME) > 0; $selectName = ($select & self::GET_USER_NAME) > 0;
$selectMail = ($select & self::GET_USER_MAIL) > 0; $selectMail = ($select & self::GET_USER_MAIL) > 0;

100
src/Users/UsersContext.php Normal file
View file

@ -0,0 +1,100 @@
<?php
namespace Misuzu\Users;
use Index\Colour\Colour;
use Index\Data\IDbConnection;
class UsersContext {
private Users $users;
private Roles $roles;
private Bans $bans;
private Warnings $warnings;
private ModNotes $modNotes;
private array $userInfos = [];
private array $userColours = [];
private array $userRanks = [];
private array $activeBans = [];
public function __construct(IDbConnection $dbConn) {
$this->users = new Users($dbConn);
$this->roles = new Roles($dbConn);
$this->bans = new Bans($dbConn);
$this->warnings = new Warnings($dbConn);
$this->modNotes = new ModNotes($dbConn);
}
public function getUsers(): Users {
return $this->users;
}
public function getRoles(): Roles {
return $this->roles;
}
public function getBans(): Bans {
return $this->bans;
}
public function getWarnings(): Warnings {
return $this->warnings;
}
public function getModNotes(): ModNotes {
return $this->modNotes;
}
public function getUserInfo(string $value, int|string|null $select = null): UserInfo {
$select = Users::resolveGetUserSelectAlias($select ?? Users::GET_USER_ID);
if(($select & Users::GET_USER_ID) > 0 && array_key_exists($value, $this->userInfos))
return $this->userInfos[$value];
$userInfo = $this->users->getUser($value, $select);
$userId = $userInfo->getId();
return $this->userInfos[$userId] = $userInfo;
}
public function getUserColour(UserInfo|string|null $userInfo): Colour {
if($userInfo === null)
return Colour::none();
$userId = $userInfo instanceof UserInfo ? $userInfo->getId() : $userInfo;
if(array_key_exists($userId, $this->userColours))
return $this->userColours[$userId];
return $this->userColours[$userId] = $this->users->getUserColour($userInfo);
}
public function getUserRank(UserInfo|string|null $userInfo): int {
if($userInfo === null)
return 0;
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if(array_key_exists($userInfo, $this->userRanks))
return $this->userRanks[$userInfo];
return $this->userRanks[$userInfo] = $this->users->getUserRank($userInfo);
}
public function tryGetActiveBan(
UserInfo|string|null $userInfo = null,
int $minimumSeverity = Bans::SEVERITY_MIN
): ?BanInfo {
if($userInfo === null)
return null;
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if(!array_key_exists($userInfo, $this->activeBans))
$this->activeBans[$userInfo] = $this->bans->tryGetActiveBan($userInfo);
return $this->activeBans[$userInfo];
}
public function hasActiveBan(UserInfo|string|null $userInfo = null): bool {
return $this->tryGetActiveBan($userInfo) !== null;
}
}