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": { "source": {
"type": "git", "type": "git",
"url": "https://git.flash.moe/flash/index.git", "url": "https://git.flash.moe/flash/index.git",
"reference": "4aae77900be26fccb23a7508744ef17d6b217e5f" "reference": "557f089ff79c3806f1973ee7bf82f81ab4faa5f4"
}, },
"require": { "require": {
"ext-mbstring": "*", "ext-mbstring": "*",
@ -386,7 +386,7 @@
], ],
"description": "Composer package for the common library for my projects.", "description": "Composer package for the common library for my projects.",
"homepage": "https://railgun.sh/index", "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", "name": "matomo/device-detector",

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,9 +1,9 @@
<?php <?php
namespace Misuzu; namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User; use Misuzu\Users\User;
use Misuzu\Users\UserRole; use Misuzu\Users\UserRole;
use Misuzu\Users\UserRoleNotFoundException;
$roleId = !empty($_GET['r']) && is_string($_GET['r']) ? (int)$_GET['r'] : UserRole::DEFAULT; $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']) : ''; $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 { try {
$roleInfo = UserRole::byId($roleId); $roleInfo = UserRole::byId($roleId);
} catch(UserRoleNotFoundException $ex) { } catch(RuntimeException $ex) {
echo render_error(404); echo render_error(404);
return; return;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,7 @@
<?php <?php
namespace Misuzu\SharpChat; namespace Misuzu\SharpChat;
use RuntimeException;
use Index\Colour\Colour; use Index\Colour\Colour;
use Index\Routing\IRouter; use Index\Routing\IRouter;
use Index\Http\HttpFx; use Index\Http\HttpFx;
@ -12,9 +13,6 @@ use Misuzu\Emoticons\Emotes;
use Misuzu\Users\User; use Misuzu\Users\User;
use Misuzu\Users\UserSession; use Misuzu\Users\UserSession;
use Misuzu\Users\UserWarning; use Misuzu\Users\UserWarning;
use Misuzu\Users\UserNotFoundException;
use Misuzu\Users\UserWarningCreationFailedException;
use Misuzu\Users\UserSessionNotFoundException;
final class SharpChatRoutes { final class SharpChatRoutes {
private IConfig $config; private IConfig $config;
@ -199,7 +197,7 @@ final class SharpChatRoutes {
try { try {
$sessionInfo = UserSession::byToken($authToken); $sessionInfo = UserSession::byToken($authToken);
} catch(UserSessionNotFoundException $ex) { } catch(RuntimeException $ex) {
return ['success' => false, 'reason' => 'token']; return ['success' => false, 'reason' => 'token'];
} }
@ -216,7 +214,7 @@ final class SharpChatRoutes {
try { try {
$userInfo = User::byId($authTokenInfo->getImpersonatedUserId()); $userInfo = User::byId($authTokenInfo->getImpersonatedUserId());
} catch(UserNotFoundException $ex) { } catch(RuntimeException $ex) {
$userInfo = $userInfoReal; $userInfo = $userInfoReal;
} }
} }
@ -297,7 +295,7 @@ final class SharpChatRoutes {
try { try {
$userInfo = User::byUsername($userId); $userInfo = User::byUsername($userId);
$userId = $userInfo->getId(); $userId = $userInfo->getId();
} catch(UserNotFoundException $ex) { } catch(RuntimeException $ex) {
$userId = 0; $userId = 0;
} }
@ -359,13 +357,13 @@ final class SharpChatRoutes {
try { try {
$modInfo = User::byId((int)$modId); $modInfo = User::byId((int)$modId);
} catch(UserNotFoundException $ex) { } catch(RuntimeException $ex) {
return 404; return 404;
} }
try { try {
$userInfo = User::byId((int)$userId); $userInfo = User::byId((int)$userId);
} catch(UserNotFoundException $ex) { } catch(RuntimeException $ex) {
return 404; return 404;
} }
@ -380,7 +378,7 @@ final class SharpChatRoutes {
$userAddr, $userAddr,
$modAddr $modAddr
); );
} catch(UserWarningCreationFailedException $ex) { } catch(RuntimeException $ex) {
return 500; 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 <?php
namespace Misuzu\Users\Assets; namespace Misuzu\Users\Assets;
use InvalidArgumentException;
use RuntimeException;
use Misuzu\Users\User; 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 { abstract class UserImageAsset implements UserImageAssetInterface {
public const PUBLIC_STORAGE = '/msz-storage'; public const PUBLIC_STORAGE = '/msz-storage';
@ -90,20 +84,20 @@ abstract class UserImageAsset implements UserImageAssetInterface {
public function setFromPath(string $path): void { public function setFromPath(string $path): void {
if(!is_file($path)) if(!is_file($path))
throw new UserImageAssetFileNotFoundException; throw new InvalidArgumentException('$path not found.');
$imageInfo = getimagesize($path); $imageInfo = getimagesize($path);
if($imageInfo === false || $imageInfo[0] < 1 || $imageInfo[1] < 1) 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])) 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()) 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()) if(filesize($path) > $this->getMaxBytes())
throw new UserImageAssetFileTooLargeException; throw new InvalidArgumentException('File size of $path is too large.');
$this->delete(); $this->delete();
@ -113,13 +107,13 @@ abstract class UserImageAsset implements UserImageAssetInterface {
mkdir($targetDir, 0775, true); mkdir($targetDir, 0775, true);
if(is_uploaded_file($path) ? !move_uploaded_file($path, $targetPath) : !copy($path, $targetPath)) 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 { public function setFromData(string $data): void {
$file = tempnam(sys_get_temp_dir(), 'msz'); $file = tempnam(sys_get_temp_dir(), 'msz');
if($file === false || !is_file($file)) if($file === false || !is_file($file))
throw new UserImageAssetFileCreationFailedException; throw new RuntimeException('Failed to apply user asset data.');
chmod($file, 0664); chmod($file, 0664);
file_put_contents($file, $data); file_put_contents($file, $data);
self::setFromPath($file); self::setFromPath($file);

View file

@ -3,6 +3,8 @@ namespace Misuzu\Users;
use DateTime; use DateTime;
use DateTimeZone; use DateTimeZone;
use InvalidArgumentException;
use RuntimeException;
use Index\XString; use Index\XString;
use Index\Colour\Colour; use Index\Colour\Colour;
use Misuzu\DateCheck; use Misuzu\DateCheck;
@ -15,10 +17,6 @@ use Misuzu\Parsers\Parser;
use Misuzu\Users\Assets\UserAvatarAsset; use Misuzu\Users\Assets\UserAvatarAsset;
use Misuzu\Users\Assets\UserBackgroundAsset; 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. // 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. // 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. // 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(); ->executeGetId();
if($createUser < 1) if($createUser < 1)
throw new UserCreationFailedException; throw new RuntimeException('User creation failed.');
return self::byId($createUser); return self::byId($createUser);
} }
@ -744,13 +742,13 @@ class User implements HasRankInterface {
->bind('user_id', $userId) ->bind('user_id', $userId)
->fetchObject(self::class); ->fetchObject(self::class);
if(!$user) if(!$user)
throw new UserNotFoundException; throw new RuntimeException('Failed to fetch user by ID.');
return $user; return $user;
}); });
} }
public static function byUsername(string $username): ?self { public static function byUsername(string $username): ?self {
if(empty($username)) if(empty($username))
throw new UserNotFoundException; throw new InvalidArgumentException('$username may not be empty.');
$username = mb_strtolower($username); $username = mb_strtolower($username);
@ -764,13 +762,13 @@ class User implements HasRankInterface {
->bind('username', $username) ->bind('username', $username)
->fetchObject(self::class); ->fetchObject(self::class);
if(!$user) if(!$user)
throw new UserNotFoundException; throw new RuntimeException('Failed to find user by ID.');
return $user; return $user;
}); });
} }
public static function byEMailAddress(string $address): ?self { public static function byEMailAddress(string $address): ?self {
if(empty($address)) if(empty($address))
throw new UserNotFoundException; throw new InvalidArgumentException('$address may not be empty.');
$address = mb_strtolower($address); $address = mb_strtolower($address);
@ -781,13 +779,13 @@ class User implements HasRankInterface {
->bind('email', $address) ->bind('email', $address)
->fetchObject(self::class); ->fetchObject(self::class);
if(!$user) if(!$user)
throw new UserNotFoundException; throw new RuntimeException('Failed to find user by e-mail address.');
return $user; return $user;
}); });
} }
public static function byUsernameOrEMailAddress(string $usernameOrAddress): self { public static function byUsernameOrEMailAddress(string $usernameOrAddress): self {
if(empty($usernameOrAddress)) if(empty($usernameOrAddress))
throw new UserNotFoundException; throw new InvalidArgumentException('$usernameOrAddress may not be empty.');
$usernameOrAddressLower = mb_strtolower($usernameOrAddress); $usernameOrAddressLower = mb_strtolower($usernameOrAddress);
@ -803,7 +801,7 @@ class User implements HasRankInterface {
->bind('username', $usernameOrAddressLower) ->bind('username', $usernameOrAddressLower)
->fetchObject(self::class); ->fetchObject(self::class);
if(!$user) if(!$user)
throw new UserNotFoundException; throw new RuntimeException('Failed to find user by name or e-mail address.');
return $user; return $user;
}); });
} }
@ -813,7 +811,7 @@ class User implements HasRankInterface {
} }
public static function findForProfile($userIdOrName): ?self { public static function findForProfile($userIdOrName): ?self {
if(empty($userIdOrName)) if(empty($userIdOrName))
throw new UserNotFoundException; throw new InvalidArgumentException('$userIdOrName may not be empty.');
$userIdOrNameLower = mb_strtolower($userIdOrName); $userIdOrNameLower = mb_strtolower($userIdOrName);
@ -828,7 +826,7 @@ class User implements HasRankInterface {
->bind('username', (string)$userIdOrName) ->bind('username', (string)$userIdOrName)
->fetchObject(self::class); ->fetchObject(self::class);
if(!$user) if(!$user)
throw new UserNotFoundException; throw new RuntimeException('Failed to find user by ID or name.');
return $user; return $user;
}); });
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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