Removed getter/setter methods in favour of property hooks and asymmetric visibility.

This commit is contained in:
flash 2024-11-30 04:09:29 +00:00
parent 2cb2918533
commit d103477fe1
149 changed files with 2169 additions and 3565 deletions

View file

@ -101,8 +101,6 @@ if(!empty($repoInfo['master']))
if($data->ref !== $repoMaster)
die('only the master branch is tracked');
$changelog = $msz->getChangelog();
$tags = $repoInfo['tags'] ?? [];
$addresses = $config['addresses'] ?? [];
@ -118,7 +116,7 @@ foreach($data->commits as $commit) {
$line = $index === false ? $message : mb_substr($message, 0, $index);
$body = trim($index === false ? '' : mb_substr($message, $index + 1));
$changeInfo = $changelog->createChange(
$changeInfo = $msz->changelog->createChange(
ghcb_changelog_action($line),
$line, $body,
$addresses[$commit->author->email] ?? null,
@ -127,5 +125,5 @@ foreach($data->commits as $commit) {
if(!empty($tags))
foreach($tags as $tag)
$changelog->addTagToChange($changeInfo, $tag);
$msz->changelog->addTagToChange($changeInfo, $tag);
}

View file

@ -4,37 +4,30 @@ namespace Misuzu;
use Exception;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getUrls();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$sessions = $authCtx->getSessions();
$loginAttempts = $authCtx->getLoginAttempts();
if(!empty($_GET['resolve'])) {
header('Content-Type: application/json; charset=utf-8');
try {
// Only works for usernames, this is by design
$userInfo = $users->getUser((string)filter_input(INPUT_GET, 'name'), 'name');
$userInfo = $msz->usersCtx->users->getUser((string)filter_input(INPUT_GET, 'name'), 'name');
} catch(Exception $ex) {
echo json_encode([
'id' => 0,
'name' => '',
'avatar' => $urls->format('user-avatar', ['res' => 200, 'user' => 0]),
'avatar' => $msz->urls->format('user-avatar', ['res' => 200, 'user' => 0]),
]);
return;
}
echo json_encode([
'id' => (int)$userInfo->getId(),
'name' => $userInfo->getName(),
'avatar' => $urls->format('user-avatar', ['user' => $userInfo->getId(), 'res' => 200]),
'name' => $userInfo->name,
'avatar' => $msz->urls->format('user-avatar', ['user' => $userInfo->getId(), 'res' => 200]),
]);
return;
}
@ -44,7 +37,7 @@ $ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
$siteIsPrivate = $cfg->getBoolean('private.enable');
if($siteIsPrivate) {
@ -95,49 +88,49 @@ while(!empty($_POST['login']) && is_array($_POST['login'])) {
$loginFailedError = "Invalid username or password, {$attemptsRemainingError}.";
try {
$userInfo = $users->getUser($_POST['login']['username'], 'login');
$userInfo = $msz->usersCtx->users->getUser($_POST['login']['username'], 'login');
} catch(Exception $ex) {
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo);
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo);
$notices[] = $loginFailedError;
break;
}
if(!$userInfo->hasPasswordHash()) {
if(!$userInfo->hasPasswordHash) {
$notices[] = 'Your password has been invalidated, please reset it.';
break;
}
if($userInfo->isDeleted() || !$userInfo->verifyPassword($_POST['login']['password'])) {
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
if($userInfo->deleted || !$userInfo->verifyPassword($_POST['login']['password'])) {
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$notices[] = $loginFailedError;
break;
}
if($userInfo->passwordNeedsRehash())
$users->updateUser($userInfo, password: $_POST['login']['password']);
if($userInfo->passwordNeedsRehash)
$msz->usersCtx->users->updateUser($userInfo, password: $_POST['login']['password']);
if(!empty($loginPermCat) && $loginPermVal > 0 && !$msz->getPerms()->checkPermissions($loginPermCat, $loginPermVal, $userInfo)) {
if(!empty($loginPermCat) && $loginPermVal > 0 && !$msz->perms->checkPermissions($loginPermCat, $loginPermVal, $userInfo)) {
$notices[] = "Login succeeded, but you're not allowed to browse the site right now.";
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
break;
}
if($userInfo->hasTOTPKey()) {
$tfaToken = $authCtx->getTwoFactorAuthSessions()->createToken($userInfo);
Tools::redirect($urls->format('auth-two-factor', ['token' => $tfaToken]));
if($userInfo->hasTOTP) {
$tfaToken = $msz->authCtx->tfaSessions->createToken($userInfo);
Tools::redirect($msz->urls->format('auth-two-factor', ['token' => $tfaToken]));
return;
}
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
try {
$sessionInfo = $sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
$sessionInfo = $msz->authCtx->sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
} catch(Exception $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}
$tokenBuilder = $authInfo->getTokenInfo()->toBuilder();
$tokenBuilder = $msz->authInfo->tokenInfo->toBuilder();
$tokenBuilder->setUserId($userInfo);
$tokenBuilder->setSessionToken($sessionInfo);
$tokenBuilder->removeImpersonatedUserId();
@ -146,7 +139,7 @@ while(!empty($_POST['login']) && is_array($_POST['login'])) {
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
if(!Tools::isLocalURL($loginRedirect))
$loginRedirect = $urls->format('index');
$loginRedirect = $msz->urls->format('index');
Tools::redirect($loginRedirect);
return;
@ -156,7 +149,7 @@ $welcomeMode = !empty($_GET['welcome']);
$loginUsername = !empty($_POST['login']['username']) && is_string($_POST['login']['username']) ? $_POST['login']['username'] : (
!empty($_GET['username']) && is_string($_GET['username']) ? $_GET['username'] : ''
);
$loginRedirect = $welcomeMode ? $urls->format('index') : (!empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : null) ?? $_SERVER['HTTP_REFERER'] ?? $urls->format('index');
$loginRedirect = $welcomeMode ? $msz->urls->format('index') : (!empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : null) ?? $_SERVER['HTTP_REFERER'] ?? $msz->urls->format('index');
$canRegisterAccount = !$siteIsPrivate;
Template::render('auth.login', [

View file

@ -3,25 +3,22 @@ namespace Misuzu;
use Misuzu\Auth\AuthTokenCookie;
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
if($msz->authInfo->isLoggedIn) {
if(!CSRF::validateRequest()) {
Template::render('auth.logout');
return;
}
$tokenInfo = $authInfo->getTokenInfo();
$authCtx = $msz->getAuthContext();
$authCtx->getSessions()->deleteSessions(sessionTokens: $tokenInfo->getSessionToken());
$tokenInfo = $msz->authInfo->tokenInfo;
$msz->authCtx->sessions->deleteSessions(sessionTokens: $tokenInfo->sessionToken);
$tokenBuilder = $tokenInfo->toBuilder();
$tokenBuilder->removeUserId();
$tokenBuilder->removeSessionToken();
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
}
Tools::redirect($msz->getUrls()->format('index'));;
Tools::redirect($msz->urls->format('index'));;

View file

@ -4,18 +4,11 @@ namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
$urls = $msz->getUrls();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('settings-account'));
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('settings-account'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$recoveryTokens = $authCtx->getRecoveryTokens();
$loginAttempts = $authCtx->getLoginAttempts();
$reset = !empty($_POST['reset']) && is_array($_POST['reset']) ? $_POST['reset'] : [];
$forgot = !empty($_POST['forgot']) && is_array($_POST['forgot']) ? $_POST['forgot'] : [];
$userId = !empty($reset['user']) ? (int)$reset['user'] : (
@ -24,9 +17,9 @@ $userId = !empty($reset['user']) ? (int)$reset['user'] : (
if($userId > 0)
try {
$userInfo = $users->getUser((string)$userId, 'id');
$userInfo = $msz->usersCtx->users->getUser((string)$userId, 'id');
} catch(RuntimeException $ex) {
Tools::redirect($urls->format('auth-forgot'));
Tools::redirect($msz->urls->format('auth-forgot'));
return;
}
@ -35,7 +28,7 @@ $ipAddress = $_SERVER['REMOTE_ADDR'];
$siteIsPrivate = $cfg->getBoolean('private.enable');
$canResetPassword = $siteIsPrivate ? $cfg->getBoolean('private.allow_password_reset', true) : true;
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
while($canResetPassword) {
if(!empty($reset) && $userId > 0) {
@ -47,12 +40,12 @@ while($canResetPassword) {
$verifyCode = !empty($reset['verification']) && is_string($reset['verification']) ? $reset['verification'] : '';
try {
$tokenInfo = $recoveryTokens->getToken(verifyCode: $verifyCode);
$tokenInfo = $msz->authCtx->recoveryTokens->getToken(verifyCode: $verifyCode);
} catch(RuntimeException $ex) {
unset($tokenInfo);
}
if(empty($tokenInfo) || !$tokenInfo->isValid() || $tokenInfo->getUserId() !== (string)$userInfo->getId()) {
if(empty($tokenInfo) || !$tokenInfo->isValid || $tokenInfo->userId !== (string)$userInfo->getId()) {
$notices[] = 'Invalid verification code!';
break;
}
@ -67,21 +60,21 @@ while($canResetPassword) {
break;
}
$passwordValidation = $users->validatePassword($passwordNew);
$passwordValidation = $msz->usersCtx->users->validatePassword($passwordNew);
if($passwordValidation !== '') {
$notices[] = $users->validatePasswordText($passwordValidation);
$notices[] = $msz->usersCtx->users->validatePasswordText($passwordValidation);
break;
}
// also disables two factor auth to prevent getting locked out of account entirely
// this behaviour should really be replaced with recovery keys...
$users->updateUser($userInfo, password: $passwordNew, totpKey: '');
$msz->usersCtx->users->updateUser($userInfo, password: $passwordNew, totpKey: '');
$msz->createAuditLog('PASSWORD_RESET', [], $userInfo);
$recoveryTokens->invalidateToken($tokenInfo);
$msz->authCtx->recoveryTokens->invalidateToken($tokenInfo);
Tools::redirect($urls->format('auth-login', ['redirect' => '/']));
Tools::redirect($msz->urls->format('auth-login', ['redirect' => '/']));
return;
}
@ -102,39 +95,39 @@ while($canResetPassword) {
}
try {
$forgotUser = $users->getUser($forgot['email'], 'email');
$forgotUser = $msz->usersCtx->users->getUser($forgot['email'], 'email');
} catch(RuntimeException $ex) {
unset($forgotUser);
}
if(empty($forgotUser) || $forgotUser->isDeleted()) {
if(empty($forgotUser) || $forgotUser->deleted) {
$notices[] = "This e-mail address is not registered with us.";
break;
}
try {
$tokenInfo = $recoveryTokens->getToken(userInfo: $forgotUser, remoteAddr: $ipAddress);
$tokenInfo = $msz->authCtx->recoveryTokens->getToken(userInfo: $forgotUser, remoteAddr: $ipAddress);
} catch(RuntimeException $ex) {
$tokenInfo = $recoveryTokens->createToken($forgotUser, $ipAddress);
$tokenInfo = $msz->authCtx->recoveryTokens->createToken($forgotUser, $ipAddress);
$recoveryMessage = Mailer::template('password-recovery', [
'username' => $forgotUser->getName(),
'token' => $tokenInfo->getCode(),
'username' => $forgotUser->name,
'token' => $tokenInfo->code,
]);
$recoveryMail = Mailer::sendMessage(
[$forgotUser->getEMailAddress() => $forgotUser->getName()],
[$forgotUser->emailAddress => $forgotUser->name],
$recoveryMessage['subject'], $recoveryMessage['message']
);
if(!$recoveryMail) {
$notices[] = "Failed to send reset email, please contact the administrator.";
$recoveryTokens->invalidateToken($tokenInfo);
$msz->authCtx->recoveryTokens->invalidateToken($tokenInfo);
break;
}
}
Tools::redirect($urls->format('auth-reset', ['user' => $forgotUser->getId()]));
Tools::redirect($msz->urls->format('auth-reset', ['user' => $forgotUser->getId()]));
return;
}

View file

@ -4,19 +4,11 @@ namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
$urls = $msz->getUrls();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$config = $msz->getConfig();
$register = !empty($_POST['register']) && is_array($_POST['register']) ? $_POST['register'] : [];
$notices = [];
$ipAddress = $_SERVER['REMOTE_ADDR'];
@ -33,8 +25,7 @@ $countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
// for fast matching
$restricted = '';
$loginAttempts = $authCtx->getLoginAttempts();
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
while(!$restricted && !empty($register)) {
if(!CSRF::validateRequest()) {
@ -69,28 +60,28 @@ while(!$restricted && !empty($register)) {
break;
}
$usernameValidation = $users->validateName($register['username']);
$usernameValidation = $msz->usersCtx->users->validateName($register['username']);
if($usernameValidation !== '')
$notices[] = $users->validateNameText($usernameValidation);
$notices[] = $msz->usersCtx->users->validateNameText($usernameValidation);
$emailValidation = $users->validateEMailAddress($register['email']);
$emailValidation = $msz->usersCtx->users->validateEMailAddress($register['email']);
if($emailValidation !== '')
$notices[] = $users->validateEMailAddressText($emailValidation);
$notices[] = $msz->usersCtx->users->validateEMailAddressText($emailValidation);
if($register['password_confirm'] !== $register['password'])
$notices[] = 'The given passwords don\'t match.';
$passwordValidation = $users->validatePassword($register['password']);
$passwordValidation = $msz->usersCtx->users->validatePassword($register['password']);
if($passwordValidation !== '')
$notices[] = $users->validatePasswordText($passwordValidation);
$notices[] = $msz->usersCtx->users->validatePasswordText($passwordValidation);
if(!empty($notices))
break;
$defaultRoleInfo = $roles->getDefaultRole();
$defaultRoleInfo = $msz->usersCtx->roles->getDefaultRole();
try {
$userInfo = $users->createUser(
$userInfo = $msz->usersCtx->users->createUser(
$register['username'],
$register['password'],
$register['email'],
@ -103,14 +94,14 @@ while(!$restricted && !empty($register)) {
break;
}
$users->addRoles($userInfo, $defaultRoleInfo);
$config->setString('users.newest', $userInfo->getId());
$msz->getPerms()->precalculatePermissions(
$msz->getForumContext()->getCategories(),
$msz->usersCtx->users->addRoles($userInfo, $defaultRoleInfo);
$msz->config->setString('users.newest', $userInfo->getId());
$msz->perms->precalculatePermissions(
$msz->forumCtx->categories,
[$userInfo->getId()]
);
Tools::redirect($urls->format('auth-login-welcome', ['username' => $userInfo->getName()]));
Tools::redirect($msz->urls->format('auth-login-welcome', ['username' => $userInfo->name]));
return;
}

View file

@ -3,21 +3,20 @@ namespace Misuzu;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getUrls();
if(CSRF::validateRequest()) {
$tokenInfo = $msz->getAuthInfo()->getTokenInfo();
$tokenInfo = $msz->authInfo->tokenInfo;
if($tokenInfo->hasImpersonatedUserId()) {
$impUserId = $tokenInfo->getImpersonatedUserId();
if($tokenInfo->hasImpersonatedUserId) {
$impUserId = $tokenInfo->impersonatedUserId;
$tokenBuilder = $tokenInfo->toBuilder();
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
Tools::redirect($urls->format('manage-user', ['user' => $impUserId]));
Tools::redirect($msz->urls->format('manage-user', ['user' => $impUserId]));
return;
}
}
Tools::redirect($urls->format('index'));
Tools::redirect($msz->urls->format('index'));

View file

@ -5,43 +5,35 @@ use RuntimeException;
use Misuzu\TOTPGenerator;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getUrls();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$sessions = $authCtx->getSessions();
$tfaSessions = $authCtx->getTwoFactorAuthSessions();
$loginAttempts = $authCtx->getLoginAttempts();
$ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$twofactor = !empty($_POST['twofactor']) && is_array($_POST['twofactor']) ? $_POST['twofactor'] : [];
$notices = [];
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
$tokenString = !empty($_GET['token']) && is_string($_GET['token']) ? $_GET['token'] : (
!empty($twofactor['token']) && is_string($twofactor['token']) ? $twofactor['token'] : ''
);
$tokenUserId = $tfaSessions->getTokenUserId($tokenString);
$tokenUserId = $msz->authCtx->tfaSessions->getTokenUserId($tokenString);
if(empty($tokenUserId)) {
Tools::redirect($urls->format('auth-login'));
Tools::redirect($msz->urls->format('auth-login'));
return;
}
$userInfo = $users->getUser($tokenUserId, 'id');
$userInfo = $msz->usersCtx->users->getUser($tokenUserId, 'id');
// checking user_totp_key specifically because there's a fringe chance that
// there's a token present, but totp is actually disabled
if(!$userInfo->hasTOTPKey()) {
Tools::redirect($urls->format('auth-login'));
if(!$userInfo->hasTOTP) {
Tools::redirect($msz->urls->format('auth-login'));
return;
}
@ -65,7 +57,7 @@ while(!empty($twofactor)) {
}
$clientInfo = ClientInfo::fromRequest();
$totp = new TOTPGenerator($userInfo->getTOTPKey());
$totp = new TOTPGenerator($userInfo->totpKey);
if(!in_array($twofactor['code'], $totp->generateRange())) {
$notices[] = sprintf(
@ -73,21 +65,21 @@ while(!empty($twofactor)) {
$remainingAttempts - 1,
$remainingAttempts === 2 ? '' : 's'
);
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
break;
}
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$tfaSessions->deleteToken($tokenString);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->tfaSessions->deleteToken($tokenString);
try {
$sessionInfo = $sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
$sessionInfo = $msz->authCtx->sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
} catch(RuntimeException $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}
$tokenBuilder = $authInfo->getTokenInfo()->toBuilder();
$tokenBuilder = $msz->authInfo->tokenInfo->toBuilder();
$tokenBuilder->setUserId($userInfo);
$tokenBuilder->setSessionToken($sessionInfo);
$tokenBuilder->removeImpersonatedUserId();
@ -96,7 +88,7 @@ while(!empty($twofactor)) {
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
if(!Tools::isLocalURL($redirect))
$redirect = $urls->format('index');
$redirect = $msz->urls->format('index');
Tools::redirect($redirect);
return;
@ -104,7 +96,7 @@ while(!empty($twofactor)) {
Template::render('auth.twofactor', [
'twofactor_notices' => $notices,
'twofactor_redirect' => !empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : $urls->format('index'),
'twofactor_redirect' => !empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : $msz->urls->format('index'),
'twofactor_attempts_remaining' => $remainingAttempts,
'twofactor_token' => $tokenString,
]);

View file

@ -3,8 +3,7 @@ namespace Misuzu;
use RuntimeException;
$usersCtx = $msz->getUsersContext();
$redirect = filter_input(INPUT_GET, 'return') ?? $_SERVER['HTTP_REFERER'] ?? $msz->getUrls()->format('index');
$redirect = filter_input(INPUT_GET, 'return') ?? $_SERVER['HTTP_REFERER'] ?? $msz->urls->format('index');
if(!Tools::isLocalURL($redirect))
Template::displayInfo('Possible request forgery detected.', 403);
@ -12,17 +11,13 @@ if(!Tools::isLocalURL($redirect))
if(!CSRF::validateRequest())
Template::displayInfo("Couldn't verify this request, please refresh the page and try again.", 403);
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::displayInfo('You must be logged in to manage comments.', 403);
$currentUserInfo = $authInfo->getUserInfo();
if($usersCtx->hasActiveBan($currentUserInfo))
if($msz->usersCtx->hasActiveBan($msz->authInfo->userInfo))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
$comments = $msz->getComments();
$perms = $authInfo->getPerms('global');
$perms = $msz->authInfo->getPerms('global');
$commentId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$commentMode = (string)filter_input(INPUT_GET, 'm');
@ -30,12 +25,12 @@ $commentVote = (int)filter_input(INPUT_GET, 'v', FILTER_SANITIZE_NUMBER_INT);
if(!empty($commentId)) {
try {
$commentInfo = $comments->getPost($commentId);
$commentInfo = $msz->comments->getPost($commentId);
} catch(RuntimeException $ex) {
Template::displayInfo('Post not found.', 404);
}
$categoryInfo = $comments->getCategory(postInfo: $commentInfo);
$categoryInfo = $msz->comments->getCategory(postInfo: $commentInfo);
}
if($commentMode !== 'create' && empty($commentInfo))
@ -44,77 +39,77 @@ if($commentMode !== 'create' && empty($commentInfo))
switch($commentMode) {
case 'pin':
case 'unpin':
if(!$perms->check(Perm::G_COMMENTS_PIN) && !$categoryInfo->isOwner($currentUserInfo))
if(!$perms->check(Perm::G_COMMENTS_PIN) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to pin comments.", 403);
if($commentInfo->isDeleted())
if($commentInfo->deleted)
Template::displayInfo("This comment doesn't exist!", 400);
if($commentInfo->isReply())
if($commentInfo->isReply)
Template::displayInfo("You can't pin replies!", 400);
$isPinning = $commentMode === 'pin';
if($isPinning) {
if($commentInfo->isPinned())
if($commentInfo->pinned)
Template::displayInfo('This comment is already pinned.', 400);
$comments->pinPost($commentInfo);
$msz->comments->pinPost($commentInfo);
} else {
if(!$commentInfo->isPinned())
if(!$commentInfo->pinned)
Template::displayInfo("This comment isn't pinned yet.", 400);
$comments->unpinPost($commentInfo);
$msz->comments->unpinPost($commentInfo);
}
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'vote':
if(!$perms->check(Perm::G_COMMENTS_VOTE) && !$categoryInfo->isOwner($currentUserInfo))
if(!$perms->check(Perm::G_COMMENTS_VOTE) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to vote on comments.", 403);
if($commentInfo->isDeleted())
if($commentInfo->deleted)
Template::displayInfo("This comment doesn't exist!", 400);
if($commentVote > 0)
$comments->addPostPositiveVote($commentInfo, $currentUserInfo);
$msz->comments->addPostPositiveVote($commentInfo, $msz->authInfo->userInfo);
elseif($commentVote < 0)
$comments->addPostNegativeVote($commentInfo, $currentUserInfo);
$msz->comments->addPostNegativeVote($commentInfo, $msz->authInfo->userInfo);
else
$comments->removePostVote($commentInfo, $currentUserInfo);
$msz->comments->removePostVote($commentInfo, $msz->authInfo->userInfo);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'delete':
$canDelete = $perms->check(Perm::G_COMMENTS_DELETE_OWN | Perm::G_COMMENTS_DELETE_ANY);
if(!$canDelete && !$categoryInfo->isOwner($currentUserInfo))
if(!$canDelete && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to delete comments.", 403);
$canDeleteAny = $perms->check(Perm::G_COMMENTS_DELETE_ANY);
if($commentInfo->isDeleted())
if($commentInfo->deleted)
Template::displayInfo(
$canDeleteAny ? 'This comment is already marked for deletion.' : "This comment doesn't exist.",
400
);
$isOwnComment = $commentInfo->getUserId() === $currentUserInfo->getId();
$isOwnComment = $commentInfo->userId === $msz->authInfo->userInfo->getId();
$isModAction = $canDeleteAny && !$isOwnComment;
if(!$isModAction && !$isOwnComment)
Template::displayInfo("You're not allowed to delete comments made by others.", 403);
$comments->deletePost($commentInfo);
$msz->comments->deletePost($commentInfo);
if($isModAction) {
$msz->createAuditLog('COMMENT_ENTRY_DELETE_MOD', [
$commentInfo->getId(),
$commentUserId = $commentInfo->getUserId(),
$commentInfo->id,
$commentUserId = $commentInfo->userId,
'<username>',
]);
} else {
$msz->createAuditLog('COMMENT_ENTRY_DELETE', [$commentInfo->getId()]);
$msz->createAuditLog('COMMENT_ENTRY_DELETE', [$commentInfo->id]);
}
Tools::redirect($redirect);
@ -124,22 +119,22 @@ switch($commentMode) {
if(!$perms->check(Perm::G_COMMENTS_DELETE_ANY))
Template::displayInfo("You're not allowed to restore deleted comments.", 403);
if(!$commentInfo->isDeleted())
if(!$commentInfo->deleted)
Template::displayInfo("This comment isn't in a deleted state.", 400);
$comments->restorePost($commentInfo);
$msz->comments->restorePost($commentInfo);
$msz->createAuditLog('COMMENT_ENTRY_RESTORE', [
$commentInfo->getId(),
$commentUserId = $commentInfo->getUserId(),
$commentInfo->id,
$commentUserId = $commentInfo->userId,
'<username>',
]);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'create':
if(!$perms->check(Perm::G_COMMENTS_CREATE) && !$categoryInfo->isOwner($currentUserInfo))
if(!$perms->check(Perm::G_COMMENTS_CREATE) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to post comments.", 403);
if(empty($_POST['comment']) || !is_array($_POST['comment']))
@ -149,13 +144,13 @@ switch($commentMode) {
$categoryId = isset($_POST['comment']['category']) && is_string($_POST['comment']['category'])
? (int)$_POST['comment']['category']
: 0;
$categoryInfo = $comments->getCategory(categoryId: $categoryId);
$categoryInfo = $msz->comments->getCategory(categoryId: $categoryId);
} catch(RuntimeException $ex) {
Template::displayInfo('This comment category doesn\'t exist.', 404);
}
$canLock = $perms->check(Perm::G_COMMENTS_LOCK);
if($categoryInfo->isLocked() && !$canLock)
if($categoryInfo->locked && !$canLock)
Template::displayInfo('This comment category has been locked.', 403);
$commentText = !empty($_POST['comment']['text']) && is_string($_POST['comment']['text']) ? $_POST['comment']['text'] : '';
@ -164,10 +159,10 @@ switch($commentMode) {
$commentPin = !empty($_POST['comment']['pin']) && $perms->check(Perm::G_COMMENTS_PIN);
if($commentLock) {
if($categoryInfo->isLocked())
$comments->unlockCategory($categoryInfo);
if($categoryInfo->locked)
$msz->comments->unlockCategory($categoryInfo);
else
$comments->lockCategory($categoryInfo);
$msz->comments->lockCategory($categoryInfo);
}
if(strlen($commentText) > 0) {
@ -186,22 +181,22 @@ switch($commentMode) {
if($commentReply > 0) {
try {
$parentInfo = $comments->getPost($commentReply);
$parentInfo = $msz->comments->getPost($commentReply);
} catch(RuntimeException $ex) {}
if(!isset($parentInfo) || $parentInfo->isDeleted())
if(!isset($parentInfo) || $parentInfo->deleted)
Template::displayInfo('The comment you tried to reply to does not exist.', 404);
}
$commentInfo = $comments->createPost(
$commentInfo = $msz->comments->createPost(
$categoryInfo,
$parentInfo ?? null,
$currentUserInfo,
$msz->authInfo->userInfo,
$commentText,
$commentPin
);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
default:

View file

@ -4,43 +4,32 @@ namespace Misuzu;
use stdClass;
use RuntimeException;
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$categoryId = (int)filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);
try {
$categoryInfo = $forumCategories->getCategory(categoryId: $categoryId);
$categoryInfo = $msz->forumCtx->categories->getCategory(categoryId: $categoryId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$authInfo = $msz->getAuthInfo();
$perms = $authInfo->getPerms('forum', $categoryInfo);
$perms = $msz->authInfo->getPerms('forum', $categoryInfo);
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if(!$perms->check(Perm::F_CATEGORY_VIEW))
Template::throwError(403);
if($usersCtx->hasActiveBan($currentUser))
if($msz->usersCtx->hasActiveBan($currentUser))
$perms = $perms->apply(fn($calc) => $calc & (Perm::F_CATEGORY_LIST | Perm::F_CATEGORY_VIEW));
if($categoryInfo->isLink()) {
if($categoryInfo->hasLinkTarget()) {
$forumCategories->incrementCategoryClicks($categoryInfo);
Tools::redirect($categoryInfo->getLinkTarget());
return;
}
Template::throwError(404);
if($categoryInfo->isLink) {
$msz->forumCtx->categories->incrementCategoryClicks($categoryInfo);
Tools::redirect($categoryInfo->linkTarget ?? '/');
return;
}
$forumPagination = new Pagination($forumTopics->countTopics(
$forumPagination = new Pagination($msz->forumCtx->topics->countTopics(
categoryInfo: $categoryInfo,
global: true,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false
@ -52,11 +41,11 @@ if(!$forumPagination->hasValidOffset())
$children = [];
$topics = [];
if($categoryInfo->mayHaveChildren()) {
$children = $forumCategories->getCategoryChildren($categoryInfo, hidden: false, asTree: true);
if($categoryInfo->mayHaveChildren) {
$children = $msz->forumCtx->categories->getCategoryChildren($categoryInfo, hidden: false, asTree: true);
foreach($children as $childId => $child) {
$childPerms = $authInfo->getPerms('forum', $child->info);
$childPerms = $msz->authInfo->getPerms('forum', $child->info);
if(!$childPerms->check(Perm::F_CATEGORY_LIST)) {
unset($category->children[$childId]);
continue;
@ -64,9 +53,9 @@ if($categoryInfo->mayHaveChildren()) {
$childUnread = false;
if($child->info->mayHaveChildren()) {
if($child->info->mayHaveChildren) {
foreach($child->children as $grandChildId => $grandChild) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChild->info);
$grandChildPerms = $msz->authInfo->getPerms('forum', $grandChild->info);
if(!$grandChildPerms->check(Perm::F_CATEGORY_LIST)) {
unset($child->children[$grandChildId]);
continue;
@ -74,15 +63,15 @@ if($categoryInfo->mayHaveChildren()) {
$grandChildUnread = false;
if($grandChild->info->mayHaveTopics()) {
$catIds = [$grandChild->info->getId()];
if($grandChild->info->mayHaveTopics) {
$catIds = [$grandChild->info->id];
foreach($grandChild->childIds as $greatGrandChildId) {
$greatGrandChildPerms = $authInfo->getPerms('forum', $greatGrandChildId);
$greatGrandChildPerms = $msz->authInfo->getPerms('forum', $greatGrandChildId);
if(!$greatGrandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $greatGrandChildId;
}
$grandChildUnread = $forumCategories->checkCategoryUnread($catIds, $currentUser);
$grandChildUnread = $msz->forumCtx->categories->checkCategoryUnread($catIds, $currentUser);
if($grandChildUnread)
$childUnread = true;
}
@ -92,16 +81,16 @@ if($categoryInfo->mayHaveChildren()) {
}
}
if($child->info->mayHaveChildren() || $child->info->mayHaveTopics()) {
$catIds = [$child->info->getId()];
if($child->info->mayHaveChildren || $child->info->mayHaveTopics) {
$catIds = [$child->info->id];
foreach($child->childIds as $grandChildId) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChildId);
$grandChildPerms = $msz->authInfo->getPerms('forum', $grandChildId);
if($grandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $grandChildId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
$lastPostInfo = $msz->forumCtx->posts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
@ -109,25 +98,25 @@ if($categoryInfo->mayHaveChildren()) {
if($lastPostInfo !== null) {
$child->lastPost = new stdClass;
$child->lastPost->info = $lastPostInfo;
$child->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
$child->lastPost->topicInfo = $msz->forumCtx->topics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
if($lastPostInfo->userId !== null) {
$child->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId);
$child->lastPost->colour = $msz->usersCtx->getUserColour($child->lastPost->user);
}
}
}
if($child->info->mayHaveTopics() && !$childUnread)
$childUnread = $forumCategories->checkCategoryUnread($child->info, $currentUser);
if($child->info->mayHaveTopics && !$childUnread)
$childUnread = $msz->forumCtx->categories->checkCategoryUnread($child->info, $currentUser);
$child->perms = $childPerms;
$child->unread = $childUnread;
}
}
if($categoryInfo->mayHaveTopics()) {
$topicInfos = $forumTopics->getTopics(
if($categoryInfo->mayHaveTopics) {
$topicInfos = $msz->forumCtx->topics->getTopics(
categoryInfo: $categoryInfo,
global: true,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false,
@ -137,25 +126,25 @@ if($categoryInfo->mayHaveTopics()) {
foreach($topicInfos as $topicInfo) {
$topics[] = $topic = new stdClass;
$topic->info = $topicInfo;
$topic->unread = $forumTopics->checkTopicUnread($topicInfo, $currentUser);
$topic->participated = $forumTopics->checkTopicParticipated($topicInfo, $currentUser);
$topic->unread = $msz->forumCtx->topics->checkTopicUnread($topicInfo, $currentUser);
$topic->participated = $msz->forumCtx->topics->checkTopicParticipated($topicInfo, $currentUser);
if($topicInfo->hasUserId()) {
$topic->user = $usersCtx->getUserInfo($topicInfo->getUserId());
$topic->colour = $usersCtx->getUserColour($topic->user);
if($topicInfo->userId !== null) {
$topic->user = $msz->usersCtx->getUserInfo($topicInfo->userId);
$topic->colour = $msz->usersCtx->getUserColour($topic->user);
}
try {
$topic->lastPost = new stdClass;
$topic->lastPost->info = $lastPostInfo = $forumPosts->getPost(
$topic->lastPost->info = $lastPostInfo = $msz->forumCtx->posts->getPost(
topicInfo: $topicInfo,
getLast: true,
deleted: $topicInfo->isDeleted() ? null : false,
deleted: $topicInfo->deleted ? null : false,
);
if($lastPostInfo->hasUserId()) {
$topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
if($lastPostInfo->userId !== null) {
$topic->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId);
$topic->lastPost->colour = $msz->usersCtx->getUserColour($topic->lastPost->user);
}
} catch(RuntimeException $ex) {
$topic->lastPost = null;
@ -168,8 +157,8 @@ $perms = $perms->checkMany([
]);
Template::render('forum.forum', [
'forum_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($categoryInfo)),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'forum_breadcrumbs' => iterator_to_array($msz->forumCtx->categories->getCategoryAncestry($categoryInfo)),
'global_accent_colour' => $msz->forumCtx->categories->getCategoryColour($categoryInfo),
'forum_info' => $categoryInfo,
'forum_children' => $children,
'forum_topics' => $topics,

View file

@ -4,42 +4,36 @@ namespace Misuzu;
use stdClass;
use RuntimeException;
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$mode = (string)filter_input(INPUT_GET, 'm');
$authInfo = $msz->getAuthInfo();
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($mode === 'mark') {
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(403);
$categoryId = filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);
if($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$categoryInfos = $categoryId === null
? $forumCategories->getCategories()
: $forumCategories->getCategoryChildren(parentInfo: $categoryId, includeSelf: true);
? $msz->forumCtx->categories->getCategories()
: $msz->forumCtx->categories->getCategoryChildren(parentInfo: $categoryId, includeSelf: true);
foreach($categoryInfos as $categoryInfo) {
$perms = $authInfo->getPerms('forum', $categoryInfo);
$perms = $msz->authInfo->getPerms('forum', $categoryInfo);
if($perms->check(Perm::F_CATEGORY_LIST))
$forumCategories->updateUserReadCategory($userInfo, $categoryInfo);
$msz->forumCtx->categories->updateUserReadCategory($userInfo, $categoryInfo);
}
Tools::redirect($msz->getUrls()->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]));
Tools::redirect($msz->urls->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]));
return;
}
Template::render('confirm', [
'title' => 'Mark forum as read',
'message' => 'Are you sure you want to mark ' . ($categoryId < 1 ? 'the entire' : 'this') . ' forum as read?',
'return' => $msz->getUrls()->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]),
'return' => $msz->urls->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]),
'params' => [
'forum' => $categoryId,
]
@ -50,10 +44,10 @@ if($mode === 'mark') {
if($mode !== '')
Template::throwError(404);
$categories = $forumCategories->getCategories(hidden: false, asTree: true);
$categories = $msz->forumCtx->categories->getCategories(hidden: false, asTree: true);
foreach($categories as $categoryId => $category) {
$perms = $authInfo->getPerms('forum', $category->info);
$perms = $msz->authInfo->getPerms('forum', $category->info);
if(!$perms->check(Perm::F_CATEGORY_LIST)) {
unset($categories[$categoryId]);
continue;
@ -61,9 +55,9 @@ foreach($categories as $categoryId => $category) {
$unread = false;
if($category->info->mayHaveChildren())
if($category->info->mayHaveChildren)
foreach($category->children as $childId => $child) {
$childPerms = $authInfo->getPerms('forum', $child->info);
$childPerms = $msz->authInfo->getPerms('forum', $child->info);
if(!$childPerms->check(Perm::F_CATEGORY_LIST)) {
unset($category->children[$childId]);
continue;
@ -71,10 +65,10 @@ foreach($categories as $categoryId => $category) {
$childUnread = false;
if($category->info->isListing()) {
if($child->info->mayHaveChildren()) {
if($category->info->isListing) {
if($child->info->mayHaveChildren) {
foreach($child->children as $grandChildId => $grandChild) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChild->info);
$grandChildPerms = $msz->authInfo->getPerms('forum', $grandChild->info);
if(!$grandChildPerms->check(Perm::F_CATEGORY_LIST)) {
unset($child->children[$grandChildId]);
continue;
@ -82,15 +76,15 @@ foreach($categories as $categoryId => $category) {
$grandChildUnread = false;
if($grandChild->info->mayHaveTopics()) {
$catIds = [$grandChild->info->getId()];
if($grandChild->info->mayHaveTopics) {
$catIds = [$grandChild->info->id];
foreach($grandChild->childIds as $greatGrandChildId) {
$greatGrandChildPerms = $authInfo->getPerms('forum', $greatGrandChildId);
$greatGrandChildPerms = $msz->authInfo->getPerms('forum', $greatGrandChildId);
if($greatGrandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $greatGrandChildId;
}
$grandChildUnread = $forumCategories->checkCategoryUnread($catIds, $currentUser);
$grandChildUnread = $msz->forumCtx->categories->checkCategoryUnread($catIds, $currentUser);
if($grandChildUnread)
$childUnread = true;
}
@ -100,16 +94,16 @@ foreach($categories as $categoryId => $category) {
}
}
if($child->info->mayHaveChildren() || $child->info->mayHaveTopics()) {
$catIds = [$child->info->getId()];
if($child->info->mayHaveChildren || $child->info->mayHaveTopics) {
$catIds = [$child->info->id];
foreach($child->childIds as $grandChildId) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChildId);
$grandChildPerms = $msz->authInfo->getPerms('forum', $grandChildId);
if($grandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $grandChildId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
$lastPostInfo = $msz->forumCtx->posts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
@ -117,18 +111,18 @@ foreach($categories as $categoryId => $category) {
if($lastPostInfo !== null) {
$child->lastPost = new stdClass;
$child->lastPost->info = $lastPostInfo;
$child->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
$child->lastPost->topicInfo = $msz->forumCtx->topics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
if($lastPostInfo->userId !== null) {
$child->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId);
$child->lastPost->colour = $msz->usersCtx->getUserColour($child->lastPost->user);
}
}
}
}
if($child->info->mayHaveTopics() && !$childUnread) {
$childUnread = $forumCategories->checkCategoryUnread($child->info, $currentUser);
if($child->info->mayHaveTopics && !$childUnread) {
$childUnread = $msz->forumCtx->categories->checkCategoryUnread($child->info, $currentUser);
if($childUnread)
$unread = true;
}
@ -137,10 +131,10 @@ foreach($categories as $categoryId => $category) {
$child->unread = $childUnread;
}
if($category->info->mayHaveTopics() && !$unread)
$unread = $forumCategories->checkCategoryUnread($category->info, $currentUser);
if($category->info->mayHaveTopics && !$unread)
$unread = $msz->forumCtx->categories->checkCategoryUnread($category->info, $currentUser);
if(!$category->info->isListing()) {
if(!$category->info->isListing) {
if(!array_key_exists('0', $categories)) {
$categories['0'] = $root = new stdClass;
$root->info = null;
@ -153,16 +147,16 @@ foreach($categories as $categoryId => $category) {
$categories['0']->children[$categoryId] = $category;
unset($categories[$categoryId]);
if($category->info->mayHaveChildren() || $category->info->mayHaveTopics()) {
$catIds = [$category->info->getId()];
if($category->info->mayHaveChildren || $category->info->mayHaveTopics) {
$catIds = [$category->info->id];
foreach($category->childIds as $childId) {
$childPerms = $authInfo->getPerms('forum', $childId);
$childPerms = $msz->authInfo->getPerms('forum', $childId);
if($childPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $childId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
$lastPostInfo = $msz->forumCtx->posts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
@ -170,11 +164,11 @@ foreach($categories as $categoryId => $category) {
if($lastPostInfo !== null) {
$category->lastPost = new stdClass;
$category->lastPost->info = $lastPostInfo;
$category->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
$category->lastPost->topicInfo = $msz->forumCtx->topics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$category->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$category->lastPost->colour = $usersCtx->getUserColour($category->lastPost->user);
if($lastPostInfo->userId !== null) {
$category->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId);
$category->lastPost->colour = $msz->usersCtx->getUserColour($category->lastPost->user);
}
}
}

View file

@ -3,11 +3,9 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIEW))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIEW))
Template::throwError(403);
$forumCtx = $msz->getForumContext();
$usersCtx = $msz->getUsersContext();
$config = $cfg->getValues([
['forum_leader.first_year:i', 2018],
['forum_leader.first_month:i', 12],
@ -61,12 +59,12 @@ for($i = $currentYear, $j = $currentMonth;;) {
break;
}
$rankings = $forumCtx->getPosts()->generatePostRankings($year, $month, $unrankedForums, $unrankedTopics);
$rankings = $msz->forumCtx->posts->generatePostRankings($year, $month, $unrankedForums, $unrankedTopics);
foreach($rankings as $ranking) {
$ranking->user = $ranking->colour = null;
if($ranking->userId !== '')
$ranking->user = $usersCtx->getUserInfo($ranking->userId);
$ranking->user = $msz->usersCtx->getUserInfo($ranking->userId);
}
$name = 'All Time';
@ -92,9 +90,9 @@ MD;
foreach($rankings as $ranking) {
$totalPostsCount += $ranking->postsCount;
$markdown .= sprintf("| %s | [%s](%s%s) | %s |\r\n", $ranking->position,
$ranking->user?->getName() ?? 'Deleted User',
$msz->getSiteInfo()->getURL(),
$msz->getUrls()->format('user-profile', ['user' => $ranking->userId]),
$ranking->user?->name ?? 'Deleted User',
$msz->siteInfo->url,
$msz->urls->format('user-profile', ['user' => $ranking->userId]),
number_format($ranking->postsCount));
}

View file

@ -3,34 +3,28 @@ namespace Misuzu;
use RuntimeException;
$urls = $msz->getUrls();
$forumCtx = $msz->getForumContext();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0;
$postMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
$submissionConfirmed = !empty($_GET['confirm']) && is_string($_GET['confirm']) && $_GET['confirm'] === '1';
$postRequestVerified = CSRF::validateRequest();
$authInfo = $msz->getAuthInfo();
if(!empty($postMode) && !$authInfo->isLoggedIn())
if(!empty($postMode) && !$msz->authInfo->isLoggedIn)
Template::displayInfo('You must be logged in to manage posts.', 401);
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($postMode !== '' && $usersCtx->hasActiveBan($currentUser))
if($postMode !== '' && $msz->usersCtx->hasActiveBan($currentUser))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
try {
$postInfo = $forumPosts->getPost(postId: $postId);
$postInfo = $msz->forumCtx->posts->getPost(postId: $postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$perms = $authInfo->getPerms('forum', $postInfo->getCategoryId());
$perms = $msz->authInfo->getPerms('forum', $postInfo->categoryId);
if(!$perms->check(Perm::F_CATEGORY_VIEW))
Template::throwError(403);
@ -40,48 +34,48 @@ $canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
switch($postMode) {
case 'delete':
if($canDeleteAny) {
if($postInfo->isDeleted())
if($postInfo->deleted)
Template::displayInfo('This post has already been marked as deleted.', 404);
} else {
if($postInfo->isDeleted())
if($postInfo->deleted)
Template::throwError(404);
if(!$perms->check(Perm::F_POST_DELETE_OWN))
Template::displayInfo('You are not allowed to delete posts.', 403);
if($postInfo->getUserId() !== $currentUser->getId())
if($postInfo->userId !== $currentUser->getId())
Template::displayInfo('You can only delete your own posts.', 403);
// posts may only be deleted within a week of creation, this should be a config value
$deleteTimeFrame = 60 * 60 * 24 * 7;
if($postInfo->getCreatedTime() < time() - $deleteTimeFrame)
if($postInfo->createdTime < time() - $deleteTimeFrame)
Template::displayInfo('This post has existed for too long. Ask a moderator to remove if it absolutely necessary.', 403);
}
$originalPostInfo = $forumPosts->getPost(topicInfo: $postInfo->getTopicId());
if($originalPostInfo->getId() === $postInfo->getId())
$originalPostInfo = $msz->forumCtx->posts->getPost(topicInfo: $postInfo->topicId);
if($originalPostInfo->id === $postInfo->id)
Template::displayInfo('This is the opening post of the topic it belongs to, it may not be deleted without deleting the entire topic as well.', 403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
Tools::redirect($msz->urls->format('forum-post', ['post' => $postInfo->id]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete post #%d. Are you sure about that?', $postInfo->getId()),
'message' => sprintf('You are about to delete post #%d. Are you sure about that?', $postInfo->id),
'params' => [
'p' => $postInfo->getId(),
'p' => $postInfo->id,
'm' => 'delete',
],
]);
break;
}
$forumPosts->deletePost($postInfo);
$msz->createAuditLog('FORUM_POST_DELETE', [$postInfo->getId()]);
$msz->forumCtx->posts->deletePost($postInfo);
$msz->createAuditLog('FORUM_POST_DELETE', [$postInfo->id]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
Tools::redirect($msz->urls->format('forum-topic', ['topic' => $postInfo->topicId]));
break;
case 'nuke':
@ -89,25 +83,25 @@ switch($postMode) {
Template::throwError(403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
Tools::redirect($msz->urls->format('forum-post', ['post' => $postInfo->id]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE post #%d. Are you sure about that?', $postInfo->getId()),
'message' => sprintf('You are about to PERMANENTLY DELETE post #%d. Are you sure about that?', $postInfo->id),
'params' => [
'p' => $postInfo->getId(),
'p' => $postInfo->id,
'm' => 'nuke',
],
]);
break;
}
$forumPosts->nukePost($postInfo->getId());
$msz->createAuditLog('FORUM_POST_NUKE', [$postInfo->getId()]);
$msz->forumCtx->posts->nukePost($postInfo->id);
$msz->createAuditLog('FORUM_POST_NUKE', [$postInfo->id]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
Tools::redirect($msz->urls->format('forum-topic', ['topic' => $postInfo->topicId]));
break;
case 'restore':
@ -115,28 +109,28 @@ switch($postMode) {
Template::throwError(403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
Tools::redirect($msz->urls->format('forum-post', ['post' => $postInfo->id]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore post #%d. Are you sure about that?', $postInfo->getId()),
'message' => sprintf('You are about to restore post #%d. Are you sure about that?', $postInfo->id),
'params' => [
'p' => $postInfo->getId(),
'p' => $postInfo->id,
'm' => 'restore',
],
]);
break;
}
$forumPosts->restorePost($postInfo->getId());
$msz->createAuditLog('FORUM_POST_RESTORE', [$postInfo->getId()]);
$msz->forumCtx->posts->restorePost($postInfo->id);
$msz->createAuditLog('FORUM_POST_RESTORE', [$postInfo->id]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
Tools::redirect($msz->urls->format('forum-topic', ['topic' => $postInfo->topicId]));
break;
default: // function as an alt for topic.php?p= by default
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
Tools::redirect($msz->urls->format('forum-post', ['post' => $postInfo->id]));
break;
}

View file

@ -8,19 +8,12 @@ use Misuzu\Parsers\Parser;
use Index\XDateTime;
use Carbon\CarbonImmutable;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(401);
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser->getId();
if($usersCtx->hasActiveBan($currentUser))
if($msz->usersCtx->hasActiveBan($currentUser))
Template::throwError(403);
$forumPostingModes = [
@ -65,16 +58,16 @@ if(empty($postId)) {
$hasPostInfo = false;
} else {
try {
$postInfo = $forumPosts->getPost(postId: $postId);
$postInfo = $msz->forumCtx->posts->getPost(postId: $postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if($postInfo->isDeleted())
if($postInfo->deleted)
Template::throwError(404);
// should automatic cross-quoting be a thing? if so, check if $topicId is < 1 first <-- what did i mean by this?
$topicId = $postInfo->getTopicId();
$topicId = $postInfo->topicId;
$hasPostInfo = true;
}
@ -82,16 +75,16 @@ if(empty($topicId)) {
$hasTopicInfo = false;
} else {
try {
$topicInfo = $forumTopics->getTopic(topicId: $topicId);
$topicInfo = $msz->forumCtx->topics->getTopic(topicId: $topicId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if($topicInfo->isDeleted())
if($topicInfo->deleted)
Template::throwError(404);
$forumId = $topicInfo->getCategoryId();
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
$forumId = $topicInfo->categoryId;
$originalPostInfo = $msz->forumCtx->posts->getPost(topicInfo: $topicInfo);
$hasTopicInfo = true;
}
@ -99,7 +92,7 @@ if(empty($forumId)) {
$hasCategoryInfo = false;
} else {
try {
$categoryInfo = $forumCategories->getCategory(categoryId: $forumId);
$categoryInfo = $msz->forumCtx->categories->getCategory(categoryId: $forumId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -107,16 +100,16 @@ if(empty($forumId)) {
$hasCategoryInfo = true;
}
$perms = $authInfo->getPerms('forum', $categoryInfo);
$perms = $msz->authInfo->getPerms('forum', $categoryInfo);
if($categoryInfo->isArchived()
|| (isset($topicInfo) && $topicInfo->isLocked() && !$perms->check(Perm::F_TOPIC_LOCK))
if($categoryInfo->archived
|| (isset($topicInfo) && $topicInfo->locked && !$perms->check(Perm::F_TOPIC_LOCK))
|| !$perms->check(Perm::F_CATEGORY_VIEW)
|| !$perms->check(Perm::F_POST_CREATE)
|| (!isset($topicInfo) && !$perms->check(Perm::F_TOPIC_CREATE)))
Template::throwError(403);
if(!$categoryInfo->mayHaveTopics())
if(!$categoryInfo->mayHaveTopics)
Template::throwError(400);
$topicTypes = [];
@ -133,7 +126,7 @@ if($mode === 'create' || $mode === 'edit') {
}
// edit mode stuff
if($mode === 'edit' && !$perms->check($postInfo->getUserId() === $currentUserId ? Perm::F_POST_EDIT_OWN : Perm::F_POST_EDIT_ANY))
if($mode === 'edit' && !$perms->check($postInfo->userId === $currentUserId ? Perm::F_POST_EDIT_OWN : Perm::F_POST_EDIT_ANY))
Template::throwError(403);
$notices = [];
@ -148,13 +141,13 @@ if(!empty($_POST)) {
if(!CSRF::validateRequest()) {
$notices[] = 'Could not verify request.';
} else {
$isEditingTopic = empty($topicInfo) || ($mode === 'edit' && $originalPostInfo->getId() == $postInfo->getId());
$isEditingTopic = empty($topicInfo) || ($mode === 'edit' && $originalPostInfo->id == $postInfo->id);
if($mode === 'create') {
$postTimeout = $cfg->getInteger('forum.posting.timeout', 5);
if($postTimeout > 0) {
$postTimeoutThreshold = new CarbonImmutable(sprintf('-%d seconds', $postTimeout));
$lastPostCreatedAt = $forumPosts->getUserLastPostCreatedAt($currentUser);
$lastPostCreatedAt = $msz->forumCtx->posts->getUserLastPostCreatedAt($currentUser);
if(XDateTime::compare($lastPostCreatedAt, $postTimeoutThreshold) > 0) {
$waitSeconds = $postTimeout + ((int)$lastPostCreatedAt->format('U') - time());
@ -166,9 +159,9 @@ if(!empty($_POST)) {
}
if($isEditingTopic) {
$originalTopicTitle = $topicInfo?->getTitle() ?? null;
$originalTopicTitle = $topicInfo?->title ?? null;
$topicTitleChanged = $topicTitle !== $originalTopicTitle;
$originalTopicType = $topicInfo?->getTypeString() ?? 'discussion';
$originalTopicType = $topicInfo?->typeString ?? 'discussion';
$topicTypeChanged = $topicType !== null && $topicType !== $originalTopicType;
$topicTitleLengths = $cfg->getValues([
@ -207,19 +200,19 @@ if(!empty($_POST)) {
switch($mode) {
case 'create':
if(empty($topicInfo)) {
$topicInfo = $forumTopics->createTopic(
$topicInfo = $msz->forumCtx->topics->createTopic(
$categoryInfo,
$currentUser,
$topicTitle,
$topicType
);
$topicId = $topicInfo->getId();
$forumCategories->incrementCategoryTopics($categoryInfo);
$topicId = $topicInfo->id;
$msz->forumCtx->categories->incrementCategoryTopics($categoryInfo);
} else
$forumTopics->bumpTopic($topicInfo);
$msz->forumCtx->topics->bumpTopic($topicInfo);
$postInfo = $forumPosts->createPost(
$postInfo = $msz->forumCtx->posts->createPost(
$topicId,
$currentUser,
$_SERVER['REMOTE_ADDR'],
@ -229,16 +222,16 @@ if(!empty($_POST)) {
$categoryInfo
);
$postId = $postInfo->getId();
$forumCategories->incrementCategoryPosts($categoryInfo);
$postId = $postInfo->id;
$msz->forumCtx->categories->incrementCategoryPosts($categoryInfo);
break;
case 'edit':
$markUpdated = $postInfo->getUserId() === $currentUserId
&& $postInfo->shouldMarkAsEdited()
&& $postText !== $postInfo->getBody();
$markUpdated = $postInfo->userId === $currentUserId
&& $postInfo->shouldMarkAsEdited
&& $postText !== $postInfo->body;
$forumPosts->updatePost(
$msz->forumCtx->posts->updatePost(
$postId,
remoteAddr: $_SERVER['REMOTE_ADDR'],
body: $postText,
@ -248,7 +241,7 @@ if(!empty($_POST)) {
);
if($isEditingTopic && ($topicTitleChanged || $topicTypeChanged))
$forumTopics->updateTopic(
$msz->forumCtx->topics->updateTopic(
$topicId,
title: $topicTitle,
type: $topicType
@ -258,7 +251,7 @@ if(!empty($_POST)) {
if(empty($notices)) {
// does this ternary ever return forum-topic?
$redirect = $msz->getUrls()->format(empty($topicInfo) ? 'forum-topic' : 'forum-post', [
$redirect = $msz->urls->format(empty($topicInfo) ? 'forum-topic' : 'forum-post', [
'topic' => $topicId ?? 0,
'post' => $postId ?? 0,
]);
@ -276,32 +269,32 @@ if($mode === 'edit') { // $post is pretty much sure to be populated at this poin
$post = new stdClass;
$post->info = $postInfo;
if($postInfo->hasUserId()) {
$post->user = $usersCtx->getUserInfo($postInfo->getUserId());
$post->colour = $usersCtx->getUserColour($post->user);
$post->postsCount = $forumCtx->countTotalUserPosts($post->user);
if($postInfo->userId !== null) {
$post->user = $msz->usersCtx->getUserInfo($postInfo->userId);
$post->colour = $msz->usersCtx->getUserColour($post->user);
$post->postsCount = $msz->forumCtx->countTotalUserPosts($post->user);
}
$post->isOriginalPost = $originalPostInfo->getId() == $postInfo->getId();
$post->isOriginalPoster = $originalPostInfo->hasUserId() && $postInfo->hasUserId()
&& $originalPostInfo->getUserId() === $postInfo->getUserId();
$post->isOriginalPost = $originalPostInfo->id == $postInfo->id;
$post->isOriginalPoster = $originalPostInfo->userId !== null && $postInfo->userId !== nul
&& $originalPostInfo->userId === $postInfo->userId;
Template::set('posting_post', $post);
}
try {
$lastPostInfo = $forumPosts->getPost(userInfo: $currentUser, getLast: true, deleted: false);
$selectedParser = $lastPostInfo->getParser();
$lastPostInfo = $msz->forumCtx->posts->getPost(userInfo: $currentUser, getLast: true, deleted: false);
$selectedParser = $lastPostInfo->parser;
} catch(RuntimeException $ex) {
$selectedParser = Parser::BBCODE;
}
Template::render('forum.posting', [
'posting_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($categoryInfo)),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'posting_breadcrumbs' => iterator_to_array($msz->forumCtx->categories->getCategoryAncestry($categoryInfo)),
'global_accent_colour' => $msz->forumCtx->categories->getCategoryColour($categoryInfo),
'posting_user' => $currentUser,
'posting_user_colour' => $usersCtx->getUserColour($currentUser),
'posting_user_posts_count' => $forumCtx->countTotalUserPosts($currentUser),
'posting_user_colour' => $msz->usersCtx->getUserColour($currentUser),
'posting_user_posts_count' => $msz->forumCtx->countTotalUserPosts($currentUser),
'posting_user_preferred_parser' => $selectedParser,
'posting_forum' => $categoryInfo,
'posting_notices' => $notices,

View file

@ -4,40 +4,31 @@ namespace Misuzu;
use stdClass;
use RuntimeException;
$urls = $msz->getUrls();
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumTopicRedirects = $forumCtx->getTopicRedirects();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0;
$topicId = !empty($_GET['t']) && is_string($_GET['t']) ? (int)$_GET['t'] : 0;
$categoryId = null;
$moderationMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
$submissionConfirmed = !empty($_GET['confirm']) && is_string($_GET['confirm']) && $_GET['confirm'] === '1';
$authInfo = $msz->getAuthInfo();
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($topicId < 1 && $postId > 0) {
try {
$postInfo = $forumPosts->getPost(postId: $postId);
$postInfo = $msz->forumCtx->posts->getPost(postId: $postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$categoryId = $postInfo->getCategoryId();
$perms = $authInfo->getPerms('forum', $postInfo->getCategoryId());
$categoryId = (int)$postInfo->categoryId;
$perms = $msz->authInfo->getPerms('forum', $postInfo->categoryId);
$canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
if($postInfo->isDeleted() && !$canDeleteAny)
if($postInfo->deleted && !$canDeleteAny)
Template::throwError(404);
$topicId = $postInfo->getTopicId();
$preceedingPostCount = $forumPosts->countPosts(
$topicId = $postInfo->topicId;
$preceedingPostCount = $msz->forumCtx->posts->countPosts(
topicInfo: $topicId,
upToPostInfo: $postInfo,
deleted: $canDeleteAny ? null : false
@ -46,32 +37,32 @@ if($topicId < 1 && $postId > 0) {
try {
$topicIsNuked = $topicIsDeleted = $canDeleteAny = false;
$topicInfo = $forumTopics->getTopic(topicId: $topicId);
$topicInfo = $msz->forumCtx->topics->getTopic(topicId: $topicId);
} catch(RuntimeException $ex) {
$topicIsNuked = true;
}
if(!$topicIsNuked) {
$topicIsDeleted = $topicInfo->isDeleted();
$topicIsDeleted = $topicInfo->deleted;
if($categoryId !== (int)$topicInfo->getCategoryId()) {
$categoryId = (int)$topicInfo->getCategoryId();
$perms = $authInfo->getPerms('forum', $topicInfo->getCategoryId());
if($categoryId !== (int)$topicInfo->categoryId) {
$categoryId = (int)$topicInfo->categoryId;
$perms = $msz->authInfo->getPerms('forum', $topicInfo->categoryId);
}
if($usersCtx->hasActiveBan($currentUser))
if($msz->usersCtx->hasActiveBan($currentUser))
$perms = $perms->apply(fn($calc) => $calc & (Perm::F_CATEGORY_LIST | Perm::F_CATEGORY_VIEW));
$canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
}
if($topicIsNuked || $topicIsDeleted) {
if($forumTopicRedirects->hasTopicRedirect($topicId)) {
$topicRedirectInfo = $forumTopicRedirects->getTopicRedirect($topicId);
if($msz->forumCtx->topicRedirects->hasTopicRedirect($topicId)) {
$topicRedirectInfo = $msz->forumCtx->topicRedirects->getTopicRedirect($topicId);
Template::set('topic_redir_info', $topicRedirectInfo);
if($topicIsNuked || !$canDeleteAny) {
header('Location: ' . $topicRedirectInfo->getLinkTarget());
header('Location: ' . $topicRedirectInfo->linkTarget);
return;
}
}
@ -87,10 +78,10 @@ if(!$perms->check(Perm::F_CATEGORY_VIEW))
// this should be in the config
$deletePostThreshold = 1;
$categoryInfo = $forumCategories->getCategory(topicInfo: $topicInfo);
$topicIsLocked = $topicInfo->isLocked();
$topicIsArchived = $categoryInfo->isArchived();
$topicPostsTotal = $topicInfo->getTotalPostsCount();
$categoryInfo = $msz->forumCtx->categories->getCategory(topicInfo: $topicInfo);
$topicIsLocked = $topicInfo->locked;
$topicIsArchived = $categoryInfo->archived;
$topicPostsTotal = $topicInfo->totalPostsCount;
$topicIsFrozen = $topicIsArchived || $topicIsDeleted;
$canDeleteOwn = !$topicIsFrozen && !$topicIsLocked && $perms->check(Perm::F_POST_DELETE_OWN);
$canBumpTopic = !$topicIsFrozen && $perms->check(Perm::F_TOPIC_BUMP);
@ -101,7 +92,7 @@ $canDelete = !$topicIsDeleted && (
$topicPostsTotal > 0
&& $topicPostsTotal <= $deletePostThreshold
&& $canDeleteOwn
&& $topicInfo->getUserId() === (string)$currentUserId
&& $topicInfo->userId === (string)$currentUserId
)
);
@ -114,35 +105,34 @@ if(in_array($moderationMode, $validModerationModes, true)) {
if(!CSRF::validateRequest())
Template::displayInfo("Couldn't verify this request, please refresh the page and try again.", 403);
$authInfo = $authInfo;
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::displayInfo('You must be logged in to manage posts.', 401);
if($usersCtx->hasActiveBan($currentUser))
if($msz->usersCtx->hasActiveBan($currentUser))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
switch($moderationMode) {
case 'delete':
if($canDeleteAny) {
if($topicInfo->isDeleted())
if($topicInfo->deleted)
Template::displayInfo('This topic has already been marked as deleted.', 404);
} else {
if($topicInfo->isDeleted())
if($topicInfo->deleted)
Template::throwError(404);
if(!$canDeleteOwn)
Template::displayInfo("You aren't allowed to delete topics.", 403);
if($topicInfo->getUserId() !== $currentUser->getId())
if($topicInfo->userId !== $currentUser->getId())
Template::displayInfo('You can only delete your own topics.', 403);
// topics may only be deleted within a day of creation, this should be a config value
$deleteTimeFrame = 60 * 60 * 24;
if($topicInfo->getCreatedTime() < time() - $deleteTimeFrame)
if($topicInfo->createdTime < time() - $deleteTimeFrame)
Template::displayInfo('This topic has existed for too long. Ask a moderator to remove if it absolutely necessary.', 403);
// deleted posts are intentionally included
$topicPostCount = $forumPosts->countPosts(topicInfo: $topicInfo);
$topicPostCount = $msz->forumCtx->posts->countPosts(topicInfo: $topicInfo);
if($topicPostCount > $deletePostThreshold)
Template::displayInfo('This topic already has replies, you may no longer delete it. Ask a moderator to remove if it absolutely necessary.', 403);
}
@ -151,26 +141,26 @@ if(in_array($moderationMode, $validModerationModes, true)) {
Template::render('forum.confirm', [
'title' => 'Confirm topic deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete topic #%d. Are you sure about that?', $topicInfo->getId()),
'message' => sprintf('You are about to delete topic #%d. Are you sure about that?', $topicInfo->id),
'params' => [
't' => $topicInfo->getId(),
't' => $topicInfo->id,
'm' => 'delete',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format(
Tools::redirect($msz->urls->format(
'forum-topic',
['topic' => $topicInfo->getId()]
['topic' => $topicInfo->id]
));
break;
}
$forumTopics->deleteTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_DELETE', [$topicInfo->getId()]);
$msz->forumCtx->topics->deleteTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_DELETE', [$topicInfo->id]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
Tools::redirect($msz->urls->format('forum-category', [
'forum' => $categoryInfo->id,
]));
break;
@ -182,25 +172,25 @@ if(in_array($moderationMode, $validModerationModes, true)) {
Template::render('forum.confirm', [
'title' => 'Confirm topic restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore topic #%d. Are you sure about that?', $topicInfo->getId()),
'message' => sprintf('You are about to restore topic #%d. Are you sure about that?', $topicInfo->id),
'params' => [
't' => $topicInfo->getId(),
't' => $topicInfo->id,
'm' => 'restore',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
Tools::redirect($msz->urls->format('forum-topic', [
'topic' => $topicInfo->id,
]));
break;
}
$forumTopics->restoreTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_RESTORE', [$topicInfo->getId()]);
$msz->forumCtx->topics->restoreTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_RESTORE', [$topicInfo->id]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
Tools::redirect($msz->urls->format('forum-category', [
'forum' => $categoryInfo->id,
]));
break;
@ -212,67 +202,67 @@ if(in_array($moderationMode, $validModerationModes, true)) {
Template::render('forum.confirm', [
'title' => 'Confirm topic nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE topic #%d. Are you sure about that?', $topicInfo->getId()),
'message' => sprintf('You are about to PERMANENTLY DELETE topic #%d. Are you sure about that?', $topicInfo->id),
'params' => [
't' => $topicInfo->getId(),
't' => $topicInfo->id,
'm' => 'nuke',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
Tools::redirect($msz->urls->format('forum-topic', [
'topic' => $topicInfo->id,
]));
break;
}
$forumTopics->nukeTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_NUKE', [$topicInfo->getId()]);
$msz->forumCtx->topics->nukeTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_NUKE', [$topicInfo->id]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
Tools::redirect($msz->urls->format('forum-category', [
'forum' => $categoryInfo->id,
]));
break;
case 'bump':
if($canBumpTopic) {
$forumTopics->bumpTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_BUMP', [$topicInfo->getId()]);
$msz->forumCtx->topics->bumpTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_BUMP', [$topicInfo->id]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
Tools::redirect($msz->urls->format('forum-topic', [
'topic' => $topicInfo->id,
]));
break;
case 'lock':
if($canLockTopic && !$topicIsLocked) {
$forumTopics->lockTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_LOCK', [$topicInfo->getId()]);
$msz->forumCtx->topics->lockTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_LOCK', [$topicInfo->id]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
Tools::redirect($msz->urls->format('forum-topic', [
'topic' => $topicInfo->id,
]));
break;
case 'unlock':
if($canLockTopic && $topicIsLocked) {
$forumTopics->unlockTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_UNLOCK', [$topicInfo->getId()]);
$msz->forumCtx->topics->unlockTopic($topicInfo->id);
$msz->createAuditLog('FORUM_TOPIC_UNLOCK', [$topicInfo->id]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
Tools::redirect($msz->urls->format('forum-topic', [
'topic' => $topicInfo->id,
]));
break;
}
return;
}
$topicPosts = $topicInfo->getPostsCount();
$topicPosts = $topicInfo->postsCount;
if($canDeleteAny)
$topicPosts += $topicInfo->getDeletedPostsCount();
$topicPosts += $topicInfo->deletedPostsCount;
$topicPagination = new Pagination($topicPosts, 10, 'page');
@ -282,7 +272,7 @@ if(isset($preceedingPostCount))
if(!$topicPagination->hasValidOffset())
Template::throwError(404);
$postInfos = $forumPosts->getPosts(
$postInfos = $msz->forumCtx->posts->getPosts(
topicInfo: $topicInfo,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false,
pagination: $topicPagination,
@ -292,7 +282,7 @@ if(empty($postInfos))
Template::throwError(404);
try {
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
$originalPostInfo = $msz->forumCtx->posts->getPost(topicInfo: $topicInfo);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -303,23 +293,23 @@ foreach($postInfos as $postInfo) {
$posts[] = $post = new stdClass;
$post->info = $postInfo;
if($postInfo->hasUserId()) {
$post->user = $usersCtx->getUserInfo($postInfo->getUserId());
$post->colour = $usersCtx->getUserColour($post->user);
$post->postsCount = $forumCtx->countTotalUserPosts($post->user);
if($postInfo->userId !== null) {
$post->user = $msz->usersCtx->getUserInfo($postInfo->userId);
$post->colour = $msz->usersCtx->getUserColour($post->user);
$post->postsCount = $msz->forumCtx->countTotalUserPosts($post->user);
}
$post->isOriginalPost = $originalPostInfo->getId() == $postInfo->getId();
$post->isOriginalPoster = $originalPostInfo->hasUserId() && $postInfo->hasUserId()
&& $originalPostInfo->getUserId() === $postInfo->getUserId();
$post->isOriginalPost = $originalPostInfo->id == $postInfo->id;
$post->isOriginalPoster = $originalPostInfo->userId !== null && $postInfo->userId !== null
&& $originalPostInfo->userId === $postInfo->userId;
}
$canReply = !$topicIsArchived && !$topicIsLocked && !$topicIsDeleted && $perms->check(Perm::F_POST_CREATE);
if(!$forumTopics->checkUserHasReadTopic($currentUser, $topicInfo))
$forumTopics->incrementTopicViews($topicInfo);
if(!$msz->forumCtx->topics->checkUserHasReadTopic($currentUser, $topicInfo))
$msz->forumCtx->topics->incrementTopicViews($topicInfo);
$forumTopics->updateUserReadTopic($currentUser, $topicInfo);
$msz->forumCtx->topics->updateUserReadTopic($currentUser, $topicInfo);
$perms = $perms->checkMany([
'can_create_post' => Perm::F_POST_CREATE,
@ -330,8 +320,8 @@ $perms = $perms->checkMany([
]);
Template::render('forum.topic', [
'topic_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($topicInfo)),
'global_accent_colour' => $forumCategories->getCategoryColour($topicInfo),
'topic_breadcrumbs' => iterator_to_array($msz->forumCtx->categories->getCategoryAncestry($topicInfo)),
'global_accent_colour' => $msz->forumCtx->categories->getCategoryColour($topicInfo),
'topic_info' => $topicInfo,
'category_info' => $categoryInfo,
'topic_posts' => $posts,

View file

@ -7,28 +7,25 @@ use Misuzu\Changelog\Changelog;
use Carbon\CarbonImmutable;
use Index\{XArray,XDateTime};
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
Template::throwError(403);
$changeActions = [];
foreach(Changelog::ACTIONS as $action)
$changeActions[$action] = Changelog::actionText($action);
$urls = $msz->getUrls();
$changelog = $msz->getChangelog();
$changeId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$changeInfo = null;
$changeTagIds = [];
$tagInfos = $changelog->getTags();
$tagInfos = $msz->changelog->getTags();
if(empty($changeId))
$isNew = true;
else
try {
$isNew = false;
$changeInfo = $changelog->getChange($changeId);
$changeTagIds = XArray::select($changelog->getTags(changeInfo: $changeInfo), fn($tagInfo) => $tagInfo->getId());
$changeInfo = $msz->changelog->getChange($changeId);
$changeTagIds = XArray::select($msz->changelog->getTags(changeInfo: $changeInfo), fn($tagInfo) => $tagInfo->id);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -37,9 +34,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$changelog->deleteChange($changeInfo);
$msz->createAuditLog('CHANGELOG_ENTRY_DELETE', [$changeInfo->getId()]);
Tools::redirect($urls->format('manage-changelog-changes'));
$msz->changelog->deleteChange($changeInfo);
$msz->createAuditLog('CHANGELOG_ENTRY_DELETE', [$changeInfo->id]);
Tools::redirect($msz->urls->format('manage-changelog-changes'));
return;
}
@ -64,20 +61,20 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
}
if($isNew) {
$changeInfo = $changelog->createChange($action, $summary, $body, $userId, $createdAt);
$changeInfo = $msz->changelog->createChange($action, $summary, $body, $userId, $createdAt);
} else {
if($action === $changeInfo->getAction())
if($action === $changeInfo->action)
$action = null;
if($summary === $changeInfo->getSummary())
if($summary === $changeInfo->summary)
$summary = null;
if($body === $changeInfo->getBody())
if($body === $changeInfo->body)
$body = null;
if($createdAt !== null && XDateTime::compare($createdAt, $changeInfo->getCreatedAt()) === 0)
if($createdAt !== null && XDateTime::compare($createdAt, $changeInfo->createdAt) === 0)
$createdAt = null;
$updateUserInfo = $userId !== $changeInfo->getUserId();
$updateUserInfo = $userId !== $changeInfo->userId;
if($action !== null || $summary !== null || $body !== null || $createdAt !== null || $updateUserInfo)
$changelog->updateChange($changeInfo, $action, $summary, $body, $updateUserInfo, $userId, $createdAt);
$msz->changelog->updateChange($changeInfo, $action, $summary, $body, $updateUserInfo, $userId, $createdAt);
}
if(!empty($tags)) {
@ -88,24 +85,24 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
foreach($tCurrent as $tag)
if(!in_array($tag, $tApply)) {
$tRemove[] = $tag;
$changelog->removeTagFromChange($changeInfo, $tag);
$msz->changelog->removeTagFromChange($changeInfo, $tag);
}
$tCurrent = array_diff($tCurrent, $tRemove);
foreach($tApply as $tag)
if(!in_array($tag, $tCurrent)) {
$changelog->addTagToChange($changeInfo, $tag);
$msz->changelog->addTagToChange($changeInfo, $tag);
$tCurrent[] = $tag;
}
}
$msz->createAuditLog(
$isNew ? 'CHANGELOG_ENTRY_CREATE' : 'CHANGELOG_ENTRY_EDIT',
[$changeInfo->getId()]
[$changeInfo->id]
);
Tools::redirect($urls->format('manage-changelog-change', ['change' => $changeInfo->getId()]));
Tools::redirect($msz->urls->format('manage-changelog-change', ['change' => $changeInfo->id]));
return;
}
@ -115,5 +112,5 @@ Template::render('manage.changelog.change', [
'change_info_tags' => $changeTagIds,
'change_tags' => $tagInfos,
'change_actions' => $changeActions,
'change_author_id' => $authInfo->getUserInfo()->getId(),
'change_author_id' => $msz->authInfo->userId,
]);

View file

@ -3,32 +3,28 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
Template::throwError(403);
$changelog = $msz->getChangelog();
$usersCtx = $msz->getUsersContext();
$changelogPagination = new Pagination($changelog->countChanges(), 30);
if(!$changelogPagination->hasValidOffset())
$pagination = new Pagination($msz->changelog->countChanges(), 30);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$changeInfos = $changelog->getChanges(pagination: $changelogPagination);
$changeInfos = $msz->changelog->getChanges(pagination: $pagination);
$changes = [];
foreach($changeInfos as $changeInfo) {
$userInfo = $changeInfo->hasUserId() ? $usersCtx->getUserInfo($changeInfo->getUserId()) : null;
$userInfo = $changeInfo->userId !== null ? $msz->usersCtx->getUserInfo($changeInfo->userId) : null;
$changes[] = [
'change' => $changeInfo,
'tags' => $changelog->getTags(changeInfo: $changeInfo),
'tags' => $msz->changelog->getTags(changeInfo: $changeInfo),
'user' => $userInfo,
'user_colour' => $usersCtx->getUserColour($userInfo),
'user_colour' => $msz->usersCtx->getUserColour($userInfo),
];
}
Template::render('manage.changelog.changes', [
'changelog_changes' => $changes,
'changelog_pagination' => $changelogPagination,
'changelog_pagination' => $pagination,
]);

View file

@ -3,13 +3,11 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$changelog = $msz->getChangelog();
$tagId = (string)filter_input(INPUT_GET, 't', FILTER_SANITIZE_NUMBER_INT);
$loadTagInfo = fn() => $changelog->getTag($tagId);
$loadTagInfo = fn() => $msz->changelog->getTag($tagId);
if(empty($tagId))
$isNew = true;
@ -25,9 +23,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$changelog->deleteTag($tagInfo);
$msz->createAuditLog('CHANGELOG_TAG_DELETE', [$tagInfo->getId()]);
Tools::redirect($urls->format('manage-changelog-tags'));
$msz->changelog->deleteTag($tagInfo);
$msz->createAuditLog('CHANGELOG_TAG_DELETE', [$tagInfo->id]);
Tools::redirect($msz->urls->format('manage-changelog-tags'));
return;
}
@ -37,26 +35,26 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$archive = !empty($_POST['ct_archive']);
if($isNew) {
$tagInfo = $changelog->createTag($name, $description, $archive);
$tagInfo = $msz->changelog->createTag($name, $description, $archive);
} else {
if($name === $tagInfo->getName())
if($name === $tagInfo->name)
$name = null;
if($description === $tagInfo->getDescription())
if($description === $tagInfo->description)
$description = null;
if($archive === $tagInfo->isArchived())
if($archive === $tagInfo->archived)
$archive = null;
if($name !== null || $description !== null || $archive !== null)
$changelog->updateTag($tagInfo, $name, $description, $archive);
$msz->changelog->updateTag($tagInfo, $name, $description, $archive);
}
$msz->createAuditLog(
$isNew ? 'CHANGELOG_TAG_CREATE' : 'CHANGELOG_TAG_EDIT',
[$tagInfo->getId()]
[$tagInfo->id]
);
if($isNew) {
Tools::redirect($urls->format('manage-changelog-tag', ['tag' => $tagInfo->getId()]));
Tools::redirect($msz->urls->format('manage-changelog-tag', ['tag' => $tagInfo->id]));
return;
} else $tagInfo = $loadTagInfo();
break;

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
Template::throwError(403);
Template::render('manage.changelog.tags', [
'changelog_tags' => $msz->getChangelog()->getTags(),
'changelog_tags' => $msz->changelog->getTags(),
]);

View file

@ -3,11 +3,10 @@ namespace Misuzu;
use Misuzu\Perm;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_CATEGORIES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_CATEGORIES_MANAGE))
Template::throwError(403);
$perms = $msz->getPerms();
$permsInfos = $perms->getPermissionInfo(categoryNames: Perm::INFO_FOR_FORUM_CATEGORY);
$permsInfos = $msz->perms->getPermissionInfo(categoryNames: Perm::INFO_FOR_FORUM_CATEGORY);
$permsLists = Perm::createList(Perm::LISTS_FOR_FORUM_CATEGORY);
if(filter_has_var(INPUT_POST, 'perms'))

View file

@ -1,14 +1,9 @@
<?php
namespace Misuzu;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_FORUM_TOPIC_REDIRS_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_TOPIC_REDIRS_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$forumCtx = $msz->getForumContext();
$forumTopicRedirects = $forumCtx->getTopicRedirects();
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(!CSRF::validateRequest())
throw new \Exception("Request verification failed.");
@ -17,8 +12,8 @@ if($_SERVER['REQUEST_METHOD'] === 'POST') {
$rTopicURL = trim((string)filter_input(INPUT_POST, 'topic_redir_url'));
$msz->createAuditLog('FORUM_TOPIC_REDIR_CREATE', [$rTopicId]);
$forumTopicRedirects->createTopicRedirect($rTopicId, $authInfo->getUserInfo(), $rTopicURL);
Tools::redirect($urls->format('manage-forum-topic-redirs'));
$msz->forumCtx->topicRedirects->createTopicRedirect($rTopicId, $msz->authInfo->userInfo, $rTopicURL);
Tools::redirect($msz->urls->format('manage-forum-topic-redirs'));
return;
}
@ -28,16 +23,16 @@ if(filter_input(INPUT_GET, 'm') === 'explode') {
$rTopicId = (string)filter_input(INPUT_GET, 't');
$msz->createAuditLog('FORUM_TOPIC_REDIR_REMOVE', [$rTopicId]);
$forumTopicRedirects->deleteTopicRedirect($rTopicId);
Tools::redirect($urls->format('manage-forum-topic-redirs'));
$msz->forumCtx->topicRedirects->deleteTopicRedirect($rTopicId);
Tools::redirect($msz->urls->format('manage-forum-topic-redirs'));
return;
}
$pagination = new Pagination($forumTopicRedirects->countTopicRedirects(), 20);
$pagination = new Pagination($msz->forumCtx->topicRedirects->countTopicRedirects(), 20);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$redirs = $forumTopicRedirects->getTopicRedirects(pagination: $pagination);
$redirs = $msz->forumCtx->topicRedirects->getTopicRedirects(pagination: $pagination);
Template::render('manage.forum.redirs', [
'manage_redirs' => $redirs,

View file

@ -4,10 +4,9 @@ namespace Misuzu;
use RuntimeException;
use Index\XArray;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
Template::throwError(403);
$emotes = $msz->getEmotes();
$emoteId = (string)filter_input(INPUT_GET, 'e', FILTER_SANITIZE_NUMBER_INT);
$emoteInfo = [];
$emoteStrings = [];
@ -17,8 +16,8 @@ if(empty($emoteId))
else
try {
$isNew = false;
$emoteInfo = $emotes->getEmote($emoteId);
$emoteStrings = iterator_to_array($emotes->getEmoteStrings($emoteInfo));
$emoteInfo = $msz->emotes->getEmote($emoteId);
$emoteStrings = iterator_to_array($msz->emotes->getEmoteStrings($emoteInfo));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -30,8 +29,8 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$url = trim((string)filter_input(INPUT_POST, 'em_url'));
$strings = explode(' ', trim((string)filter_input(INPUT_POST, 'em_strings')));
if($isNew || $url !== $emoteInfo->getUrl()) {
$checkUrl = $emotes->checkEmoteUrl($url);
if($isNew || $url !== $emoteInfo->url) {
$checkUrl = $msz->emotes->checkEmoteUrl($url);
if($checkUrl !== '') {
echo match($checkUrl) {
'empty' => 'URL may not be empty.',
@ -47,36 +46,36 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$order = null;
if($isNew) {
$emoteInfo = $emotes->createEmote($url, $minRank, $order);
$emoteInfo = $msz->emotes->createEmote($url, $minRank, $order);
} else {
if($order === $emoteInfo->getOrder())
if($order === $emoteInfo->order)
$order = null;
if($minRank === $emoteInfo->getMinRank())
if($minRank === $emoteInfo->minRank)
$minRank = null;
if($url === $emoteInfo->getUrl())
if($url === $emoteInfo->url)
$url = null;
if($order !== null || $minRank !== null || $url !== null)
$emotes->updateEmote($emoteInfo, $order, $minRank, $url);
$msz->emotes->updateEmote($emoteInfo, $order, $minRank, $url);
}
$sCurrent = XArray::select($emoteStrings, fn($stringInfo) => $stringInfo->getString());
$sCurrent = XArray::select($emoteStrings, fn($stringInfo) => $stringInfo->string);
$sApply = $strings;
$sRemove = [];
foreach($sCurrent as $string)
if(!in_array($string, $sApply)) {
$sRemove[] = $string;
$emotes->removeEmoteString($string);
$msz->emotes->removeEmoteString($string);
}
$sCurrent = array_diff($sCurrent, $sRemove);
foreach($sApply as $string)
if(!in_array($string, $sCurrent)) {
$checkString = $emotes->checkEmoteString($string);
$checkString = $msz->emotes->checkEmoteString($string);
if($checkString === '') {
$emotes->addEmoteString($emoteInfo, $string);
$msz->emotes->addEmoteString($emoteInfo, $string);
} else {
echo match($checkString) {
'empty' => 'String may not be empty.',
@ -94,10 +93,10 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$msz->createAuditLog(
$isNew ? 'EMOTICON_CREATE' : 'EMOTICON_EDIT',
[$emoteInfo->getId()]
[$emoteInfo->id]
);
Tools::redirect($msz->getUrls()->format('manage-general-emoticon', ['emote' => $emoteInfo->getId()]));
Tools::redirect($msz->urls->format('manage-general-emoticon', ['emote' => $emoteInfo->id]));
return;
}

View file

@ -3,44 +3,42 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
Template::throwError(403);
$emotes = $msz->getEmotes();
if(CSRF::validateRequest() && !empty($_GET['emote'])) {
$emoteId = (string)filter_input(INPUT_GET, 'emote', FILTER_SANITIZE_NUMBER_INT);
try {
$emoteInfo = $emotes->getEmote($emoteId);
$emoteInfo = $msz->emotes->getEmote($emoteId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if(!empty($_GET['delete'])) {
$emotes->deleteEmote($emoteInfo);
$msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->getId()]);
$msz->emotes->deleteEmote($emoteInfo);
$msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->id]);
} else {
if(isset($_GET['order'])) {
$order = filter_input(INPUT_GET, 'order');
$offset = $order === 'i' ? 10 : ($order === 'd' ? -10 : 0);
$emotes->updateEmoteOrderOffset($emoteInfo, $offset);
$msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->getId()]);
$msz->emotes->updateEmoteOrderOffset($emoteInfo, $offset);
$msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->id]);
}
if(isset($_GET['alias'])) {
$alias = (string)filter_input(INPUT_GET, 'alias');
if($emotes->checkEmoteString($alias) === '') {
$emotes->addEmoteString($emoteInfo, $alias);
$msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->getId(), $alias]);
if($msz->emotes->checkEmoteString($alias) === '') {
$msz->emotes->addEmoteString($emoteInfo, $alias);
$msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->id, $alias]);
}
}
}
Tools::redirect($msz->getUrls()->format('manage-general-emoticons'));
Tools::redirect($msz->urls->format('manage-general-emoticons'));
return;
}
Template::render('manage.general.emoticons', [
'emotes' => $emotes->getEmotes(),
'emotes' => $msz->emotes->getEmotes(),
]);

View file

@ -1,8 +1,8 @@
<?php
namespace Misuzu;
$counterInfos = $msz->getCounters()->getCounters(orderBy: 'name');
$counterNamesRaw = $msz->getConfig()->getArray('counters.names');
$counterInfos = $msz->counters->getCounters(orderBy: 'name');
$counterNamesRaw = $msz->config->getArray('counters.names');
$counterNamesCount = count($counterNamesRaw);
$counterNames = [];

View file

@ -3,26 +3,24 @@ namespace Misuzu;
use Misuzu\Pagination;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_LOGS_VIEW))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_LOGS_VIEW))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$auditLog = $msz->getAuditLog();
$pagination = new Pagination($auditLog->countLogs(), 50);
$pagination = new Pagination($msz->auditLog->countLogs(), 50);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$logs = iterator_to_array($auditLog->getLogs(pagination: $pagination));
$logs = iterator_to_array($msz->auditLog->getLogs(pagination: $pagination));
$userInfos = [];
$userColours = [];
foreach($logs as $log)
if($log->hasUserId()) {
$userId = $log->getUserId();
if($log->userId !== null) {
$userId = $log->userId;
if(!array_key_exists($userId, $userInfos)) {
$userInfos[$userId] = $usersCtx->getUserInfo($userId);
$userColours[$userId] = $usersCtx->getUserColour($userId);
$userInfos[$userId] = $msz->usersCtx->getUserInfo($userId);
$userColours[$userId] = $msz->usersCtx->getUserColour($userId);
}
}

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$valueName = (string)filter_input(INPUT_GET, 'name');
@ -13,7 +13,7 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$valueName = $valueInfo->getName();
$msz->createAuditLog('CONFIG_DELETE', [$valueName]);
$cfg->removeValues($valueName);
Tools::redirect($msz->getUrls()->format('manage-general-settings'));
Tools::redirect($msz->urls->format('manage-general-settings'));
return;
}

View file

@ -3,7 +3,7 @@ namespace Misuzu;
use Index\Config\Db\DbConfig;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$isNew = true;
@ -73,7 +73,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$msz->createAuditLog($isNew ? 'CONFIG_CREATE' : 'CONFIG_UPDATE', [$sName]);
$applyFunc($sName, $sValue);
Tools::redirect($msz->getUrls()->format('manage-general-settings'));
Tools::redirect($msz->urls->format('manage-general-settings'));
return;
}

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$hidden = $cfg->getArray('settings.hidden');

View file

@ -1,16 +1,15 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
Template::throwError(403);
$news = $msz->getNews();
$pagination = new Pagination($news->countCategories(), 15);
$pagination = new Pagination($msz->news->countCategories(), 15);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$categories = $news->getCategories(pagination: $pagination);
$categories = $msz->news->getCategories(pagination: $pagination);
Template::render('manage.news.categories', [
'news_categories' => $categories,

View file

@ -3,13 +3,11 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$news = $msz->getNews();
$categoryId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$loadCategoryInfo = fn() => $news->getCategory(categoryId: $categoryId);
$loadCategoryInfo = fn() => $msz->news->getCategory(categoryId: $categoryId);
if(empty($categoryId))
$isNew = true;
@ -25,9 +23,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$news->deleteCategory($categoryInfo);
$msz->createAuditLog('NEWS_CATEGORY_DELETE', [$categoryInfo->getId()]);
Tools::redirect($urls->format('manage-news-categories'));
$msz->news->deleteCategory($categoryInfo);
$msz->createAuditLog('NEWS_CATEGORY_DELETE', [$categoryInfo->id]);
Tools::redirect($msz->urls->format('manage-news-categories'));
return;
}
@ -37,26 +35,26 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$hidden = !empty($_POST['nc_hidden']);
if($isNew) {
$categoryInfo = $news->createCategory($name, $description, $hidden);
$categoryInfo = $msz->news->createCategory($name, $description, $hidden);
} else {
if($name === $categoryInfo->getName())
if($name === $categoryInfo->name)
$name = null;
if($description === $categoryInfo->getDescription())
if($description === $categoryInfo->description)
$description = null;
if($hidden === $categoryInfo->isHidden())
if($hidden === $categoryInfo->hidden)
$hidden = null;
if($name !== null || $description !== null || $hidden !== null)
$news->updateCategory($categoryInfo, $name, $description, $hidden);
$msz->news->updateCategory($categoryInfo, $name, $description, $hidden);
}
$msz->createAuditLog(
$isNew ? 'NEWS_CATEGORY_CREATE' : 'NEWS_CATEGORY_EDIT',
[$categoryInfo->getId()]
[$categoryInfo->id]
);
if($isNew) {
Tools::redirect($urls->format('manage-news-category', ['category' => $categoryInfo->getId()]));
Tools::redirect($msz->urls->format('manage-news-category', ['category' => $categoryInfo->id]));
return;
} else $categoryInfo = $loadCategoryInfo();
break;

View file

@ -3,14 +3,11 @@ namespace Misuzu;
use RuntimeException;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_NEWS_POSTS_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_POSTS_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$news = $msz->getNews();
$postId = (string)filter_input(INPUT_GET, 'p', FILTER_SANITIZE_NUMBER_INT);
$loadPostInfo = fn() => $news->getPost($postId);
$loadPostInfo = fn() => $msz->news->getPost($postId);
if(empty($postId))
$isNew = true;
@ -26,9 +23,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$news->deletePost($postInfo);
$msz->createAuditLog('NEWS_POST_DELETE', [$postInfo->getId()]);
Tools::redirect($urls->format('manage-news-posts'));
$msz->news->deletePost($postInfo);
$msz->createAuditLog('NEWS_POST_DELETE', [$postInfo->id]);
Tools::redirect($msz->urls->format('manage-news-posts'));
return;
}
@ -39,40 +36,40 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$body = trim((string)filter_input(INPUT_POST, 'np_body'));
if($isNew) {
$postInfo = $news->createPost($category, $title, $body, $featured, $authInfo->getUserInfo());
$postInfo = $msz->news->createPost($category, $title, $body, $featured, $msz->authInfo->userInfo);
} else {
if($category === $postInfo->getCategoryId())
if($category === $postInfo->categoryId)
$category = null;
if($title === $postInfo->getTitle())
if($title === $postInfo->title)
$title = null;
if($body === $postInfo->getBody())
if($body === $postInfo->body)
$body = null;
if($featured === $postInfo->isFeatured())
if($featured === $postInfo->featured)
$featured = null;
if($category !== null || $title !== null || $body !== null || $featured !== null)
$news->updatePost($postInfo, $category, $title, $body, $featured);
$msz->news->updatePost($postInfo, $category, $title, $body, $featured);
}
$msz->createAuditLog(
$isNew ? 'NEWS_POST_CREATE' : 'NEWS_POST_EDIT',
[$postInfo->getId()]
[$postInfo->id]
);
if($isNew) {
if($postInfo->isFeatured()) {
if($postInfo->featured) {
// Twitter integration used to be here, replace with Railgun Pulse integration
}
Tools::redirect($urls->format('manage-news-post', ['post' => $postInfo->getId()]));
Tools::redirect($msz->urls->format('manage-news-post', ['post' => $postInfo->id]));
return;
} else $postInfo = $loadPostInfo();
break;
}
$categories = [];
foreach($news->getCategories() as $categoryInfo)
$categories[$categoryInfo->getId()] = $categoryInfo->getName();
foreach($msz->news->getCategories() as $categoryInfo)
$categories[$categoryInfo->id] = $categoryInfo->name;
Template::render('manage.news.post', [
'categories' => $categories,

View file

@ -1,11 +1,10 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_NEWS_POSTS_MANAGE))
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_POSTS_MANAGE))
Template::throwError(403);
$news = $msz->getNews();
$pagination = new Pagination($news->countPosts(
$pagination = new Pagination($msz->news->countPosts(
includeScheduled: true,
includeDeleted: true
), 15);
@ -13,7 +12,7 @@ $pagination = new Pagination($news->countPosts(
if(!$pagination->hasValidOffset())
Template::throwError(404);
$posts = $news->getPosts(
$posts = $msz->news->getPosts(
includeScheduled: true,
includeDeleted: true,
pagination: $pagination

View file

@ -5,37 +5,32 @@ use DateTimeInterface;
use RuntimeException;
use Carbon\CarbonImmutable;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('user')->check(Perm::U_BANS_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_BANS_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$usersCtx = $msz->getUsersContext();
$bans = $usersCtx->getBans();
if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
if(!CSRF::validateRequest())
Template::throwError(403);
try {
$banInfo = $bans->getBan((string)filter_input(INPUT_GET, 'b'));
$banInfo = $msz->usersCtx->bans->getBan((string)filter_input(INPUT_GET, 'b'));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$bans->deleteBans($banInfo);
$msz->createAuditLog('BAN_DELETE', [$banInfo->getId(), $banInfo->getUserId()]);
Tools::redirect($urls->format('manage-users-bans', ['user' => $banInfo->getUserId()]));
$msz->usersCtx->bans->deleteBans($banInfo);
$msz->createAuditLog('BAN_DELETE', [$banInfo->id, $banInfo->userId]);
Tools::redirect($msz->urls->format('manage-users-bans', ['user' => $banInfo->userId]));
return;
}
try {
$userInfo = $usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
$userInfo = $msz->usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$modInfo = $authInfo->getUserInfo();
$modInfo = $msz->authInfo->userInfo;
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$expires = (int)filter_input(INPUT_POST, 'ub_expires', FILTER_SANITIZE_NUMBER_INT);
@ -64,13 +59,13 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
} else
$expires = time() + $expires;
$banInfo = $bans->createBan(
$banInfo = $msz->usersCtx->bans->createBan(
$userInfo, $expires, $publicReason, $privateReason,
severity: $severity, modInfo: $modInfo
);
$msz->createAuditLog('BAN_CREATE', [$banInfo->getId(), $userInfo->getId()]);
Tools::redirect($urls->format('manage-users-bans', ['user' => $userInfo->getId()]));
$msz->createAuditLog('BAN_CREATE', [$banInfo->id, $userInfo->getId()]);
Tools::redirect($msz->urls->format('manage-users-bans', ['user' => $userInfo->getId()]));
return;
}

View file

@ -3,40 +3,37 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_BANS_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_BANS_MANAGE))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$bans = $usersCtx->getBans();
$filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try {
$filterUser = $usersCtx->getUserInfo($filterUserId);
$filterUser = $msz->usersCtx->getUserInfo($filterUserId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
}
$pagination = new Pagination($bans->countBans(userInfo: $filterUser), 10);
$pagination = new Pagination($msz->usersCtx->bans->countBans(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$banList = [];
$banInfos = $bans->getBans(userInfo: $filterUser, activeFirst: true, pagination: $pagination);
$banInfos = $msz->usersCtx->bans->getBans(userInfo: $filterUser, activeFirst: true, pagination: $pagination);
foreach($banInfos as $banInfo) {
$userInfo = $usersCtx->getUserInfo($banInfo->getUserId());
$userColour = $usersCtx->getUserColour($userInfo);
$userInfo = $msz->usersCtx->getUserInfo($banInfo->userId);
$userColour = $msz->usersCtx->getUserColour($userInfo);
if(!$banInfo->hasModId()) {
if($banInfo->modId === null) {
$modInfo = null;
$modColour = null;
} else {
$modInfo = $usersCtx->getUserInfo($banInfo->getModId());
$modColour = $usersCtx->getUserColour($modInfo);
$modInfo = $msz->usersCtx->getUserInfo($banInfo->modId);
$modColour = $msz->usersCtx->getUserColour($modInfo);
}
$banList[] = [

View file

@ -1,29 +1,28 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_USERS_MANAGE))
use Misuzu\Users\Roles;
if(!$msz->authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$pagination = new Pagination($users->countUsers(), 30);
$pagination = new Pagination($msz->usersCtx->users->countUsers(), 30);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$userList = [];
$userInfos = $users->getUsers(pagination: $pagination, orderBy: 'id');
$userInfos = $msz->usersCtx->users->getUsers(pagination: $pagination, orderBy: 'id');
$roleInfos = [];
foreach($userInfos as $userInfo) {
$displayRoleId = $userInfo->getDisplayRoleId() ?? '1';
$displayRoleId = $userInfo->displayRoleId ?? Roles::DEFAULT_ROLE;
if(array_key_exists($displayRoleId, $roleInfos))
$roleInfo = $roleInfos[$displayRoleId];
else
$roleInfos[$displayRoleId] = $roleInfo = $roles->getRole($displayRoleId);
$roleInfos[$displayRoleId] = $roleInfo = $msz->usersCtx->roles->getRole($displayRoleId);
$colour = $userInfo->hasColour() ? $userInfo->getColour() : $roleInfo->getColour();
$colour = $userInfo->hasColour ? $userInfo->colour : $roleInfo->colour;
$userList[] = [
'info' => $userInfo,

View file

@ -3,8 +3,7 @@ namespace Misuzu;
use RuntimeException;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('user')->check(Perm::U_NOTES_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_NOTES_MANAGE))
Template::throwError(403);
$hasNoteId = filter_has_var(INPUT_GET, 'n');
@ -13,25 +12,21 @@ $hasUserId = filter_has_var(INPUT_GET, 'u');
if((!$hasNoteId && !$hasUserId) || ($hasNoteId && $hasUserId))
Template::throwError(400);
$urls = $msz->getUrls();
$usersCtx = $msz->getUsersContext();
$modNotes = $usersCtx->getModNotes();
if($hasUserId) {
$isNew = true;
try {
$userInfo = $usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT));
$userInfo = $msz->usersCtx->getUserInfo(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$authorInfo = $authInfo->getUserInfo();
$authorInfo = $msz->authInfo->userInfo;
} elseif($hasNoteId) {
$isNew = false;
try {
$noteInfo = $modNotes->getNote((string)filter_input(INPUT_GET, 'n', FILTER_SANITIZE_NUMBER_INT));
$noteInfo = $msz->usersCtx->modNotes->getNote((string)filter_input(INPUT_GET, 'n', FILTER_SANITIZE_NUMBER_INT));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -40,14 +35,14 @@ if($hasUserId) {
if(!CSRF::validateRequest())
Template::throwError(403);
$modNotes->deleteNotes($noteInfo);
$msz->createAuditLog('MOD_NOTE_DELETE', [$noteInfo->getId(), $noteInfo->getUserId()]);
Tools::redirect($urls->format('manage-users-notes', ['user' => $noteInfo->getUserId()]));
$msz->usersCtx->modNotes->deleteNotes($noteInfo);
$msz->createAuditLog('MOD_NOTE_DELETE', [$noteInfo->id, $noteInfo->userId]);
Tools::redirect($msz->urls->format('manage-users-notes', ['user' => $noteInfo->userId]));
return;
}
$userInfo = $usersCtx->getUserInfo($noteInfo->getUserId());
$authorInfo = $noteInfo->hasAuthorId() ? $usersCtx->getUserInfo($noteInfo->getAuthorId()) : null;
$userInfo = $msz->usersCtx->getUserInfo($noteInfo->userId);
$authorInfo = $noteInfo->authorId !== null ? $msz->usersCtx->getUserInfo($noteInfo->authorId) : null;
}
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
@ -55,24 +50,24 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$body = trim((string)filter_input(INPUT_POST, 'mn_body'));
if($isNew) {
$noteInfo = $modNotes->createNote($userInfo, $title, $body, $authorInfo);
$noteInfo = $msz->usersCtx->modNotes->createNote($userInfo, $title, $body, $authorInfo);
} else {
if($title === $noteInfo->getTitle())
if($title === $noteInfo->title)
$title = null;
if($body === $noteInfo->getBody())
if($body === $noteInfo->body)
$body = null;
if($title !== null || $body !== null)
$modNotes->updateNote($noteInfo, $title, $body);
$msz->usersCtx->modNotes->updateNote($noteInfo, $title, $body);
}
$msz->createAuditLog(
$isNew ? 'MOD_NOTE_CREATE' : 'MOD_NOTE_UPDATE',
[$noteInfo->getId(), $userInfo->getId()]
[$noteInfo->id, $userInfo->getId()]
);
// this is easier
Tools::redirect($urls->format('manage-users-note', ['note' => $noteInfo->getId()]));
Tools::redirect($msz->urls->format('manage-users-note', ['note' => $noteInfo->id]));
return;
}
@ -80,7 +75,7 @@ Template::render('manage.users.note', [
'note_new' => $isNew,
'note_info' => $noteInfo ?? null,
'note_user' => $userInfo,
'note_user_colour' => $usersCtx->getUserColour($userInfo),
'note_user_colour' => $msz->usersCtx->getUserColour($userInfo),
'note_author' => $authorInfo,
'note_author_colour' => $usersCtx->getUserColour($authorInfo),
'note_author_colour' => $msz->usersCtx->getUserColour($authorInfo),
]);

View file

@ -3,40 +3,37 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_NOTES_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_NOTES_MANAGE))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$modNotes = $usersCtx->getModNotes();
$filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try {
$filterUser = $usersCtx->getUserInfo($filterUserId);
$filterUser = $msz->usersCtx->getUserInfo($filterUserId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
}
$pagination = new Pagination($modNotes->countNotes(userInfo: $filterUser), 10);
$pagination = new Pagination($msz->usersCtx->modNotes->countNotes(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$notes = [];
$noteInfos = $modNotes->getNotes(userInfo: $filterUser, pagination: $pagination);
$noteInfos = $msz->usersCtx->modNotes->getNotes(userInfo: $filterUser, pagination: $pagination);
foreach($noteInfos as $noteInfo) {
$userInfo = $usersCtx->getUserInfo($noteInfo->getUserId());
$userColour = $usersCtx->getUserColour($userInfo);
$userInfo = $msz->usersCtx->getUserInfo($noteInfo->userId);
$userColour = $msz->usersCtx->getUserColour($userInfo);
if(!$noteInfo->hasAuthorId()) {
if($noteInfo->authorId === null) {
$authorInfo = null;
$authorColour = null;
} else {
$authorInfo = $usersCtx->getUserInfo($noteInfo->getAuthorId());
$authorColour = $usersCtx->getUserColour($authorInfo);
$authorInfo = $msz->usersCtx->getUserInfo($noteInfo->authorId);
$authorColour = $msz->usersCtx->getUserColour($authorInfo);
}
$notes[] = [

View file

@ -6,38 +6,33 @@ use Index\Colour\Colour;
use Index\Colour\ColourRgb;
use Misuzu\Perm;
$authInfo = $msz->getAuthInfo();
$viewerPerms = $authInfo->getPerms('user');
$viewerPerms = $msz->authInfo->getPerms('user');
if(!$viewerPerms->check(Perm::U_ROLES_MANAGE))
Template::throwError(403);
$roleInfo = null;
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$perms = $msz->getPerms();
if(filter_has_var(INPUT_GET, 'r')) {
$roleId = (string)filter_input(INPUT_GET, 'r', FILTER_SANITIZE_NUMBER_INT);
try {
$isNew = false;
$roleInfo = $roles->getRole($roleId);
$roleInfo = $msz->usersCtx->roles->getRole($roleId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
} else $isNew = true;
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$canEditPerms = $viewerPerms->check(Perm::U_PERMS_MANAGE);
$permsInfos = $roleInfo === null ? null : $perms->getPermissionInfo(roleInfo: $roleInfo, categoryNames: Perm::INFO_FOR_ROLE);
$permsInfos = $roleInfo === null ? null : $msz->perms->getPermissionInfo(roleInfo: $roleInfo, categoryNames: Perm::INFO_FOR_ROLE);
$permsLists = Perm::createList(Perm::LISTS_FOR_ROLE);
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$userRank = $users->getUserRank($currentUser);
$userRank = $msz->usersCtx->users->getUserRank($currentUser);
if(!$isNew && !$currentUser->isSuperUser() && $roleInfo->getRank() >= $userRank) {
if(!$isNew && !$currentUser->super && $roleInfo->rank >= $userRank) {
echo 'You aren\'t allowed to edit this role.';
break;
}
@ -68,7 +63,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
'role_ur_col_blue' => $colourBlue,
]);
if(!$currentUser->isSuperUser() && $roleRank >= $userRank) {
if(!$currentUser->super && $roleRank >= $userRank) {
echo 'You aren\'t allowed to make a role with equal rank to your own.';
break;
}
@ -108,7 +103,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
}
if($isNew) {
$roleInfo = $roles->createRole(
$roleInfo = $msz->usersCtx->roles->createRole(
$roleName,
$roleRank,
$roleColour,
@ -119,25 +114,25 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
leavable: $roleLeavable
);
} else {
if($roleName === $roleInfo->getName())
if($roleName === $roleInfo->name)
$roleName = null;
if($roleString === $roleInfo->getString())
if($roleString === $roleInfo->string)
$roleString = null;
if($roleHide === $roleInfo->isHidden())
if($roleHide === $roleInfo->hidden)
$roleHide = null;
if($roleLeavable === $roleInfo->isLeavable())
if($roleLeavable === $roleInfo->leavable)
$roleLeavable = null;
if($roleRank === $roleInfo->getRank())
if($roleRank === $roleInfo->rank)
$roleRank = null;
if($roleTitle === $roleInfo->getTitle())
if($roleTitle === $roleInfo->title)
$roleTitle = null;
if($roleDesc === $roleInfo->getDescription())
if($roleDesc === $roleInfo->description)
$roleDesc = null;
// local genius did not implement colour comparison
if((string)$roleColour === (string)$roleInfo->getColour())
if((string)$roleColour === (string)$roleInfo->colour)
$roleColour = null;
$roles->updateRole(
$msz->usersCtx->roles->updateRole(
$roleInfo,
string: $roleString,
name: $roleName,
@ -152,7 +147,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$msz->createAuditLog(
$isNew ? 'ROLE_CREATE' : 'ROLE_UPDATE',
[$roleInfo->getId()]
[$roleInfo->id]
);
if($canEditPerms && filter_has_var(INPUT_POST, 'perms')) {
@ -162,13 +157,13 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
);
foreach($permsApply as $categoryName => $values)
$perms->setPermissions($categoryName, $values['allow'], $values['deny'], roleInfo: $roleInfo);
$msz->perms->setPermissions($categoryName, $values['allow'], $values['deny'], roleInfo: $roleInfo);
// could target all users with the role but ech
$msz->getConfig()->setBoolean('perms.needsRecalc', true);
$msz->config->setBoolean('perms.needsRecalc', true);
}
Tools::redirect($msz->getUrls()->format('manage-role', ['role' => $roleInfo->getId()]));
Tools::redirect($msz->urls->format('manage-role', ['role' => $roleInfo->id]));
return;
}

View file

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

View file

@ -7,18 +7,11 @@ use Misuzu\Perm;
use Misuzu\Auth\AuthTokenCookie;
use Misuzu\Users\User;
$authInfo = $msz->getAuthInfo();
$viewerPerms = $authInfo->getPerms('user');
if(!$authInfo->isLoggedIn())
$viewerPerms = $msz->authInfo->getPerms('user');
if(!$msz->authInfo->isLoggedIn)
Template::throwError(403);
$urls = $msz->getUrls();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$perms = $msz->getPerms();
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$canManageUsers = $viewerPerms->check(Perm::U_USERS_MANAGE);
$canManagePerms = $viewerPerms->check(Perm::U_PERMS_MANAGE);
@ -26,7 +19,7 @@ $canManageNotes = $viewerPerms->check(Perm::U_NOTES_MANAGE);
$canManageWarnings = $viewerPerms->check(Perm::U_WARNINGS_MANAGE);
$canManageBans = $viewerPerms->check(Perm::U_BANS_MANAGE);
$canImpersonate = $viewerPerms->check(Perm::U_CAN_IMPERSONATE);
$canSendTestMail = $currentUser->isSuperUser();
$canSendTestMail = $currentUser->super;
$hasAccess = $canManageUsers || $canManageNotes || $canManageWarnings || $canManageBans;
if(!$hasAccess)
@ -36,18 +29,18 @@ $notices = [];
$userId = (int)filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try {
$userInfo = $users->getUser($userId, 'id');
$userInfo = $msz->usersCtx->users->getUser($userId, 'id');
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$currentUserRank = $users->getUserRank($currentUser);
$userRank = $users->getUserRank($userInfo);
$currentUserRank = $msz->usersCtx->users->getUserRank($currentUser);
$userRank = $msz->usersCtx->users->getUserRank($userInfo);
$canEdit = $canManageUsers && ($currentUser->isSuperUser() || (string)$currentUser->getId() === $userInfo->getId() || $currentUserRank > $userRank);
$canEdit = $canManageUsers && ($currentUser->super || (string)$currentUser->getId() === $userInfo->getId() || $currentUserRank > $userRank);
$canEditPerms = $canEdit && $canManagePerms;
$permsInfos = $perms->getPermissionInfo(userInfo: $userInfo, categoryNames: Perm::INFO_FOR_USER);
$permsInfos = $msz->perms->getPermissionInfo(userInfo: $userInfo, categoryNames: Perm::INFO_FOR_USER);
$permsLists = Perm::createList(Perm::LISTS_FOR_USER);
$permsNeedRecalc = false;
@ -58,22 +51,22 @@ if(CSRF::validateRequest() && $canEdit) {
} elseif(!is_string($_POST['impersonate_user']) || $_POST['impersonate_user'] !== 'meow') {
$notices[] = 'You didn\'t say the magic word.';
} else {
$allowToImpersonate = $currentUser->isSuperUser();
$allowToImpersonate = $currentUser->super;
if(!$allowToImpersonate) {
$allowImpersonateUsers = $msz->getConfig()->getArray(sprintf('impersonate.allow.u%s', $currentUser->getId()));
$allowImpersonateUsers = $msz->config->getArray(sprintf('impersonate.allow.u%s', $currentUser->getId()));
$allowToImpersonate = in_array($userInfo->getId(), $allowImpersonateUsers, true);
}
if($allowToImpersonate) {
$msz->createAuditLog('USER_IMPERSONATE', [$userInfo->getId(), $userInfo->getName()]);
$msz->createAuditLog('USER_IMPERSONATE', [$userInfo->getId(), $userInfo->name]);
$tokenBuilder = $authInfo->getTokenInfo()->toBuilder();
$tokenBuilder = $msz->authInfo->tokenInfo->toBuilder();
$tokenBuilder->setImpersonatedUserId($userInfo->getId());
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
Tools::redirect($urls->format('index'));
Tools::redirect($msz->urls->format('index'));
return;
} else $notices[] = 'You aren\'t allowed to impersonate this user.';
}
@ -86,7 +79,7 @@ if(CSRF::validateRequest() && $canEdit) {
$notices[] = 'Invalid request thing shut the fuck up.';
} else {
$testMail = Mailer::sendMessage(
[$userInfo->getEMailAddress() => $userInfo->getName()],
[$userInfo->emailAddress => $userInfo->name],
'Flashii Test E-mail',
'You were sent this e-mail to validate if you can receive e-mails from Flashii. You may discard it.'
);
@ -106,13 +99,13 @@ if(CSRF::validateRequest() && $canEdit) {
}
$existingRoles = [];
foreach(iterator_to_array($roles->getRoles(userInfo: $userInfo)) as $roleInfo)
$existingRoles[$roleInfo->getId()] = $roleInfo;
foreach(iterator_to_array($msz->usersCtx->roles->getRoles(userInfo: $userInfo)) as $roleInfo)
$existingRoles[$roleInfo->id] = $roleInfo;
$removeRoles = [];
foreach($existingRoles as $roleInfo) {
if($roleInfo->isDefault() || !($currentUser->isSuperUser() || $userRank > $roleInfo->getRank()))
if($roleInfo->default || !($currentUser->super || $userRank > $roleInfo->rank))
continue;
if(!in_array($roleInfo->getId(), $applyRoles))
@ -120,18 +113,18 @@ if(CSRF::validateRequest() && $canEdit) {
}
if(!empty($removeRoles))
$users->removeRoles($userInfo, $removeRoles);
$msz->usersCtx->users->removeRoles($userInfo, $removeRoles);
$addRoles = [];
foreach($applyRoles as $roleId) {
try {
$roleInfo = $existingRoles[$roleId] ?? $roles->getRole($roleId);
$roleInfo = $existingRoles[$roleId] ?? $msz->usersCtx->roles->getRole($roleId);
} catch(RuntimeException $ex) {
continue;
}
if(!$currentUser->isSuperUser() && $userRank <= $roleInfo->getRank())
if(!$currentUser->super && $userRank <= $roleInfo->rank)
continue;
if(!in_array($roleInfo, $existingRoles))
@ -139,7 +132,7 @@ if(CSRF::validateRequest() && $canEdit) {
}
if(!empty($addRoles))
$users->addRoles($userInfo, $addRoles);
$msz->usersCtx->users->addRoles($userInfo, $addRoles);
if(!empty($addRoles) || !empty($removeRoles))
$permsNeedRecalc = true;
@ -150,7 +143,7 @@ if(CSRF::validateRequest() && $canEdit) {
$setTitle = (string)($_POST['user']['title'] ?? '');
$displayRole = (string)($_POST['user']['display_role'] ?? 0);
if(!$users->hasRole($userInfo, $displayRole))
if(!$msz->usersCtx->users->hasRole($userInfo, $displayRole))
$notices[] = 'User does not have the role you\'re trying to assign as primary.';
$countryValidation = strlen($setCountry) === 2
@ -164,7 +157,7 @@ if(CSRF::validateRequest() && $canEdit) {
$notices[] = 'User title was invalid.';
if(empty($notices)) {
$users->updateUser(
$msz->usersCtx->users->updateUser(
userInfo: $userInfo,
displayRoleInfo: $displayRole,
countryCode: (string)($_POST['user']['country'] ?? 'XX'),
@ -183,7 +176,7 @@ if(CSRF::validateRequest() && $canEdit) {
}
if(empty($notices))
$users->updateUser(userInfo: $userInfo, colour: $setColour);
$msz->usersCtx->users->updateUser(userInfo: $userInfo, colour: $setColour);
}
if(!empty($_POST['password']) && is_array($_POST['password'])) {
@ -194,13 +187,13 @@ if(CSRF::validateRequest() && $canEdit) {
if($passwordNewValue !== $passwordConfirmValue)
$notices[] = 'Confirm password does not match.';
else {
$passwordValidation = $users->validatePassword($passwordNewValue);
$passwordValidation = $msz->usersCtx->users->validatePassword($passwordNewValue);
if($passwordValidation !== '')
$notices[] = $users->validatePasswordText($passwordValidation);
$notices[] = $msz->usersCtx->users->validatePasswordText($passwordValidation);
}
if(empty($notices))
$users->updateUser(userInfo: $userInfo, password: $passwordNewValue);
$msz->usersCtx->users->updateUser(userInfo: $userInfo, password: $passwordNewValue);
}
}
@ -211,23 +204,23 @@ if(CSRF::validateRequest() && $canEdit) {
);
foreach($permsApply as $categoryName => $values)
$perms->setPermissions($categoryName, $values['allow'], $values['deny'], userInfo: $userInfo);
$msz->perms->setPermissions($categoryName, $values['allow'], $values['deny'], userInfo: $userInfo);
$permsNeedRecalc = true;
}
if($permsNeedRecalc)
$perms->precalculatePermissions(
$msz->getForumContext()->getCategories(),
$msz->perms->precalculatePermissions(
$msz->forumCtx->categories,
[$userInfo->getId()]
);
Tools::redirect($urls->format('manage-user', ['user' => $userInfo->getId()]));
Tools::redirect($msz->urls->format('manage-user', ['user' => $userInfo->getId()]));
return;
}
$rolesAll = iterator_to_array($roles->getRoles());
$userRoleIds = $users->hasRoles($userInfo, $rolesAll);
$rolesAll = iterator_to_array($msz->usersCtx->roles->getRoles());
$userRoleIds = $msz->usersCtx->users->hasRoles($userInfo, $rolesAll);
Template::render('manage.users.user', [
'user_info' => $userInfo,

View file

@ -3,49 +3,43 @@ namespace Misuzu;
use RuntimeException;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
Template::throwError(403);
$urls = $msz->getUrls();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$warns = $usersCtx->getWarnings();
if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
if(!CSRF::validateRequest())
Template::throwError(403);
try {
$warnInfo = $warns->getWarning((string)filter_input(INPUT_GET, 'w'));
$warnInfo = $msz->usersCtx->warnings->getWarning((string)filter_input(INPUT_GET, 'w'));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$warns->deleteWarnings($warnInfo);
$msz->createAuditLog('WARN_DELETE', [$warnInfo->getId(), $warnInfo->getUserId()]);
Tools::redirect($urls->format('manage-users-warnings', ['user' => $warnInfo->getUserId()]));
$msz->usersCtx->warnings->deleteWarnings($warnInfo);
$msz->createAuditLog('WARN_DELETE', [$warnInfo->id, $warnInfo->userId]);
Tools::redirect($msz->urls->format('manage-users-warnings', ['user' => $warnInfo->userId]));
return;
}
try {
$userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
$userInfo = $msz->usersCtx->users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$modInfo = $authInfo->getUserInfo();
$modInfo = $msz->authInfo->userInfo;
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$body = trim((string)filter_input(INPUT_POST, 'uw_body'));
Template::set('warn_value_body', $body);
$warnInfo = $warns->createWarning(
$warnInfo = $msz->usersCtx->warnings->createWarning(
$userInfo, $body, modInfo: $modInfo
);
$msz->createAuditLog('WARN_CREATE', [$warnInfo->getId(), $userInfo->getId()]);
Tools::redirect($urls->format('manage-users-warnings', ['user' => $userInfo->getId()]));
$msz->createAuditLog('WARN_CREATE', [$warnInfo->id, $userInfo->getId()]);
Tools::redirect($msz->urls->format('manage-users-warnings', ['user' => $userInfo->getId()]));
return;
}

View file

@ -3,40 +3,37 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
if(!$msz->authInfo->getPerms('user')->check(Perm::U_WARNINGS_MANAGE))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$warns = $usersCtx->getWarnings();
$filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) {
$filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
try {
$filterUser = $usersCtx->getUserInfo($filterUserId);
$filterUser = $msz->usersCtx->getUserInfo($filterUserId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
}
$pagination = new Pagination($warns->countWarnings(userInfo: $filterUser), 10);
$pagination = new Pagination($msz->usersCtx->warnings->countWarnings(userInfo: $filterUser), 10);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$warnList = [];
$warnInfos = $warns->getWarnings(userInfo: $filterUser, pagination: $pagination);
$warnInfos = $msz->usersCtx->warnings->getWarnings(userInfo: $filterUser, pagination: $pagination);
foreach($warnInfos as $warnInfo) {
$userInfo = $usersCtx->getUserInfo($warnInfo->getUserId());
$userColour = $usersCtx->getUserColour($userInfo);
$userInfo = $msz->usersCtx->getUserInfo($warnInfo->userId);
$userColour = $msz->usersCtx->getUserColour($userInfo);
if(!$warnInfo->hasModId()) {
if($warnInfo->modId === null) {
$modInfo = null;
$modColour = null;
} else {
$modInfo = $usersCtx->getUserInfo($warnInfo->getModId());
$modColour = $usersCtx->getUserColour($modInfo);
$modInfo = $msz->usersCtx->getUserInfo($warnInfo->modId);
$modColour = $msz->usersCtx->getUserColour($modInfo);
}
$warnList[] = [

View file

@ -3,17 +3,11 @@ namespace Misuzu;
use RuntimeException;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(403);
// TODO: restore forum-topics and forum-posts orderings
$forumCtx = $msz->getForumContext();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$roleId = filter_has_var(INPUT_GET, 'r') ? (string)filter_input(INPUT_GET, 'r') : null;
$orderBy = strtolower((string)filter_input(INPUT_GET, 'ss'));
$orderDir = strtolower((string)filter_input(INPUT_GET, 'sd'));
@ -66,7 +60,7 @@ if(empty($orderDir)) {
}
if($roleId === null) {
$roleInfo = $roles->getDefaultRole();
$roleInfo = $msz->usersCtx->roles->getDefaultRole();
} else {
try {
$roleInfo = $roles->getRole($roleId);
@ -75,14 +69,14 @@ if($roleId === null) {
}
}
$canManageUsers = $authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE);
$canManageUsers = $msz->authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE);
$deleted = $canManageUsers ? null : false;
$rolesAll = $roles->getRoles(hidden: false);
$pagination = new Pagination($users->countUsers(roleInfo: $roleInfo, deleted: $deleted), 15);
$rolesAll = $msz->usersCtx->roles->getRoles(hidden: false);
$pagination = new Pagination($msz->usersCtx->users->countUsers(roleInfo: $roleInfo, deleted: $deleted), 15);
$userList = [];
$userInfos = $users->getUsers(
$userInfos = $msz->usersCtx->users->getUsers(
roleInfo: $roleInfo,
deleted: $deleted,
orderBy: $orderBy,
@ -93,9 +87,9 @@ $userInfos = $users->getUsers(
foreach($userInfos as $userInfo)
$userList[] = [
'info' => $userInfo,
'colour' => $usersCtx->getUserColour($userInfo),
'ftopics' => $forumCtx->countTotalUserTopics($userInfo),
'fposts' => $forumCtx->countTotalUserPosts($userInfo),
'colour' => $msz->usersCtx->getUserColour($userInfo),
'ftopics' => $msz->forumCtx->countTotalUserTopics($userInfo),
'fposts' => $msz->forumCtx->countTotalUserPosts($userInfo),
];
if(empty($userList))

View file

@ -14,21 +14,12 @@ $userId = !empty($_GET['u']) && is_string($_GET['u']) ? trim($_GET['u']) : 0;
$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);
$urls = $msz->getUrls();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$authInfo = $msz->getAuthInfo();
$viewerInfo = $authInfo->getUserInfo();
$viewerInfo = $msz->authInfo->userInfo;
$viewingAsGuest = $viewerInfo === null;
$viewerId = $viewingAsGuest ? '0' : $viewerInfo->getId();
try {
$userInfo = $usersCtx->getUserInfo($userId, 'profile');
$userInfo = $msz->usersCtx->getUserInfo($userId, 'profile');
} catch(RuntimeException $ex) {
http_response_code(404);
Template::render('profile.index', [
@ -39,7 +30,7 @@ try {
return;
}
if($userInfo->isDeleted()) {
if($userInfo->deleted) {
http_response_code(404);
Template::render('profile.index', [
'profile_is_guest' => $viewingAsGuest,
@ -54,11 +45,11 @@ switch($profileMode) {
Template::throwError(404);
case 'forum-topics':
Tools::redirect($urls->format('search-query', ['query' => sprintf('type:forum:topic author:%s', $userInfo->getName()), 'section' => 'topics']));
Tools::redirect($msz->urls->format('search-query', ['query' => sprintf('type:forum:topic author:%s', $userInfo->name), 'section' => 'topics']));
return;
case 'forum-posts':
Tools::redirect($urls->format('search-query', ['query' => sprintf('type:forum:post author:%s', $userInfo->getName()), 'section' => 'posts']));
Tools::redirect($msz->urls->format('search-query', ['query' => sprintf('type:forum:post author:%s', $userInfo->name), 'section' => 'posts']));
return;
case '':
@ -67,18 +58,17 @@ switch($profileMode) {
$notices = [];
$userRank = $usersCtx->getUserRank($userInfo);
$viewerRank = $usersCtx->getUserRank($viewerInfo);
$userRank = $msz->usersCtx->getUserRank($userInfo);
$viewerRank = $msz->usersCtx->getUserRank($viewerInfo);
$viewerPermsGlobal = $authInfo->getPerms('global');
$viewerPermsUser = $authInfo->getPerms('user');
$viewerPermsGlobal = $msz->authInfo->getPerms('global');
$viewerPermsUser = $msz->authInfo->getPerms('user');
$activeBanInfo = $usersCtx->tryGetActiveBan($userInfo);
$activeBanInfo = $msz->usersCtx->tryGetActiveBan($userInfo);
$isBanned = $activeBanInfo !== null;
$profileFields = $msz->getProfileFields();
$viewingOwnProfile = (string)$viewerId === $userInfo->getId();
$canManageWarnings = $viewerPermsUser->check(Perm::U_WARNINGS_MANAGE);
$canEdit = !$viewingAsGuest && ((!$isBanned && $viewingOwnProfile) || $viewerInfo->isSuperUser() || (
$canEdit = !$viewingAsGuest && ((!$isBanned && $viewingOwnProfile) || $viewerInfo->super || (
$viewerPermsUser->check(Perm::U_USERS_MANAGE) && ($viewingOwnProfile || $viewerRank > $userRank)
));
$avatarInfo = new UserAvatarAsset($userInfo);
@ -112,13 +102,13 @@ if($isEditing) {
if(!$perms->edit_profile) {
$notices[] = 'You\'re not allowed to edit your profile';
} else {
$profileFieldInfos = iterator_to_array($profileFields->getFields());
$profileFieldInfos = iterator_to_array($msz->profileFields->getFields());
$profileFieldsSetInfos = [];
$profileFieldsSetValues = [];
$profileFieldsRemove = [];
foreach($profileFieldInfos as $fieldInfo) {
$fieldName = $fieldInfo->getName();
$fieldName = $fieldInfo->name;
$fieldValue = empty($profileFieldsSubmit[$fieldName]) ? '' : (string)filter_var($profileFieldsSubmit[$fieldName]);
if(empty($profileFieldsSubmit[$fieldName])) {
@ -130,15 +120,15 @@ if($isEditing) {
$profileFieldsSetInfos[] = $fieldInfo;
$profileFieldsSetValues[] = $fieldValue;
} else
$notices[] = sprintf('%s isn\'t properly formatted.', $fieldInfo->getTitle());
$notices[] = sprintf('%s isn\'t properly formatted.', $fieldInfo->title);
unset($fieldName, $fieldValue, $fieldInfo);
}
if(!empty($profileFieldsRemove))
$profileFields->removeFieldValues($userInfo, $profileFieldsRemove);
$msz->profileFields->removeFieldValues($userInfo, $profileFieldsRemove);
if(!empty($profileFieldsSetInfos))
$profileFields->setFieldValues($userInfo, $profileFieldsSetInfos, $profileFieldsSetValues);
$msz->profileFields->setFieldValues($userInfo, $profileFieldsSetInfos, $profileFieldsSetValues);
}
}
@ -148,12 +138,12 @@ if($isEditing) {
} else {
$aboutText = (string)($_POST['about']['text'] ?? '');
$aboutParse = (int)($_POST['about']['parser'] ?? Parser::PLAIN);
$aboutValid = $users->validateProfileAbout($aboutParse, $aboutText);
$aboutValid = $msz->usersCtx->users->validateProfileAbout($aboutParse, $aboutText);
if($aboutValid === '')
$users->updateUser($userInfo, aboutContent: $aboutText, aboutParser: $aboutParse);
$msz->usersCtx->users->updateUser($userInfo, aboutBody: $aboutText, aboutBodyParser: $aboutParse);
else
$notices[] = $users->validateProfileAboutText($aboutValid);
$notices[] = $msz->usersCtx->users->validateProfileAboutText($aboutValid);
}
}
@ -163,12 +153,12 @@ if($isEditing) {
} else {
$sigText = (string)($_POST['signature']['text'] ?? '');
$sigParse = (int)($_POST['signature']['parser'] ?? Parser::PLAIN);
$sigValid = $users->validateForumSignature($sigParse, $sigText);
$sigValid = $msz->usersCtx->users->validateForumSignature($sigParse, $sigText);
if($sigValid === '')
$users->updateUser($userInfo, signatureContent: $sigText, signatureParser: $sigParse);
$msz->usersCtx->users->updateUser($userInfo, signatureBody: $sigText, signatureBodyParser: $sigParse);
else
$notices[] = $users->validateForumSignatureText($sigValid);
$notices[] = $msz->usersCtx->users->validateForumSignatureText($sigValid);
}
}
@ -179,12 +169,12 @@ if($isEditing) {
$birthYear = (int)($_POST['birthdate']['year'] ?? 0);
$birthMonth = (int)($_POST['birthdate']['month'] ?? 0);
$birthDay = (int)($_POST['birthdate']['day'] ?? 0);
$birthValid = $users->validateBirthdate($birthYear, $birthMonth, $birthDay);
$birthValid = $msz->usersCtx->users->validateBirthdate($birthYear, $birthMonth, $birthDay);
if($birthValid === '')
$users->updateUser($userInfo, birthYear: $birthYear, birthMonth: $birthMonth, birthDay: $birthDay);
$msz->usersCtx->users->updateUser($userInfo, birthYear: $birthYear, birthMonth: $birthMonth, birthDay: $birthDay);
else
$notices[] = $users->validateBirthdateText($birthValid);
$notices[] = $msz->usersCtx->users->validateBirthdateText($birthValid);
}
}
@ -281,7 +271,7 @@ if($isEditing) {
}
}
$users->updateUser($userInfo, backgroundSettings: $backgroundInfo->getSettings());
$msz->usersCtx->users->updateUser($userInfo, backgroundSettings: $backgroundInfo->getSettings());
}
}
@ -293,12 +283,12 @@ if($isEditing) {
// TODO: create user counters so these can be statically kept
$profileStats = new stdClass;
$profileStats->forum_topic_count = $forumCtx->countTotalUserTopics($userInfo);
$profileStats->forum_post_count = $forumCtx->countTotalUserPosts($userInfo);
$profileStats->comments_count = $msz->getComments()->countPosts(userInfo: $userInfo, deleted: false);
$profileStats->forum_topic_count = $msz->forumCtx->countTotalUserTopics($userInfo);
$profileStats->forum_post_count = $msz->forumCtx->countTotalUserPosts($userInfo);
$profileStats->comments_count = $msz->comments->countPosts(userInfo: $userInfo, deleted: false);
if(!$viewingAsGuest) {
Template::set('profile_warnings', iterator_to_array($usersCtx->getWarnings()->getWarningsWithDefaultBacklog($userInfo)));
Template::set('profile_warnings', iterator_to_array($msz->usersCtx->warnings->getWarningsWithDefaultBacklog($userInfo)));
if((!$isBanned || $canEdit)) {
$unranked = $cfg->getValues([
@ -306,25 +296,25 @@ if(!$viewingAsGuest) {
'forum_leader.unranked.topic:a',
]);
$activeCategoryStats = $forumCategories->getMostActiveCategoryInfo(
$activeCategoryStats = $msz->forumCtx->categories->getMostActiveCategoryInfo(
$userInfo,
$unranked['forum_leader.unranked.forum'],
$unranked['forum_leader.unranked.topic'],
deleted: false
);
$activeCategoryInfo = $activeCategoryStats->success ? $forumCategories->getCategory(categoryId: $activeCategoryStats->categoryId) : null;
$activeCategoryInfo = $activeCategoryStats->success ? $msz->forumCtx->categories->getCategory(categoryId: $activeCategoryStats->categoryId) : null;
$activeTopicStats = $forumTopics->getMostActiveTopicInfo(
$activeTopicStats = $msz->forumCtx->topics->getMostActiveTopicInfo(
$userInfo,
$unranked['forum_leader.unranked.forum'],
$unranked['forum_leader.unranked.topic'],
deleted: false
);
$activeTopicInfo = $activeTopicStats->success ? $forumTopics->getTopic(topicId: $activeTopicStats->topicId) : null;
$activeTopicInfo = $activeTopicStats->success ? $msz->forumCtx->topics->getTopic(topicId: $activeTopicStats->topicId) : null;
$profileFieldValues = iterator_to_array($profileFields->getFieldValues($userInfo));
$profileFieldInfos = $profileFieldInfos ?? iterator_to_array($profileFields->getFields(fieldValueInfos: $isEditing ? null : $profileFieldValues));
$profileFieldFormats = iterator_to_array($profileFields->getFieldFormats(fieldValueInfos: $profileFieldValues));
$profileFieldValues = iterator_to_array($msz->profileFields->getFieldValues($userInfo));
$profileFieldInfos = $profileFieldInfos ?? iterator_to_array($msz->profileFields->getFields(fieldValueInfos: $isEditing ? null : $profileFieldValues));
$profileFieldFormats = iterator_to_array($msz->profileFields->getFieldFormats(fieldValueInfos: $profileFieldValues));
$profileFieldRawValues = [];
$profileFieldLinkValues = [];
@ -335,24 +325,24 @@ if(!$viewingAsGuest) {
unset($fieldValue);
foreach($profileFieldValues as $fieldValueTest)
if($fieldValueTest->getFieldId() === $fieldInfo->getId()) {
if($fieldValueTest->fieldId === $fieldInfo->id) {
$fieldValue = $fieldValueTest;
break;
}
$fieldName = $fieldInfo->getName();
$fieldName = $fieldInfo->name;
if(isset($fieldValue)) {
foreach($profileFieldFormats as $fieldFormatTest)
if($fieldFormatTest->getId() === $fieldValue->getFormatId()) {
if($fieldFormatTest->id === $fieldValue->formatId) {
$fieldFormat = $fieldFormatTest;
break;
}
$profileFieldRawValues[$fieldName] = $fieldValue->getValue();
$profileFieldDisplayValues[$fieldName] = $fieldFormat->formatDisplay($fieldValue->getValue());
if($fieldFormat->hasLinkFormat())
$profileFieldLinkValues[$fieldName] = $fieldFormat->formatLink($fieldValue->getValue());
$profileFieldRawValues[$fieldName] = $fieldValue->value;
$profileFieldDisplayValues[$fieldName] = $fieldFormat->formatDisplay($fieldValue->value);
if($fieldFormat->linkFormat !== null)
$profileFieldLinkValues[$fieldName] = $fieldFormat->formatLink($fieldValue->value);
}
}
@ -372,7 +362,7 @@ if(!$viewingAsGuest) {
Template::render('profile.index', [
'profile_viewer' => $viewerInfo,
'profile_user' => $userInfo,
'profile_colour' => $usersCtx->getUserColour($userInfo),
'profile_colour' => $msz->usersCtx->getUserColour($userInfo),
'profile_stats' => $profileStats,
'profile_mode' => $profileMode,
'profile_notices' => $notices,

View file

@ -6,8 +6,7 @@ use RuntimeException;
use Index\XArray;
use Misuzu\Comments\CommentsCategory;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(403);
$searchQuery = !empty($_GET['q']) && is_string($_GET['q']) ? $_GET['q'] : '';
@ -24,7 +23,7 @@ Template::addFunction('search_merge_query', function($attrs) use (&$searchQueryE
if(!empty($attrs['author']))
$existing[] = 'author:' . $attrs['author'];
elseif(!empty($searchQueryEvaluated['author']))
$existing[] = 'author:' . $searchQueryEvaluated['author']->getName();
$existing[] = 'author:' . $searchQueryEvaluated['author']->name;
if(!empty($attrs['after']))
$existing[] = 'after:' . $attrs['after'];
@ -39,15 +38,6 @@ Template::addFunction('search_merge_query', function($attrs) use (&$searchQueryE
return implode(' ', $existing);
});
if(!empty($searchQuery)) {
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$news = $msz->getNews();
$comments = $msz->getComments();
$searchQueryAttributes = ['type', 'author', 'after'];
$searchQueryParts = explode(' ', $searchQuery);
foreach($searchQueryParts as $queryPart) {
@ -72,60 +62,60 @@ if(!empty($searchQuery)) {
if(!empty($searchQueryEvaluated['author']))
try {
$searchQueryEvaluated['author'] = $usersCtx->getUserInfo($searchQueryEvaluated['author'], 'search');
$searchQueryEvaluated['author'] = $msz->usersCtx->getUserInfo($searchQueryEvaluated['author'], 'search');
} catch(RuntimeException $ex) {
unset($searchQueryEvaluated['author']);
}
if(empty($searchQueryEvaluated['type']) || str_starts_with($searchQueryEvaluated['type'], 'forum')) {
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser === null ? 0 : (int)$currentUser->getId();
$forumCategoryIds = XArray::where(
$forumCategories->getCategories(hidden: false),
fn($categoryInfo) => $categoryInfo->mayHaveTopics() && $authInfo->getPerms('forum', $categoryInfo)->check(Perm::F_CATEGORY_VIEW)
$msz->forumCtx->categories->getCategories(hidden: false),
fn($categoryInfo) => $categoryInfo->mayHaveTopics && $msz->authInfo->getPerms('forum', $categoryInfo)->check(Perm::F_CATEGORY_VIEW)
);
$forumTopicInfos = $forumTopics->getTopics(categoryInfo: $forumCategoryIds, deleted: false, searchQuery: $searchQueryEvaluated);
$forumTopicInfos = $msz->forumCtx->topics->getTopics(categoryInfo: $forumCategoryIds, deleted: false, searchQuery: $searchQueryEvaluated);
$ftopics = [];
foreach($forumTopicInfos as $topicInfo) {
$ftopics[] = $topic = new stdClass;
$topic->info = $topicInfo;
$topic->unread = $forumTopics->checkTopicUnread($topicInfo, $currentUser);
$topic->participated = $forumTopics->checkTopicParticipated($topicInfo, $currentUser);
$topic->unread = $msz->forumCtx->topics->checkTopicUnread($topicInfo, $currentUser);
$topic->participated = $msz->forumCtx->topics->checkTopicParticipated($topicInfo, $currentUser);
$topic->lastPost = new stdClass;
if($topicInfo->hasUserId()) {
$topic->user = $usersCtx->getUserInfo($topicInfo->getUserId(), 'id');
$topic->colour = $usersCtx->getUserColour($topic->user);
if($topicInfo->userId !== null) {
$topic->user = $msz->usersCtx->getUserInfo($topicInfo->userId, 'id');
$topic->colour = $msz->usersCtx->getUserColour($topic->user);
}
try {
$topic->lastPost->info = $lastPostInfo = $forumPosts->getPost(
$topic->lastPost->info = $lastPostInfo = $msz->forumCtx->posts->getPost(
topicInfo: $topicInfo,
getLast: true,
deleted: $topicInfo->isDeleted() ? null : false,
deleted: $topicInfo->deleted ? null : false,
);
if($lastPostInfo->hasUserId()) {
$topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId(), 'id');
$topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
if($lastPostInfo->userId !== null) {
$topic->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId, 'id');
$topic->lastPost->colour = $msz->usersCtx->getUserColour($topic->lastPost->user);
}
} catch(RuntimeException $ex) {}
}
$forumPostInfos = $forumPosts->getPosts(categoryInfo: $forumCategoryIds, searchQuery: $searchQueryEvaluated);
$forumPostInfos = $msz->forumCtx->posts->getPosts(categoryInfo: $forumCategoryIds, searchQuery: $searchQueryEvaluated);
$fposts = [];
foreach($forumPostInfos as $postInfo) {
$fposts[] = $post = new stdClass;
$post->info = $postInfo;
if($postInfo->hasUserId()) {
$post->user = $usersCtx->getUserInfo($postInfo->getUserId(), 'id');
$post->colour = $usersCtx->getUserColour($post->user);
$post->postsCount = $forumCtx->countTotalUserPosts($post->user);
if($postInfo->userId !== null) {
$post->user = $msz->usersCtx->getUserInfo($postInfo->userId, 'id');
$post->colour = $msz->usersCtx->getUserColour($post->user);
$post->postsCount = $msz->forumCtx->countTotalUserPosts($post->user);
}
// can't be bothered sorry
@ -135,22 +125,21 @@ if(!empty($searchQuery)) {
}
$newsPosts = [];
$newsPostInfos = empty($searchQueryEvaluated['type']) || $searchQueryEvaluated['type'] === 'news' ? $news->getPosts(searchQuery: $searchQuery) : [];
$newsPostInfos = empty($searchQueryEvaluated['type']) || $searchQueryEvaluated['type'] === 'news' ? $msz->news->getPosts(searchQuery: $searchQuery) : [];
$newsCategoryInfos = [];
foreach($newsPostInfos as $postInfo) {
$userId = $postInfo->getUserId();
$categoryId = $postInfo->getCategoryId();
$userInfo = $postInfo->hasUserId() ? $usersCtx->getUserInfo($postInfo->getUserId()) : null;
$userColour = $usersCtx->getUserColour($userInfo);
$categoryId = $postInfo->categoryId;
$userInfo = $postInfo->userId !== null ? $msz->usersCtx->getUserInfo($postInfo->userId) : null;
$userColour = $msz->usersCtx->getUserColour($userInfo);
if(array_key_exists($categoryId, $newsCategoryInfos))
$categoryInfo = $newsCategoryInfos[$categoryId];
else
$newsCategoryInfos[$categoryId] = $categoryInfo = $news->getCategory(postInfo: $postInfo);
$newsCategoryInfos[$categoryId] = $categoryInfo = $msz->news->getCategory(postInfo: $postInfo);
$commentsCount = $postInfo->hasCommentsCategoryId()
? $comments->countPosts(categoryInfo: $postInfo->getCommentsCategoryId(), deleted: false) : 0;
$commentsCount = $postInfo->commentsSectionId !== null
? $msz->comments->countPosts(categoryInfo: $postInfo->commentsSectionId, deleted: false) : 0;
$newsPosts[] = [
'post' => $postInfo,
@ -162,14 +151,14 @@ if(!empty($searchQuery)) {
}
$members = [];
$memberInfos = $users->getUsers(searchQuery: $searchQueryEvaluated);
$memberInfos = $msz->usersCtx->users->getUsers(searchQuery: $searchQueryEvaluated);
foreach($memberInfos as $memberInfo) {
$members[] = $member = new stdClass;
$member->info = $memberInfo;
$member->colour = $usersCtx->getUserColour($memberInfo);
$member->ftopics = $forumCtx->countTotalUserTopics($memberInfo);
$member->fposts = $forumCtx->countTotalUserPosts($memberInfo);
$member->colour = $msz->usersCtx->getUserColour($memberInfo);
$member->ftopics = $msz->forumCtx->countTotalUserTopics($memberInfo);
$member->fposts = $msz->forumCtx->countTotalUserPosts($memberInfo);
}
}

View file

@ -6,39 +6,35 @@ use Misuzu\Users\User;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(401);
$errors = [];
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$userInfo = $authInfo->getUserInfo();
$isRestricted = $usersCtx->hasActiveBan($userInfo);
$userInfo = $msz->authInfo->userInfo;
$isRestricted = $msz->usersCtx->hasActiveBan($userInfo);
$isVerifiedRequest = CSRF::validateRequest();
if(!$isRestricted && $isVerifiedRequest && !empty($_POST['role'])) {
try {
$roleInfo = $roles->getRole(($_POST['role']['id'] ?? 0));
$roleInfo = $msz->usersCtx->roles->getRole(($_POST['role']['id'] ?? 0));
} catch(RuntimeException $ex) {}
if(empty($roleInfo) || !$users->hasRole($userInfo, $roleInfo))
if(empty($roleInfo) || !$msz->usersCtx->users->hasRole($userInfo, $roleInfo))
$errors[] = "You're trying to modify a role that hasn't been assigned to you.";
else {
switch($_POST['role']['mode'] ?? '') {
case 'display':
$users->updateUser(
$msz->usersCtx->users->updateUser(
$userInfo,
displayRoleInfo: $roleInfo
);
break;
case 'leave':
if($roleInfo->isLeavable()) {
$users->removeRoles($userInfo, $roleInfo);
$msz->getPerms()->precalculatePermissions(
$msz->getForumContext()->getCategories(),
if($roleInfo->leavable) {
$msz->usersCtx->users->removeRoles($userInfo, $roleInfo);
$msz->perms->precalculatePermissions(
$msz->forumCtx->categories,
[$userInfo->getId()]
);
} else
@ -48,17 +44,17 @@ if(!$isRestricted && $isVerifiedRequest && !empty($_POST['role'])) {
}
}
if($isVerifiedRequest && isset($_POST['tfa']['enable']) && $userInfo->hasTOTPKey() !== (bool)$_POST['tfa']['enable']) {
if($isVerifiedRequest && isset($_POST['tfa']['enable']) && $userInfo->hasTOTP !== (bool)$_POST['tfa']['enable']) {
$totpKey = '';
if((bool)$_POST['tfa']['enable']) {
$totpKey = TOTPGenerator::generateKey();
$totpIssuer = $msz->getSiteInfo()->getName();
$totpIssuer = $msz->siteInfo->name;
$totpQrcode = (new QRCode(new QROptions([
'version' => 5,
'outputType' => QRCode::OUTPUT_IMAGE_JPG,
'eccLevel' => QRCode::ECC_L,
])))->render(sprintf('otpauth://totp/%s:%s?%s', $totpIssuer, $userInfo->getName(), http_build_query([
])))->render(sprintf('otpauth://totp/%s:%s?%s', $totpIssuer, $userInfo->name, http_build_query([
'secret' => $totpKey,
'issuer' => $totpIssuer,
])));
@ -69,7 +65,7 @@ if($isVerifiedRequest && isset($_POST['tfa']['enable']) && $userInfo->hasTOTPKey
]);
}
$users->updateUser(userInfo: $userInfo, totpKey: $totpKey);
$msz->usersCtx->users->updateUser(userInfo: $userInfo, totpKey: $totpKey);
}
if($isVerifiedRequest && !empty($_POST['current_password'])) {
@ -80,15 +76,15 @@ if($isVerifiedRequest && !empty($_POST['current_password'])) {
if(!empty($_POST['email']['new'])) {
if(empty($_POST['email']['confirm']) || $_POST['email']['new'] !== $_POST['email']['confirm']) {
$errors[] = 'The addresses you entered did not match each other.';
} elseif($userInfo->getEMailAddress() === mb_strtolower($_POST['email']['confirm'])) {
} elseif($userInfo->emailAddress === mb_strtolower($_POST['email']['confirm'])) {
$errors[] = 'This is already your e-mail address!';
} else {
$checkMail = $users->validateEMailAddress($_POST['email']['new']);
$checkMail = $msz->usersCtx->users->validateEMailAddress($_POST['email']['new']);
if($checkMail !== '') {
$errors[] = $users->validateEMailAddressText($checkMail);
$errors[] = $msz->usersCtx->users->validateEMailAddressText($checkMail);
} else {
$users->updateUser(userInfo: $userInfo, emailAddr: $_POST['email']['new']);
$msz->usersCtx->users->updateUser(userInfo: $userInfo, emailAddr: $_POST['email']['new']);
$msz->createAuditLog('PERSONAL_EMAIL_CHANGE', [$_POST['email']['new']]);
}
}
@ -99,12 +95,12 @@ if($isVerifiedRequest && !empty($_POST['current_password'])) {
if(empty($_POST['password']['confirm']) || $_POST['password']['new'] !== $_POST['password']['confirm']) {
$errors[] = 'The new passwords you entered did not match each other.';
} else {
$checkPassword = $users->validatePassword($_POST['password']['new']);
$checkPassword = $msz->usersCtx->users->validatePassword($_POST['password']['new']);
if($checkPassword !== '') {
$errors[] = $users->validatePasswordText($checkPassword);
$errors[] = $msz->usersCtx->users->validatePasswordText($checkPassword);
} else {
$users->updateUser(userInfo: $userInfo, password: $_POST['password']['new']);
$msz->usersCtx->users->updateUser(userInfo: $userInfo, password: $_POST['password']['new']);
$msz->createAuditLog('PERSONAL_PASSWORD_CHANGE');
}
}
@ -114,9 +110,9 @@ if($isVerifiedRequest && !empty($_POST['current_password'])) {
// reload $userInfo object
if($_SERVER['REQUEST_METHOD'] === 'POST' && $isVerifiedRequest)
$userInfo = $users->getUser($userInfo->getId(), 'id');
$userInfo = $msz->usersCtx->users->getUser($userInfo->getId(), 'id');
$userRoles = iterator_to_array($roles->getRoles(userInfo: $userInfo));
$userRoles = iterator_to_array($msz->usersCtx->roles->getRoles(userInfo: $userInfo));
Template::render('settings.account', [
'errors' => $errors,

View file

@ -5,11 +5,10 @@ use ZipArchive;
use Index\XString;
use Misuzu\Users\UserInfo;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(401);
$dbConn = $msz->getDbConn();
$dbConn = $msz->dbConn;
function db_to_zip(ZipArchive $archive, UserInfo $userInfo, string $baseName, array $fieldInfos, string $userIdField = 'user_id'): string {
global $dbConn;
@ -98,7 +97,7 @@ function db_to_zip(ZipArchive $archive, UserInfo $userInfo, string $baseName, ar
}
$errors = [];
$userInfo = $authInfo->getUserInfo();
$userInfo = $msz->authInfo->userInfo;
if(isset($_POST['action']) && is_string($_POST['action'])) {
if(isset($_POST['password']) && is_string($_POST['password'])

View file

@ -3,20 +3,15 @@ namespace Misuzu;
use Misuzu\Pagination;
$authInfo = $msz->getAuthInfo();
$currentUser = $authInfo->getUserInfo();
$currentUser = $msz->authInfo->userInfo;
if($currentUser === null)
Template::throwError(401);
$authCtx = $msz->getAuthContext();
$loginAttempts = $authCtx->getLoginAttempts();
$auditLog = $msz->getAuditLog();
$loginHistoryPagination = new Pagination($msz->authCtx->loginAttempts->countAttempts(userInfo: $currentUser), 5, 'hp');
$accountLogPagination = new Pagination($msz->auditLog->countLogs(userInfo: $currentUser), 10, 'ap');
$loginHistoryPagination = new Pagination($loginAttempts->countAttempts(userInfo: $currentUser), 5, 'hp');
$accountLogPagination = new Pagination($auditLog->countLogs(userInfo: $currentUser), 10, 'ap');
$loginHistory = iterator_to_array($loginAttempts->getAttempts(userInfo: $currentUser, pagination: $loginHistoryPagination));
$auditLogs = iterator_to_array($auditLog->getLogs(userInfo: $currentUser, pagination: $accountLogPagination));
$loginHistory = iterator_to_array($msz->authCtx->loginAttempts->getAttempts(userInfo: $currentUser, pagination: $loginHistoryPagination));
$auditLogs = iterator_to_array($msz->auditLog->getLogs(userInfo: $currentUser, pagination: $accountLogPagination));
Template::render('settings.logs', [
'login_history_list' => $loginHistory,

View file

@ -3,15 +3,12 @@ namespace Misuzu;
use RuntimeException;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::throwError(401);
$errors = [];
$authCtx = $msz->getAuthContext();
$sessions = $authCtx->getSessions();
$currentUser = $authInfo->getUserInfo();
$activeSessionId = $authInfo->getSessionId();
$currentUser = $msz->authInfo->userInfo;
$activeSessionId = $msz->authInfo->sessionId;
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$sessionId = (string)filter_input(INPUT_POST, 'session');
@ -19,38 +16,38 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
if($sessionId === 'all') {
$activeSessionKilled = true;
$sessions->deleteSessions(userInfos: $currentUser);
$msz->authCtx->sessions->deleteSessions(userInfos: $currentUser);
$msz->createAuditLog('PERSONAL_SESSION_DESTROY_ALL');
} else {
try {
$sessionInfo = $sessions->getSession(sessionId: $sessionId);
$sessionInfo = $msz->authCtx->sessions->getSession(sessionId: $sessionId);
} catch(RuntimeException $ex) {}
if(empty($sessionInfo) || $sessionInfo->getUserId() !== $currentUser->getId()) {
if(empty($sessionInfo) || $sessionInfo->userId !== $currentUser->getId()) {
$errors[] = "That session doesn't exist.";
break;
}
$activeSessionKilled = $sessionInfo->getId() === $activeSessionId;
$sessions->deleteSessions(sessionInfos: $sessionInfo);
$msz->createAuditLog('PERSONAL_SESSION_DESTROY', [$sessionInfo->getId()]);
$activeSessionKilled = $sessionInfo->id === $activeSessionId;
$msz->authCtx->sessions->deleteSessions(sessionInfos: $sessionInfo);
$msz->createAuditLog('PERSONAL_SESSION_DESTROY', [$sessionInfo->id]);
}
if($activeSessionKilled) {
Tools::redirect($msz->getUrls()->format('index'));
Tools::redirect($msz->urls->format('index'));
return;
} else break;
}
$pagination = new Pagination($sessions->countSessions(userInfo: $currentUser), 10);
$pagination = new Pagination($msz->authCtx->sessions->countSessions(userInfo: $currentUser), 10);
$sessionList = [];
$sessionInfos = $sessions->getSessions(userInfo: $currentUser, pagination: $pagination);
$sessionInfos = $msz->authCtx->sessions->getSessions(userInfo: $currentUser, pagination: $pagination);
foreach($sessionInfos as $sessionInfo)
$sessionList[] = [
'info' => $sessionInfo,
'active' => $sessionInfo->getId() === $activeSessionId,
'active' => $sessionInfo->id === $activeSessionId,
];
Template::render('settings.sessions', [