Normalised custom exception usage in user classes.

Also updated the Index library to include the MediaType fix.
This commit is contained in:
flash 2023-07-22 15:02:41 +00:00
parent 42d893fc18
commit d0e3f6ce65
36 changed files with 128 additions and 194 deletions

4
composer.lock generated
View file

@ -348,7 +348,7 @@
"source": {
"type": "git",
"url": "https://git.flash.moe/flash/index.git",
"reference": "4aae77900be26fccb23a7508744ef17d6b217e5f"
"reference": "557f089ff79c3806f1973ee7bf82f81ab4faa5f4"
},
"require": {
"ext-mbstring": "*",
@ -386,7 +386,7 @@
],
"description": "Composer package for the common library for my projects.",
"homepage": "https://railgun.sh/index",
"time": "2023-07-21T21:47:41+00:00"
"time": "2023-07-22T14:25:58+00:00"
},
{
"name": "matomo/device-detector",

View file

@ -1,13 +1,12 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\AuthToken;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserAuthSession;
use Misuzu\Users\UserLoginAttempt;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserSessionCreationFailedException;
if(UserSession::hasCurrent()) {
url_redirect('index');
@ -20,7 +19,7 @@ if(!empty($_GET['resolve'])) {
try {
// Only works for usernames, this is by design
$userInfo = User::byUsername((string)filter_input(INPUT_GET, 'name'));
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
echo json_encode([
'id' => 0,
'name' => '',
@ -90,7 +89,7 @@ while(!empty($_POST['login']) && is_array($_POST['login'])) {
try {
$userInfo = User::byUsernameOrEMailAddress($_POST['login']['username']);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
UserLoginAttempt::create($ipAddress, $countryCode, false);
$notices[] = $loginFailedError;
break;
@ -128,7 +127,7 @@ while(!empty($_POST['login']) && is_array($_POST['login'])) {
try {
$sessionInfo = UserSession::create($userInfo, $ipAddress, $countryCode);
$sessionInfo->setCurrent();
} catch(UserSessionCreationFailedException $ex) {
} catch(RuntimeException $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}

View file

@ -1,12 +1,10 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserLoginAttempt;
use Misuzu\Users\UserRecoveryToken;
use Misuzu\Users\UserRecoveryTokenNotFoundException;
use Misuzu\Users\UserRecoveryTokenCreationFailedException;
use Misuzu\Users\UserSession;
if(UserSession::hasCurrent()) {
@ -23,7 +21,7 @@ $userId = !empty($reset['user']) ? (int)$reset['user'] : (
if($userId > 0)
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
url_redirect('auth-forgot');
return;
}
@ -45,7 +43,7 @@ while($canResetPassword) {
try {
$tokenInfo = UserRecoveryToken::byToken($verificationCode);
} catch(UserRecoveryTokenNotFoundException $ex) {
} catch(RuntimeException $ex) {
unset($tokenInfo);
}
@ -101,7 +99,7 @@ while($canResetPassword) {
try {
$forgotUser = User::byEMailAddress($forgot['email']);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
unset($forgotUser);
}
@ -112,7 +110,7 @@ while($canResetPassword) {
try {
$tokenInfo = UserRecoveryToken::byUserAndRemoteAddress($forgotUser, $ipAddress);
} catch(UserRecoveryTokenNotFoundException $ex) {
} catch(RuntimeException $ex) {
$tokenInfo = UserRecoveryToken::create($forgotUser, $ipAddress);
$recoveryMessage = Mailer::template('password-recovery', [

View file

@ -1,8 +1,8 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserCreationFailedException;
use Misuzu\Users\UserLoginAttempt;
use Misuzu\Users\UserRole;
use Misuzu\Users\UserSession;
@ -80,7 +80,7 @@ while(!$restricted && !empty($register)) {
$ipAddress,
$countryCode
);
} catch(UserCreationFailedException $ex) {
} catch(RuntimeException $ex) {
$notices[] = 'Something went wrong while creating your account, please alert an administrator or a developer about this!';
break;
}

View file

@ -1,12 +1,11 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserLoginAttempt;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserSessionCreationFailedException;
use Misuzu\Users\UserAuthSession;
use Misuzu\Users\UserAuthSessionNotFoundException;
if(UserSession::hasCurrent()) {
url_redirect('index');
@ -25,7 +24,7 @@ try {
!empty($twofactor['token']) && is_string($twofactor['token']) ? $twofactor['token'] : ''
)
);
} catch(UserAuthSessionNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
if(empty($tokenInfo) || $tokenInfo->hasExpired()) {
url_redirect('auth-login');
@ -76,7 +75,7 @@ while(!empty($twofactor)) {
try {
$sessionInfo = UserSession::create($userInfo, $ipAddress, $countryCode);
$sessionInfo->setCurrent();
} catch(UserSessionCreationFailedException $ex) {
} catch(RuntimeException $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}

View file

@ -6,7 +6,6 @@ use RuntimeException;
use Index\DateTime;
use Misuzu\Changelog\Changelog;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_CHANGELOG, User::getCurrent()->getId(), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
echo render_error(403);

View file

@ -1,6 +1,7 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_CHANGELOG, User::getCurrent()->getId(), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
@ -28,7 +29,7 @@ foreach($changeInfos as $changeInfo) {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -1,11 +1,11 @@
<?php
namespace Misuzu;
use RuntimeException;
use Index\Colour\Colour;
use Index\Colour\ColourRGB;
use Misuzu\Users\User;
use Misuzu\Users\UserRole;
use Misuzu\Users\UserRoleNotFoundException;
if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_USER, User::getCurrent()->getId(), MSZ_PERM_USER_MANAGE_ROLES)) {
echo render_error(403);
@ -17,7 +17,7 @@ $roleId = (int)filter_input(INPUT_GET, 'r', FILTER_SANITIZE_NUMBER_INT);
if($roleId > 0)
try {
$roleInfo = UserRole::byId($roleId);
} catch(UserRoleNotFoundException $ex) {
} catch(RuntimeException $ex) {
echo render_error(404);
return;
}

View file

@ -1,11 +1,10 @@
<?php
namespace Misuzu;
use RuntimeException;
use Index\Colour\Colour;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserRole;
use Misuzu\Users\UserRoleNotFoundException;
if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_USER, User::getCurrent()->getId(), MSZ_PERM_USER_MANAGE_USERS)) {
echo render_error(403);
@ -19,7 +18,7 @@ $currentUserId = $currentUser->getId();
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
echo render_error(404);
return;
}
@ -94,7 +93,7 @@ if(CSRF::validateRequest() && $canEdit) {
foreach($applyRoles as $roleId) {
try {
$role = $existingRoles[$roleId] ?? UserRole::byId($roleId);
} catch(UserRoleNotFoundException $ex) {
} catch(RuntimeException $ex) {
continue;
}
if(!$currentUser->hasAuthorityOver($role))
@ -118,7 +117,7 @@ if(CSRF::validateRequest() && $canEdit) {
try {
$userInfo->setDisplayRole(UserRole::byId($displayRole));
} catch(UserRoleNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
$countryValidation = strlen($setCountry) === 2
&& ctype_alpha($setCountry)

View file

@ -1,12 +1,10 @@
<?php
namespace Misuzu;
use RuntimeException;
use InvalidArgumentException;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserWarning;
use Misuzu\Users\UserWarningNotFoundException;
use Misuzu\Users\UserWarningCreationFailedException;
if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_USER, User::getCurrent()->getId(), MSZ_PERM_USER_MANAGE_WARNINGS)) {
echo render_error(403);
@ -20,7 +18,7 @@ $currentUserId = $currentUser->getId();
if(!empty($_POST['lookup']) && is_string($_POST['lookup'])) {
try {
$userId = User::byUsername((string)filter_input(INPUT_POST, 'lookup'))->getId();
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userId = 0;
}
url_redirect('manage-users-warnings', ['user' => $userId]);
@ -32,7 +30,7 @@ if(!empty($_POST['lookup']) && is_string($_POST['lookup'])) {
if(!empty($_GET['delete'])) {
try {
UserWarning::byId((int)filter_input(INPUT_GET, 'w', FILTER_SANITIZE_NUMBER_INT))->delete();
} catch(UserWarningNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
redirect($_SERVER['HTTP_REFERER'] ?? url('manage-users-warnings'));
return;
}
@ -79,7 +77,7 @@ if(!empty($_POST['warning']) && is_array($_POST['warning'])) {
if(!$currentUser->hasAuthorityOver($warningsUserInfo))
$notices[] = 'You do not have authority over this user.';
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$notices[] = 'This user doesn\'t exist.';
}
@ -96,7 +94,7 @@ if(!empty($_POST['warning']) && is_array($_POST['warning'])) {
);
} catch(InvalidArgumentException $ex) {
$notices[] = $ex->getMessage();
} catch(UserWarningCreationFailedException $ex) {
} catch(RuntimeException $ex) {
$notices[] = 'Warning creation failed.';
}
}
@ -108,7 +106,7 @@ if(empty($warningsUser))
if(empty($warningsUserInfo))
try {
$warningsUserInfo = User::byId($warningsUser);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$warningsUserInfo = null;
}

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserRole;
use Misuzu\Users\UserRoleNotFoundException;
$roleId = !empty($_GET['r']) && is_string($_GET['r']) ? (int)$_GET['r'] : UserRole::DEFAULT;
$orderBy = !empty($_GET['ss']) && is_string($_GET['ss']) ? mb_strtolower($_GET['ss']) : '';
@ -71,7 +71,7 @@ $canManageUsers = perms_check_user(MSZ_PERMS_USER, User::hasCurrent() ? User::ge
try {
$roleInfo = UserRole::byId($roleId);
} catch(UserRoleNotFoundException $ex) {
} catch(RuntimeException $ex) {
echo render_error(404);
return;
}

View file

@ -2,18 +2,13 @@
namespace Misuzu;
use InvalidArgumentException;
use RuntimeException;
use Index\ByteFormat;
use Misuzu\Parsers\Parser;
use Misuzu\Profile\ProfileFields;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserSession;
use Misuzu\Users\Assets\UserBackgroundAsset;
use Misuzu\Users\Assets\UserImageAssetException;
use Misuzu\Users\Assets\UserImageAssetInvalidImageException;
use Misuzu\Users\Assets\UserImageAssetInvalidTypeException;
use Misuzu\Users\Assets\UserImageAssetInvalidDimensionsException;
use Misuzu\Users\Assets\UserImageAssetFileTooLargeException;
$userId = !empty($_GET['u']) && is_string($_GET['u']) ? trim($_GET['u']) : 0;
$profileMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
@ -21,7 +16,7 @@ $isEditing = !empty($_GET['edit']) && is_string($_GET['edit']) ? (bool)$_GET['ed
try {
$profileUser = User::findForProfile($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
http_response_code(404);
Template::render('profile.index');
return;
@ -211,15 +206,16 @@ if($isEditing) {
} else {
try {
$avatarInfo->setFromPath($_FILES['avatar']['tmp_name']['file']);
} catch(UserImageAssetInvalidImageException $ex) {
$notices[] = 'The file you uploaded was not an image!';
} catch(UserImageAssetInvalidTypeException $ex) {
$notices[] = 'This type of image is not supported, keep to PNG, JPG or GIF!';
} catch(UserImageAssetInvalidDimensionsException $ex) {
$notices[] = sprintf('Your avatar can\'t be larger than %dx%d!', $avatarInfo->getMaxWidth(), $avatarInfo->getMaxHeight());
} catch(UserImageAssetFileTooLargeException $ex) {
$notices[] = sprintf('Your avatar is not allowed to be larger in file size than %s!', ByteFormat::format($avatarInfo->getMaxBytes()));
} catch(UserImageAssetException $ex) {
} catch(InvalidArgumentException $ex) {
$exMessage = $ex->getMessage();
$notices[] = match($exMessage) {
'$path is not a valid image.' => 'The file you uploaded was not an image!',
'$path is not an allowed image file.' => 'This type of image is not supported, keep to PNG, JPG or GIF!',
'Dimensions of $path are too large.' => sprintf('Your avatar can\'t be larger than %dx%d!', $avatarInfo->getMaxWidth(), $avatarInfo->getMaxHeight()),
'File size of $path is too large.' => sprintf('Your avatar is not allowed to be larger in file size than %s!', ByteFormat::format($avatarInfo->getMaxBytes())),
default => $exMessage,
};
} catch(RuntimeException $ex) {
$notices[] = 'Unable to save your avatar, contact an administator!';
}
}
@ -256,15 +252,16 @@ if($isEditing) {
} else {
try {
$backgroundInfo->setFromPath($_FILES['background']['tmp_name']['file']);
} catch(UserImageAssetInvalidImageException $ex) {
$notices[] = 'The file you uploaded was not an image!';
} catch(UserImageAssetInvalidTypeException $ex) {
$notices[] = 'This type of image is not supported, keep to PNG, JPG or GIF!';
} catch(UserImageAssetInvalidDimensionsException $ex) {
$notices[] = sprintf('Your background can\'t be larger than %dx%d!', $backgroundInfo->getMaxWidth(), $backgroundInfo->getMaxHeight());
} catch(UserImageAssetFileTooLargeException $ex) {
$notices[] = sprintf('Your background is not allowed to be larger in file size than %2$s!', ByteFormat::format($backgroundInfo->getMaxBytes()));
} catch(UserImageAssetException $ex) {
} catch(InvalidArgumentException $ex) {
$exMessage = $ex->getMessage();
$notices[] = match($exMessage) {
'$path is not a valid image.' => 'The file you uploaded was not an image!',
'$path is not an allowed image file.' => 'This type of image is not supported, keep to PNG, JPG or GIF!',
'Dimensions of $path are too large.' => sprintf('Your background can\'t be larger than %dx%d!', $backgroundInfo->getMaxWidth(), $backgroundInfo->getMaxHeight()),
'File size of $path is too large.' => sprintf('Your background is not allowed to be larger in file size than %2$s!', ByteFormat::format($backgroundInfo->getMaxBytes())),
default => $exMessage,
};
} catch(RuntimeException $ex) {
$notices[] = 'Unable to save your background, contact an administator!';
}
}

View file

@ -28,7 +28,7 @@ if(!empty($searchQuery)) {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserRole;
use Misuzu\Users\UserRoleNotFoundException;
use Misuzu\Users\UserSession;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
@ -22,7 +22,7 @@ $isVerifiedRequest = CSRF::validateRequest();
if(!$isRestricted && $isVerifiedRequest && !empty($_POST['role'])) {
try {
$roleInfo = UserRole::byId((int)($_POST['role']['id'] ?? 0));
} catch(UserRoleNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
if(empty($roleInfo) || !$currentUser->hasRole($roleInfo))
$errors[] = "You're trying to modify a role that hasn't been assigned to you.";

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserSessionNotFoundException;
if(!User::hasCurrent()) {
echo render_error(401);
@ -25,7 +25,7 @@ if(!empty($_POST['session']) && CSRF::validateRequest()) {
try {
$sessionInfo = UserSession::byId($sessionId);
} catch(UserSessionNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
if(empty($sessionInfo) || $sessionInfo->getUserId() !== $currentUser->getId()) {
$errors[] = "Session #{$sessionId} does not exist.";

View file

@ -1,10 +1,9 @@
<?php
namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserSessionNotFoundException;
require_once __DIR__ . '/../misuzu.php';
@ -118,7 +117,7 @@ if($authToken->isValid()) {
try {
$userInfo = User::byId($authToken->getImpersonatedUserId());
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = $userInfoReal;
$authToken->removeImpersonatedUserId();
$authToken->applyCookie();
@ -128,10 +127,7 @@ if($authToken->isValid()) {
}
}
}
} catch(UserNotFoundException $ex) {
UserSession::unsetCurrent();
User::unsetCurrent();
} catch(UserSessionNotFoundException $ex) {
} catch(RuntimeException $ex) {
UserSession::unsetCurrent();
User::unsetCurrent();
}

View file

@ -2,7 +2,6 @@
namespace Misuzu\AuditLog;
use InvalidArgumentException;
use RuntimeException;
use Index\Data\DbStatementCache;
use Index\Data\IDbConnection;
use Index\Data\IDbResult;

View file

@ -2,8 +2,8 @@
namespace Misuzu\Comments;
use stdClass;
use RuntimeException;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
class CommentsEx {
private Comments $comments;
@ -38,7 +38,7 @@ class CommentsEx {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu\Comments;
use RuntimeException;
use Misuzu\DB;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
class CommentsParser {
private const MARKUP_USERNAME = '#\B(?:@{1}(' . User::NAME_REGEX . '))#u';
@ -13,7 +13,7 @@ class CommentsParser {
return preg_replace_callback(self::MARKUP_USERNAME, function ($matches) {
try {
return sprintf('@@%d', User::byUsername($matches[1])->getId());
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
return $matches[0];
}
}, $text);

View file

@ -1,8 +1,6 @@
<?php
namespace Misuzu\Feeds;
use InvalidArgumentException;
class Feed {
private string $title = '';
private ?string $description = null;

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu\Http\Handlers;
use RuntimeException;
use Misuzu\GitInfo;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\Assets\StaticUserImageAsset;
use Misuzu\Users\Assets\UserImageAssetInterface;
use Misuzu\Users\Assets\UserAssetScalableInterface;
@ -55,7 +55,7 @@ final class AssetsHandler extends Handler {
} elseif($userInfo->hasAvatar()) {
$assetInfo = $userInfo->getAvatarInfo();
}
} catch(UserNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
$this->serveUserAsset($response, $request, $assetInfo);
}
@ -69,7 +69,7 @@ final class AssetsHandler extends Handler {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
if(empty($userInfo) || !$userInfo->hasBackground() || !$this->canViewAsset($request, $userInfo)) {
$response->setContent('');

View file

@ -11,7 +11,6 @@ use Misuzu\Feeds\FeedItem;
use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
class ChangelogHandler extends Handler {
private array $userInfos = [];
@ -34,7 +33,7 @@ class ChangelogHandler extends Handler {
if($filterUser > 0)
try {
$filterUser = User::byId($filterUser);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
return 404;
}
else
@ -68,7 +67,7 @@ class ChangelogHandler extends Handler {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}
@ -105,7 +104,7 @@ class ChangelogHandler extends Handler {
try {
$userInfo = User::byId($changeInfo->getUserId());
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -8,7 +8,6 @@ use Misuzu\Template;
use Misuzu\Comments\CommentsCategory;
use Misuzu\Users\User;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserNotFoundException;
final class HomeHandler extends Handler {
public function index($response, $request): void {
@ -132,7 +131,7 @@ final class HomeHandler extends Handler {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -14,7 +14,6 @@ use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\News\NewsCategoryInfo;
use Misuzu\Parsers\Parser;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
final class NewsHandler extends Handler {
private function fetchPostInfo(array $postInfos, array $categoryInfos = []): array {
@ -32,7 +31,7 @@ final class NewsHandler extends Handler {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}
@ -138,7 +137,7 @@ final class NewsHandler extends Handler {
if($postInfo->hasUserId())
try {
$userInfo = User::byId($postInfo->getUserId());
} catch(UserNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
$comments = new CommentsEx($comments);
@ -208,7 +207,7 @@ final class NewsHandler extends Handler {
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = null;
}

View file

@ -5,9 +5,7 @@ use InvalidArgumentException;
use Misuzu\Config\IConfig;
use Symfony\Component\Mime\Email as SymfonyMessage;
use Symfony\Component\Mime\Address as SymfonyAddress;
use Symfony\Component\Mailer\Mailer as SymfonyMailer;
use Symfony\Component\Mailer\Transport as SymfonyTransport;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
final class Mailer {
private const TEMPLATE_PATH = MSZ_ROOT . '/config/emails/%s.txt';

View file

@ -1,6 +1,7 @@
<?php
namespace Misuzu\SharpChat;
use RuntimeException;
use Index\Colour\Colour;
use Index\Routing\IRouter;
use Index\Http\HttpFx;
@ -12,9 +13,6 @@ use Misuzu\Emoticons\Emotes;
use Misuzu\Users\User;
use Misuzu\Users\UserSession;
use Misuzu\Users\UserWarning;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserWarningCreationFailedException;
use Misuzu\Users\UserSessionNotFoundException;
final class SharpChatRoutes {
private IConfig $config;
@ -199,7 +197,7 @@ final class SharpChatRoutes {
try {
$sessionInfo = UserSession::byToken($authToken);
} catch(UserSessionNotFoundException $ex) {
} catch(RuntimeException $ex) {
return ['success' => false, 'reason' => 'token'];
}
@ -216,7 +214,7 @@ final class SharpChatRoutes {
try {
$userInfo = User::byId($authTokenInfo->getImpersonatedUserId());
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userInfo = $userInfoReal;
}
}
@ -297,7 +295,7 @@ final class SharpChatRoutes {
try {
$userInfo = User::byUsername($userId);
$userId = $userInfo->getId();
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
$userId = 0;
}
@ -359,13 +357,13 @@ final class SharpChatRoutes {
try {
$modInfo = User::byId((int)$modId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
return 404;
}
try {
$userInfo = User::byId((int)$userId);
} catch(UserNotFoundException $ex) {
} catch(RuntimeException $ex) {
return 404;
}
@ -380,7 +378,7 @@ final class SharpChatRoutes {
$userAddr,
$modAddr
);
} catch(UserWarningCreationFailedException $ex) {
} catch(RuntimeException $ex) {
return 500;
}

View file

@ -1,6 +0,0 @@
<?php
namespace Misuzu\Users\Assets;
use Misuzu\Users\UsersException;
class UserAssetException extends UsersException {}

View file

@ -1,16 +1,10 @@
<?php
namespace Misuzu\Users\Assets;
use InvalidArgumentException;
use RuntimeException;
use Misuzu\Users\User;
class UserImageAssetFileCreationFailedException extends UserAssetException {}
class UserImageAssetFileNotFoundException extends UserAssetException {}
class UserImageAssetInvalidImageException extends UserAssetException {}
class UserImageAssetInvalidTypeException extends UserAssetException {}
class UserImageAssetInvalidDimensionsException extends UserAssetException {}
class UserImageAssetFileTooLargeException extends UserAssetException {}
class UserImageAssetMoveFailedException extends UserAssetException {}
abstract class UserImageAsset implements UserImageAssetInterface {
public const PUBLIC_STORAGE = '/msz-storage';
@ -90,20 +84,20 @@ abstract class UserImageAsset implements UserImageAssetInterface {
public function setFromPath(string $path): void {
if(!is_file($path))
throw new UserImageAssetFileNotFoundException;
throw new InvalidArgumentException('$path not found.');
$imageInfo = getimagesize($path);
if($imageInfo === false || $imageInfo[0] < 1 || $imageInfo[1] < 1)
throw new UserImageAssetInvalidImageException;
throw new InvalidArgumentException('$path is not a valid image.');
if(!self::isAllowedType($imageInfo[2]))
throw new UserImageAssetInvalidTypeException;
throw new InvalidArgumentException('$path is not an allowed image file.');
if($imageInfo[0] > $this->getMaxWidth() || $imageInfo[1] > $this->getMaxHeight())
throw new UserImageAssetInvalidDimensionsException;
throw new InvalidArgumentException('Dimensions of $path are too large.');
if(filesize($path) > $this->getMaxBytes())
throw new UserImageAssetFileTooLargeException;
throw new InvalidArgumentException('File size of $path is too large.');
$this->delete();
@ -113,13 +107,13 @@ abstract class UserImageAsset implements UserImageAssetInterface {
mkdir($targetDir, 0775, true);
if(is_uploaded_file($path) ? !move_uploaded_file($path, $targetPath) : !copy($path, $targetPath))
throw new UserImageAssetMoveFailedException;
throw new RuntimeException('Was unable to move $path to the storage destination.');
}
public function setFromData(string $data): void {
$file = tempnam(sys_get_temp_dir(), 'msz');
if($file === false || !is_file($file))
throw new UserImageAssetFileCreationFailedException;
throw new RuntimeException('Failed to apply user asset data.');
chmod($file, 0664);
file_put_contents($file, $data);
self::setFromPath($file);

View file

@ -3,6 +3,8 @@ namespace Misuzu\Users;
use DateTime;
use DateTimeZone;
use InvalidArgumentException;
use RuntimeException;
use Index\XString;
use Index\Colour\Colour;
use Misuzu\DateCheck;
@ -15,10 +17,6 @@ use Misuzu\Parsers\Parser;
use Misuzu\Users\Assets\UserAvatarAsset;
use Misuzu\Users\Assets\UserBackgroundAsset;
class UserException extends UsersException {} // this naming definitely won't lead to confusion down the line!
class UserNotFoundException extends UserException {}
class UserCreationFailedException extends UserException {}
// Quick note to myself and others about the `display_role` column in the users database and its corresponding methods in this class.
// Never ever EVER use it for ANYTHING other than determining display colours, there's a small chance that it might not be accurate.
// And even if it were, roles properties are aggregated and thus must all be accounted for.
@ -704,7 +702,7 @@ class User implements HasRankInterface {
->executeGetId();
if($createUser < 1)
throw new UserCreationFailedException;
throw new RuntimeException('User creation failed.');
return self::byId($createUser);
}
@ -744,13 +742,13 @@ class User implements HasRankInterface {
->bind('user_id', $userId)
->fetchObject(self::class);
if(!$user)
throw new UserNotFoundException;
throw new RuntimeException('Failed to fetch user by ID.');
return $user;
});
}
public static function byUsername(string $username): ?self {
if(empty($username))
throw new UserNotFoundException;
throw new InvalidArgumentException('$username may not be empty.');
$username = mb_strtolower($username);
@ -764,13 +762,13 @@ class User implements HasRankInterface {
->bind('username', $username)
->fetchObject(self::class);
if(!$user)
throw new UserNotFoundException;
throw new RuntimeException('Failed to find user by ID.');
return $user;
});
}
public static function byEMailAddress(string $address): ?self {
if(empty($address))
throw new UserNotFoundException;
throw new InvalidArgumentException('$address may not be empty.');
$address = mb_strtolower($address);
@ -781,13 +779,13 @@ class User implements HasRankInterface {
->bind('email', $address)
->fetchObject(self::class);
if(!$user)
throw new UserNotFoundException;
throw new RuntimeException('Failed to find user by e-mail address.');
return $user;
});
}
public static function byUsernameOrEMailAddress(string $usernameOrAddress): self {
if(empty($usernameOrAddress))
throw new UserNotFoundException;
throw new InvalidArgumentException('$usernameOrAddress may not be empty.');
$usernameOrAddressLower = mb_strtolower($usernameOrAddress);
@ -803,7 +801,7 @@ class User implements HasRankInterface {
->bind('username', $usernameOrAddressLower)
->fetchObject(self::class);
if(!$user)
throw new UserNotFoundException;
throw new RuntimeException('Failed to find user by name or e-mail address.');
return $user;
});
}
@ -813,7 +811,7 @@ class User implements HasRankInterface {
}
public static function findForProfile($userIdOrName): ?self {
if(empty($userIdOrName))
throw new UserNotFoundException;
throw new InvalidArgumentException('$userIdOrName may not be empty.');
$userIdOrNameLower = mb_strtolower($userIdOrName);
@ -828,7 +826,7 @@ class User implements HasRankInterface {
->bind('username', (string)$userIdOrName)
->fetchObject(self::class);
if(!$user)
throw new UserNotFoundException;
throw new RuntimeException('Failed to find user by ID or name.');
return $user;
});
}

View file

@ -1,12 +1,9 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
use Misuzu\DB;
class UserAuthSessionException extends UsersException {}
class UserAuthSessionNotFoundException extends UserAuthSessionException {}
class UserAuthSessionCreationFailedException extends UserAuthSessionException {}
class UserAuthSession {
// Database fields
private $user_id = -1;
@ -64,17 +61,13 @@ class UserAuthSession {
->execute();
if(!$created)
throw new UserAuthSessionCreationFailedException;
throw new RuntimeException('Failed to create auth session.');
if(!$return)
return null;
try {
$object = self::byToken($token);
$object->user = $user;
return $object;
} catch(UserAuthSessionNotFoundException $ex) {
throw new UserAuthSessionCreationFailedException;
}
$object = self::byToken($token);
$object->user = $user;
return $object;
}
private static function byQueryBase(): string {
@ -86,7 +79,7 @@ class UserAuthSession {
->fetchObject(self::class);
if(!$object)
throw new UserAuthSessionNotFoundException;
throw new RuntimeException('Could not find auth session token.');
return $object;
}

View file

@ -1,6 +1,7 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
use Misuzu\ClientInfo;
use Misuzu\DB;
use Misuzu\Pagination;
@ -32,7 +33,7 @@ class UserLoginAttempt {
$this->userLookedUp = true;
try {
$this->user = User::byId($userId);
} catch(UserNotFoundException $ex) {}
} catch(RuntimeException $ex) {}
}
return $this->user;
}

View file

@ -1,12 +1,9 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
use Misuzu\DB;
class UserRecoveryTokenException extends UsersException {}
class UserRecoveryTokenNotFoundException extends UserRecoveryTokenException {}
class UserRecoveryTokenCreationFailedException extends UserRecoveryTokenException {}
class UserRecoveryToken {
// Database fields
private $user_id = -1;
@ -82,17 +79,13 @@ class UserRecoveryToken {
->execute();
if(!$created)
throw new UserRecoveryTokenCreationFailedException;
throw new RuntimeException('Failed to create password recovery token.');
if(!$return)
return null;
try {
$object = self::byToken($token);
$object->user = $user;
return $object;
} catch(UserRecoveryTokenNotFoundException $ex) {
throw new UserRecoveryTokenCreationFailedException;
}
$object = self::byToken($token);
$object->user = $user;
return $object;
}
private static function byQueryBase(): string {
@ -104,7 +97,7 @@ class UserRecoveryToken {
->fetchObject(self::class);
if(!$object)
throw new UserRecoveryTokenNotFoundException;
throw new RuntimeException('Failed to fetch recovery token.');
return $object;
}
@ -115,7 +108,7 @@ class UserRecoveryToken {
->fetchObject(self::class);
if(!$object)
throw new UserRecoveryTokenNotFoundException;
throw new RuntimeException('Failed to fetch recovery token by user and address.');
return $object;
}

View file

@ -2,16 +2,13 @@
namespace Misuzu\Users;
use ArrayAccess;
use RuntimeException;
use Index\Colour\Colour;
use Misuzu\DB;
use Misuzu\HasRankInterface;
use Misuzu\Memoizer;
use Misuzu\Pagination;
class UserRoleException extends UsersException {}
class UserRoleNotFoundException extends UserRoleException {}
class UserRoleCreationFailedException extends UserRoleException {}
class UserRole implements ArrayAccess, HasRankInterface {
public const DEFAULT = 1;
@ -184,7 +181,7 @@ class UserRole implements ArrayAccess, HasRankInterface {
) ->bind('role', $roleId)
->fetchObject(self::class);
if(!$object)
throw new UserRoleNotFoundException;
throw new RuntimeException('No role found with that ID.');
return $object;
});
}

View file

@ -1,14 +1,11 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
use Misuzu\ClientInfo;
use Misuzu\DB;
use Misuzu\Pagination;
class UserSessionException extends UsersException {}
class UserSessionCreationFailedException extends UserSessionException {}
class UserSessionNotFoundException extends UserSessionException {}
class UserSession {
public const TOKEN_SIZE = 64;
public const LIFETIME = 60 * 60 * 24 * 31;
@ -196,7 +193,7 @@ class UserSession {
->executeGetId();
if($sessionId < 1)
throw new UserSessionCreationFailedException;
throw new RuntimeException('Failed to create new session.');
return self::byId($sessionId);
}
@ -223,7 +220,7 @@ class UserSession {
->fetchObject(self::class);
if(!$session)
throw new UserSessionNotFoundException;
throw new RuntimeException('Could not find a session with that ID.');
return $session;
}
@ -233,7 +230,7 @@ class UserSession {
->fetchObject(self::class);
if(!$session)
throw new UserSessionNotFoundException;
throw new RuntimeException('Could not find a session with that token.');
return $session;
}

View file

@ -2,13 +2,10 @@
namespace Misuzu\Users;
use InvalidArgumentException;
use RuntimeException;
use Misuzu\DB;
use Misuzu\Pagination;
class UserWarningException extends UsersException {}
class UserWarningNotFoundException extends UserWarningException {}
class UserWarningCreationFailedException extends UserWarningException {}
class UserWarning {
// Informational notes on profile, only show up for moderators
public const TYPE_NOTE = 0;
@ -202,7 +199,7 @@ class UserWarning {
->executeGetId();
if($warningId < 1)
throw new UserWarningCreationFailedException;
throw new RuntimeException('Failed to create new warning.');
return self::byId($warningId);
}
@ -234,7 +231,7 @@ class UserWarning {
) ->bind('warning', $warningId)
->fetchObject(self::class);
if(!$object)
throw new UserWarningNotFoundException;
throw new RuntimeException('Not warning with that ID could be found.');
return $object;
}
public static function byUserActive(User $user): ?self {

View file

@ -1,6 +0,0 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
class UsersException extends RuntimeException {}