Compare commits

..

No commits in common. "master" and "20240202" have entirely different histories.

76 changed files with 1353 additions and 1479 deletions

View file

@ -1,4 +1,4 @@
Copyright (c) 2017-2024, flashwave <me@flash.moe>
Copyright (c) 2017-2023, flashwave <me@flash.moe>
All rights reserved.
Redistribution and use in source and binary forms, with or without

View file

@ -49,6 +49,7 @@ const MszForumEditor = function(form) {
const uploadTask = eepromClient.create(file);
uploadTask.onProgress(prog => {
const progress = `}%`;
uploadElemProgressBarValue.style.width = `${Math.ceil(prog.progress * 100)}%`;
uploadElemProgressText.textContent = `${prog.progress.toLocaleString(undefined, { style: 'percent' })} (${prog.total - prog.loaded} bytes remaining)`;
});

369
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,14 +0,0 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
final class BaseSixtyFourEncodePmsInDb_20240602_194809 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
$conn->execute('UPDATE msz_messages SET msg_title = TO_BASE64(msg_title), msg_body = TO_BASE64(msg_body)');
$conn->execute('
ALTER TABLE `msz_messages`
CHANGE COLUMN `msg_title` `msg_title` TINYBLOB NOT NULL AFTER `msg_reply_to`,
CHANGE COLUMN `msg_body` `msg_body` BLOB NOT NULL AFTER `msg_title`;
');
}
}

593
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,8 @@
{
"dependencies": {
"@swc/core": "^1.5.24",
"autoprefixer": "^10.4.19",
"cssnano": "^6.1.2",
"postcss": "^8.4.38"
"@swc/core": "^1.3.69",
"autoprefixer": "^10.4.14",
"cssnano": "^6.0.1",
"postcss": "^8.4.26"
}
}

View file

@ -168,7 +168,7 @@ $perms = $perms->checkMany([
]);
Template::render('forum.forum', [
'forum_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($categoryInfo)),
'forum_breadcrumbs' => $forumCategories->getCategoryAncestry($categoryInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'forum_info' => $categoryInfo,
'forum_children' => $children,

View file

@ -296,7 +296,7 @@ try {
}
Template::render('forum.posting', [
'posting_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($categoryInfo)),
'posting_breadcrumbs' => $forumCategories->getCategoryAncestry($categoryInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'posting_user' => $currentUser,
'posting_user_colour' => $usersCtx->getUserColour($currentUser),

View file

@ -291,11 +291,7 @@ $postInfos = $forumPosts->getPosts(
if(empty($postInfos))
Template::throwError(404);
try {
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
$posts = [];
@ -330,7 +326,7 @@ $perms = $perms->checkMany([
]);
Template::render('forum.topic', [
'topic_breadcrumbs' => iterator_to_array($forumCategories->getCategoryAncestry($topicInfo)),
'topic_breadcrumbs' => $forumCategories->getCategoryAncestry($topicInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($topicInfo),
'topic_info' => $topicInfo,
'category_info' => $categoryInfo,

View file

@ -18,7 +18,7 @@ else
try {
$isNew = false;
$emoteInfo = $emotes->getEmote($emoteId);
$emoteStrings = iterator_to_array($emotes->getEmoteStrings($emoteInfo));
$emoteStrings = $emotes->getEmoteStrings($emoteInfo);
} catch(RuntimeException $ex) {
Template::throwError(404);
}

View file

@ -13,7 +13,7 @@ $pagination = new Pagination($auditLog->countLogs(), 50);
if(!$pagination->hasValidOffset())
Template::throwError(404);
$logs = iterator_to_array($auditLog->getLogs(pagination: $pagination));
$logs = $auditLog->getLogs(pagination: $pagination);
$userInfos = [];
$userColours = [];

View file

@ -106,7 +106,7 @@ if(CSRF::validateRequest() && $canEdit) {
}
$existingRoles = [];
foreach(iterator_to_array($roles->getRoles(userInfo: $userInfo)) as $roleInfo)
foreach($roles->getRoles(userInfo: $userInfo) as $roleInfo)
$existingRoles[$roleInfo->getId()] = $roleInfo;
$removeRoles = [];
@ -226,7 +226,7 @@ if(CSRF::validateRequest() && $canEdit) {
return;
}
$rolesAll = iterator_to_array($roles->getRoles());
$rolesAll = $roles->getRoles();
$userRoleIds = $users->hasRoles($userInfo, $rolesAll);
Template::render('manage.users.user', [

View file

@ -113,7 +113,7 @@ if($isEditing) {
if(!$perms->edit_profile) {
$notices[] = 'You\'re not allowed to edit your profile';
} else {
$profileFieldInfos = iterator_to_array($profileFields->getFields());
$profileFieldInfos = $profileFields->getFields();
$profileFieldsSetInfos = [];
$profileFieldsSetValues = [];
$profileFieldsRemove = [];
@ -299,7 +299,7 @@ $profileStats->forum_post_count = $forumCtx->countTotalUserPosts($userInfo);
$profileStats->comments_count = $msz->getComments()->countPosts(userInfo: $userInfo, deleted: false);
if(!$viewingAsGuest) {
Template::set('profile_warnings', iterator_to_array($usersCtx->getWarnings()->getWarningsWithDefaultBacklog($userInfo)));
Template::set('profile_warnings', $usersCtx->getWarnings()->getWarningsWithDefaultBacklog($userInfo));
if((!$isBanned || $canEdit)) {
$unranked = $cfg->getValues([
@ -323,9 +323,9 @@ if(!$viewingAsGuest) {
);
$activeTopicInfo = $activeTopicStats->success ? $forumTopics->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 = $profileFields->getFieldValues($userInfo);
$profileFieldInfos = $profileFieldInfos ?? $profileFields->getFields(fieldValueInfos: $isEditing ? null : $profileFieldValues);
$profileFieldFormats = $profileFields->getFieldFormats(fieldValueInfos: $profileFieldValues);
$profileFieldRawValues = [];
$profileFieldLinkValues = [];

View file

@ -116,7 +116,7 @@ if($isVerifiedRequest && !empty($_POST['current_password'])) {
if($_SERVER['REQUEST_METHOD'] === 'POST' && $isVerifiedRequest)
$userInfo = $users->getUser($userInfo->getId(), 'id');
$userRoles = iterator_to_array($roles->getRoles(userInfo: $userInfo));
$userRoles = $roles->getRoles(userInfo: $userInfo);
Template::render('settings.account', [
'errors' => $errors,

View file

@ -129,7 +129,6 @@ if(isset($_POST['action']) && is_string($_POST['action'])) {
$tmpFiles[] = db_to_zip($archive, $userInfo, 'forum_topics_redirects', ['topic_id:s', 'user_id:s:n', 'topic_redir_url:s', 'topic_redir_created:t']);
$tmpFiles[] = db_to_zip($archive, $userInfo, 'forum_topics_track', ['user_id:s', 'topic_id:s', 'forum_id:s', 'track_last_read:t']);
$tmpFiles[] = db_to_zip($archive, $userInfo, 'login_attempts', ['user_id:s:n', 'attempt_success:b', 'attempt_ip:a', 'attempt_country:s', 'attempt_created:t', 'attempt_user_agent:s']);
$tmpFiles[] = db_to_zip($archive, $userInfo, 'messages', ['msg_id:s', 'msg_owner_id:s', 'msg_author_id:s:n', 'msg_recipient_id:s:n', 'msg_reply_to:s:n', 'msg_title:s', 'msg_body:s', 'msg_parser:i', 'msg_created:t', 'msg_sent:t:n', 'msg_read:t:n', 'msg_deleted:t:n'], 'msg_owner_id');
$tmpFiles[] = db_to_zip($archive, $userInfo, 'news_posts', ['post_id:s', 'category_id:s', 'user_id:s:n', 'comment_section_id:s:n', 'post_is_featured:b', 'post_title:s', 'post_text:s', 'post_scheduled:t', 'post_created:t', 'post_updated:t', 'post_deleted:t:n']);
$tmpFiles[] = db_to_zip($archive, $userInfo, 'perms', ['user_id:s:n', 'role_id:s:n', 'forum_id:s:n', 'perms_category:s', 'perms_allow:i', 'perms_deny:i']);
$tmpFiles[] = db_to_zip($archive, $userInfo, 'perms_calculated', ['user_id:s:n', 'forum_id:s:n', 'perms_category:s', 'perms_calculated:i']);

View file

@ -15,8 +15,8 @@ $auditLog = $msz->getAuditLog();
$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 = $loginAttempts->getAttempts(userInfo: $currentUser, pagination: $loginHistoryPagination);
$auditLogs = $auditLog->getLogs(userInfo: $currentUser, pagination: $accountLogPagination);
Template::render('settings.logs', [
'login_history_list' => $loginHistory,

View file

@ -61,7 +61,7 @@ class AuditLog {
UserInfo|string|null $userInfo = null,
IPAddress|string|null $remoteAddr = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($remoteAddr instanceof IPAddress)
@ -98,8 +98,13 @@ class AuditLog {
}
$stmt->execute();
$result = $stmt->getResult();
$logs = [];
return $stmt->getResult()->getIterator(AuditLogInfo::fromResult(...));
while($result->next())
$logs[] = new AuditLogInfo($result);
return $logs;
}
public function createLog(

View file

@ -7,24 +7,20 @@ use Index\Data\IDbResult;
use Index\Net\IPAddress;
class AuditLogInfo {
public function __construct(
private ?string $userId,
private string $action,
private array $params,
private int $created,
private string $address,
private string $country,
) {}
private ?string $userId;
private string $action;
private array $params;
private int $created;
private string $address;
private string $country;
public static function fromResult(IDbResult $result): AuditLogInfo {
return new AuditLogInfo(
userId: $result->getStringOrNull(0),
action: $result->getString(1),
params: json_decode($result->getString(2)),
created: $result->getInteger(3),
address: $result->isNull(4) ? '::1' : $result->getString(4), // apparently this being NULL is possible?
country: $result->getString(5),
);
public function __construct(IDbResult $result) {
$this->userId = $result->isNull(0) ? null : (string)$result->getInteger(0);
$this->action = $result->getString(1);
$this->params = json_decode($result->getString(2));
$this->created = $result->getInteger(3);
$this->address = $result->isNull(4) ? '::1' : $result->getString(4); // apparently this being NULL is possible?
$this->country = $result->getString(5);
}
public function hasUserId(): bool {

View file

@ -7,26 +7,22 @@ use Index\Net\IPAddress;
use Misuzu\ClientInfo;
class LoginAttemptInfo {
public function __construct(
private ?string $userId,
private bool $success,
private string $remoteAddr,
private string $countryCode,
private int $created,
private string $userAgent,
private string $clientInfo,
) {}
private ?string $userId;
private bool $success;
private string $remoteAddr;
private string $countryCode;
private int $created;
private string $userAgent;
private string $clientInfo;
public static function fromResult(IDbResult $result): LoginAttemptInfo {
return new LoginAttemptInfo(
userId: $result->getStringOrNull(0),
success: $result->getBoolean(1),
remoteAddr: $result->getString(2),
countryCode: $result->getString(3),
created: $result->getInteger(4),
userAgent: $result->getString(5),
clientInfo: $result->getString(6),
);
public function __construct(IDbResult $result) {
$this->userId = $result->isNull(0) ? null : (string)$result->getInteger(0);
$this->success = $result->getInteger(1) !== 0;
$this->remoteAddr = $result->getString(2);
$this->countryCode = $result->getString(3);
$this->created = $result->getInteger(4);
$this->userAgent = $result->getString(5);
$this->clientInfo = $result->getString(6);
}
public function hasUserId(): bool {

View file

@ -83,7 +83,7 @@ class LoginAttempts {
IPAddress|string|null $remoteAddr = null,
TimeSpan|int|null $timeRange = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($remoteAddr instanceof IPAddress)
@ -127,7 +127,13 @@ class LoginAttempts {
}
$stmt->execute();
return $stmt->getResult()->getIterator(LoginAttemptInfo::fromResult(...));
$result = $stmt->getResult();
$attempts = [];
while($result->next())
$attempts[] = new LoginAttemptInfo($result);
return $attempts;
}
public function recordAttempt(

View file

@ -7,36 +7,32 @@ use Index\Net\IPAddress;
use Misuzu\ClientInfo;
class SessionInfo {
public function __construct(
private string $id,
private string $userId,
private string $token,
private string $firstRemoteAddr,
private ?string $lastRemoteAddr,
private string $userAgent,
private string $clientInfo,
private string $countryCode,
private int $expires,
private bool $bumpExpires,
private int $created,
private ?int $lastActive,
) {}
private string $id;
private string $userId;
private string $token;
private string $firstRemoteAddr;
private ?string $lastRemoteAddr;
private string $userAgent;
private string $clientInfo;
private string $countryCode;
private int $expires;
private bool $bumpExpires;
private int $created;
private ?int $lastActive;
public static function fromResult(IDbResult $result): SessionInfo {
return new SessionInfo(
id: $result->getString(0),
userId: $result->getString(1),
token: $result->getString(2),
firstRemoteAddr: $result->getString(3),
lastRemoteAddr: $result->getStringOrNull(4),
userAgent: $result->getString(5),
clientInfo: $result->getString(6),
countryCode: $result->getString(7),
expires: $result->getInteger(8),
bumpExpires: $result->getBoolean(9),
created: $result->getInteger(10),
lastActive: $result->getIntegerOrNull(11),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->userId = (string)$result->getInteger(1);
$this->token = $result->getString(2);
$this->firstRemoteAddr = $result->getString(3);
$this->lastRemoteAddr = $result->isNull(4) ? null : $result->getString(4);
$this->userAgent = $result->getString(5);
$this->clientInfo = $result->getString(6);
$this->countryCode = $result->getString(7);
$this->expires = $result->getInteger(8);
$this->bumpExpires = $result->getInteger(9) !== 0;
$this->created = $result->getInteger(10);
$this->lastActive = $result->isNull(11) ? null : $result->getInteger(11);
}
public function getId(): string {

View file

@ -58,7 +58,7 @@ class Sessions {
public function getSessions(
UserInfo|string|null $userInfo = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -85,7 +85,13 @@ class Sessions {
}
$stmt->execute();
return $stmt->getResult()->getIterator(SessionInfo::fromResult(...));
$result = $stmt->getResult();
$sessions = [];
while($result->next())
$sessions[] = new SessionInfo($result);
return $sessions;
}
public function getSession(
@ -118,7 +124,7 @@ class Sessions {
if(!$result->next())
throw new RuntimeException('Session not found.');
return SessionInfo::fromResult($result);
return new SessionInfo($result);
}
public function createSession(

View file

@ -5,24 +5,20 @@ use Index\DateTime;
use Index\Data\IDbResult;
class ChangeInfo {
public function __construct(
private string $id,
private ?string $userId,
private int $action,
private int $created,
private string $summary,
private string $body,
) {}
private string $id;
private ?string $userId;
private int $action;
private int $created;
private string $summary;
private string $body;
public static function fromResult(IDbResult $result): ChangeInfo {
return new ChangeInfo(
id: $result->getString(0),
userId: $result->getStringOrNull(1),
action: $result->getInteger(2),
created: $result->getInteger(3),
summary: $result->getString(4),
body: $result->getString(5),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->userId = $result->isNull(1) ? null : (string)$result->getInteger(1);
$this->action = $result->getInteger(2);
$this->created = $result->getInteger(3);
$this->summary = $result->getString(4);
$this->body = $result->getString(5);
}
public function getId(): string {

View file

@ -121,7 +121,7 @@ class Changelog {
DateTime|int|null $dateTime = null,
?array $tags = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($dateTime instanceof DateTime)
@ -169,7 +169,13 @@ class Changelog {
$stmt->execute();
return $stmt->getResult()->getIterator(ChangeInfo::fromResult(...));
$result = $stmt->getResult();
$changes = [];
while($result->next())
$changes[] = new ChangeInfo($result);
return $changes;
}
public function getChange(string $changeId): ChangeInfo {
@ -181,7 +187,7 @@ class Changelog {
if(!$result->next())
throw new RuntimeException('No tag with that ID exists.');
return ChangeInfo::fromResult($result);
return new ChangeInfo($result);
}
public function createChange(

View file

@ -3,12 +3,20 @@ namespace Misuzu\Changelog;
use ErrorException;
use RuntimeException;
use Index\Http\Routing\{HttpGet,RouteHandler};
use Misuzu\{Pagination,SiteInfo,Template};
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Misuzu\Pagination;
use Misuzu\SiteInfo;
use Misuzu\Template;
use Misuzu\Auth\AuthInfo;
use Misuzu\Comments\{Comments,CommentsEx};
use Misuzu\Feeds\{Feed,FeedItem,AtomFeedSerializer,RssFeedSerializer};
use Misuzu\URLs\{URLInfo,URLRegistry};
use Misuzu\Comments\Comments;
use Misuzu\Comments\CommentsEx;
use Misuzu\Feeds\Feed;
use Misuzu\Feeds\FeedItem;
use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\UsersContext;
final class ChangelogRoutes extends RouteHandler {
@ -26,7 +34,7 @@ final class ChangelogRoutes extends RouteHandler {
return $comments->getCommentsForLayout($categoryName);
}
#[HttpGet('/changelog')]
#[Route('GET', '/changelog')]
#[URLInfo('changelog-index', '/changelog', ['date' => '<date>', 'user' => '<user>', 'tags' => '<tags>', 'p' => '<page>'])]
public function getIndex($response, $request) {
$filterDate = (string)$request->getParam('date');
@ -65,16 +73,15 @@ final class ChangelogRoutes extends RouteHandler {
if(!$pagination->hasValidOffset())
return 404;
$changes = [];
$changeInfos = $this->changelog->getChanges(userInfo: $filterUser, dateTime: $filterDate, tags: $filterTags, pagination: $pagination);
$commentsCategoryName = null;
if(empty($changeInfos))
return 404;
$changes = [];
foreach($changeInfos as $changeInfo) {
$userInfo = $changeInfo->hasUserId() ? $this->usersCtx->getUserInfo($changeInfo->getUserId()) : null;
if($commentsCategoryName === null)
$commentsCategoryName = $changeInfo->getCommentsCategoryName();
$changes[] = [
'change' => $changeInfo,
'user' => $userInfo,
@ -82,20 +89,17 @@ final class ChangelogRoutes extends RouteHandler {
];
}
if(empty($changes))
return 404;
return Template::renderRaw('changelog.index', [
'changelog_infos' => $changes,
'changelog_date' => $filterDate,
'changelog_user' => $filterUser,
'changelog_tags' => $filterTags,
'changelog_pagination' => $pagination,
'comments_info' => empty($filterDate) && $commentsCategoryName !== null ? null : $this->getCommentsInfo($commentsCategoryName),
'comments_info' => empty($filterDate) ? null : $this->getCommentsInfo($changeInfos[0]->getCommentsCategoryName()),
]);
}
#[HttpGet('/changelog/change/([0-9]+)')]
#[Route('GET', '/changelog/change/:id')]
#[URLInfo('changelog-change', '/changelog/change/<change>')]
#[URLInfo('changelog-change-comments', '/changelog/change/<change>', fragment: 'comments')]
public function getChange($response, $request, string $changeId) {
@ -144,14 +148,14 @@ final class ChangelogRoutes extends RouteHandler {
return $feed;
}
#[HttpGet('/changelog.rss')]
#[Route('GET', '/changelog.rss')]
#[URLInfo('changelog-feed-rss', '/changelog.rss')]
public function getFeedRSS($response) {
$response->setContentType('application/rss+xml; charset=utf-8');
return (new RssFeedSerializer)->serializeFeed($this->createFeed('rss'));
}
#[HttpGet('/changelog.atom')]
#[Route('GET', '/changelog.atom')]
#[URLInfo('changelog-feed-atom', '/changelog.atom')]
public function getFeedAtom($response) {
$response->setContentType('application/atom+xml; charset=utf-8');

View file

@ -46,7 +46,7 @@ class Comments {
public function getCategories(
UserInfo|string|null $owner = null,
?Pagination $pagination = null
): iterable {
): array {
if($owner instanceof UserInfo)
$owner = $owner->getId();
@ -72,7 +72,13 @@ class Comments {
$stmt->execute();
return $stmt->getResult()->getIterator(CommentsCategoryInfo::fromResult(...));
$result = $stmt->getResult();
$categories = [];
while($result->next())
$categories[] = new CommentsCategoryInfo($result);
return $categories;
}
public function getCategory(
@ -118,7 +124,7 @@ class Comments {
if(!$result->next())
throw new RuntimeException('Comments category not found.');
return CommentsCategoryInfo::fromResult($result);
return new CommentsCategoryInfo($result);
}
public function checkCategoryNameExists(string $name): bool {
@ -270,7 +276,7 @@ class Comments {
?bool $deleted = null,
bool $includeRepliesCount = false,
bool $includeVotesCount = false
): iterable {
): array {
if($categoryInfo instanceof CommentsCategoryInfo)
$categoryInfo = $categoryInfo->getId();
if($parentInfo instanceof CommentsPostInfo)
@ -324,7 +330,13 @@ class Comments {
$stmt->addParameter(++$args, $userInfo instanceof UserInfo ? $userInfo->getId() : $userInfo);
$stmt->execute();
return $stmt->getResult()->getIterator(fn($result) => CommentsPostInfo::fromResult($result, $includeRepliesCount, $includeVotesCount));
$posts = [];
$result = $stmt->getResult();
while($result->next())
$posts[] = new CommentsPostInfo($result, $includeRepliesCount, $includeVotesCount);
return $posts;
}
public function getPost(
@ -350,7 +362,7 @@ class Comments {
if(!$result->next())
throw new RuntimeException('No comment with that ID exists.');
return CommentsPostInfo::fromResult($result, $includeRepliesCount, $includeVotesCount);
return new CommentsPostInfo($result, $includeRepliesCount, $includeVotesCount);
}
public function createPost(

View file

@ -6,24 +6,20 @@ use Index\Data\IDbResult;
use Misuzu\Users\UserInfo;
class CommentsCategoryInfo {
public function __construct(
private string $id,
private string $name,
private ?string $ownerId,
private int $created,
private ?int $locked,
private int $comments,
) {}
private string $id;
private string $name;
private ?string $ownerId;
private int $created;
private ?int $locked;
private int $comments;
public static function fromResult(IDbResult $result): CommentsCategoryInfo {
return new CommentsCategoryInfo(
id: $result->getString(0),
name: $result->getString(1),
ownerId: $result->getStringOrNull(2),
created: $result->getInteger(3),
locked: $result->getIntegerOrNull(4),
comments: $result->getInteger(5),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->name = $result->getString(1);
$this->ownerId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->created = $result->getInteger(3);
$this->locked = $result->isNull(4) ? null : $result->getInteger(4);
$this->comments = $result->getInteger(5);
}
public function getId(): string {

View file

@ -5,53 +5,47 @@ use Index\DateTime;
use Index\Data\IDbResult;
class CommentsPostInfo {
public function __construct(
private string $id,
private string $categoryId,
private ?string $userId,
private ?string $replyingTo,
private string $body,
private int $created,
private ?int $pinned,
private ?int $updated,
private ?int $deleted,
private int $replies,
private int $votesTotal,
private int $votesPositive,
private int $votesNegative,
) {}
private string $id;
private string $categoryId;
private ?string $userId;
private ?string $replyingTo;
private string $body;
private int $created;
private ?int $pinned;
private ?int $updated;
private ?int $deleted;
private int $replies;
private int $votesTotal;
private int $votesPositive;
private int $votesNegative;
public static function fromResult(
public function __construct(
IDbResult $result,
bool $includeRepliesCount = false,
bool $includeVotesCount = false
): CommentsPostInfo {
$args = [];
$count = 0;
) {
$args = 0;
$this->id = (string)$result->getInteger($args);
$this->categoryId = (string)$result->getInteger(++$args);
$this->userId = $result->isNull(++$args) ? null : (string)$result->getInteger($args);
$this->replyingTo = $result->isNull(++$args) ? null : (string)$result->getInteger($args);
$this->body = $result->getString(++$args);
$this->created = $result->getInteger(++$args);
$this->pinned = $result->isNull(++$args) ? null : $result->getInteger($args);
$this->updated = $result->isNull(++$args) ? null : $result->getInteger($args);
$this->deleted = $result->isNull(++$args) ? null : $result->getInteger($args);
$args[] = $result->getString($count); // id
$args[] = $result->getString(++$count); // categoryId
$args[] = $result->getStringOrNull(++$count); // userId
$args[] = $result->getStringOrNull(++$count); // replyingTo
$args[] = $result->getString(++$count); // body
$args[] = $result->getInteger(++$count); // created
$args[] = $result->getIntegerOrNull(++$count); // pinned
$args[] = $result->getIntegerOrNull(++$count); // updated
$args[] = $result->getIntegerOrNull(++$count); // deleted
$args[] = $includeRepliesCount ? $result->getInteger(++$count) : 0;
$this->replies = $includeRepliesCount ? $result->getInteger(++$args) : 0;
if($includeVotesCount) {
$args[] = $result->getInteger(++$count); // votesTotal
$args[] = $result->getInteger(++$count); // votesPositive
$args[] = $result->getInteger(++$count); // votesNegative
$this->votesTotal = $result->getInteger(++$args);
$this->votesPositive = $result->getInteger(++$args);
$this->votesNegative = $result->getInteger(++$args);
} else {
$args[] = 0;
$args[] = 0;
$args[] = 0;
$this->votesTotal = 0;
$this->votesPositive = 0;
$this->votesNegative = 0;
}
return new CommentsPostInfo(...$args);
}
public function getId(): string {

View file

@ -5,18 +5,14 @@ use Index\DateTime;
use Index\Data\IDbResult;
class CounterInfo {
public function __construct(
private string $name,
private int $value,
private int $updated,
) {}
private string $name;
private int $value;
private int $updated;
public static function fromResult(IDbResult $result): CounterInfo {
return new CounterInfo(
name: $result->getString(0),
value: $result->getInteger(1),
updated: $result->getInteger(2),
);
public function __construct(IDbResult $result) {
$this->name = $result->getString(0);
$this->value = $result->getInteger(1);
$this->updated = $result->getInteger(2);
}
public function getName(): string {

View file

@ -25,7 +25,7 @@ class Counters {
public function getCounters(
?string $orderBy = null,
?Pagination $pagination = null
): iterable {
): array {
$hasOrderBy = $orderBy !== null;
$hasPagination = $pagination !== null;
@ -47,7 +47,13 @@ class Counters {
}
$stmt->execute();
return $stmt->getResult()->getIterator(CounterInfo::fromResult(...));
$result = $stmt->getResult();
$counters = [];
while($result->next())
$counters[] = new CounterInfo($result);
return $counters;
}
public function get(array|string $names): array|int {

View file

@ -5,20 +5,16 @@ use Stringable;
use Index\Data\IDbResult;
class EmoteInfo implements Stringable {
public function __construct(
private string $id,
private int $order,
private int $rank,
private string $url,
) {}
private string $id;
private int $order;
private int $rank;
private string $url;
public static function fromResult(IDbResult $result): EmoteInfo {
return new EmoteInfo(
id: $result->getString(0),
order: $result->getInteger(1),
rank: $result->getInteger(2),
url: $result->getString(3),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->order = $result->getInteger(1);
$this->rank = $result->getInteger(2);
$this->url = $result->getString(3);
}
public function getId(): string {

View file

@ -5,18 +5,14 @@ use Stringable;
use Index\Data\IDbResult;
class EmoteStringInfo implements Stringable {
public function __construct(
private string $emoteId,
private int $order,
private string $string,
) {}
private string $emoteId;
private int $order;
private string $string;
public static function fromResult(IDbResult $result): EmoteStringInfo {
return new EmoteStringInfo(
emoteId: $result->getString(0),
order: $result->getInteger(1),
string: $result->getString(2),
);
public function __construct(IDbResult $result) {
$this->emoteId = (string)$result->getInteger(0);
$this->order = $result->getInteger(1);
$this->string = $result->getString(2);
}
public function getEmoteId(): string {

View file

@ -31,7 +31,7 @@ class Emotes {
if(!$result->next())
throw new RuntimeException('No emoticon with that ID exists.');
return EmoteInfo::fromResult($result);
return new EmoteInfo($result);
}
public static function emoteOrderOptions(): array {
@ -43,7 +43,7 @@ class Emotes {
?int $minRank = null,
?string $orderBy = null,
?bool $reverse = null
): iterable {
): array {
$hasMinRank = $minRank !== null;
$hasOrderBy = $orderBy !== null;
$hasReverse = $reverse !== null;
@ -65,7 +65,13 @@ class Emotes {
$stmt->addParameter(1, $minRank);
$stmt->execute();
return $stmt->getResult()->getIterator(EmoteInfo::fromResult(...));
$emotes = [];
$result = $stmt->getResult();
while($result->next())
$emotes[] = new EmoteInfo($result);
return $emotes;
}
private static function checkEmoteUrlInternal(string $url): string {
@ -150,7 +156,7 @@ class Emotes {
$stmt->execute();
}
public function getEmoteStrings(EmoteInfo|string $infoOrId): iterable {
public function getEmoteStrings(EmoteInfo|string $infoOrId): array {
if($infoOrId instanceof EmoteInfo)
$infoOrId = $infoOrId->getId();
@ -158,7 +164,13 @@ class Emotes {
$stmt->addParameter(1, $infoOrId);
$stmt->execute();
return $stmt->getResult()->getIterator(EmoteStringInfo::fromResult(...));
$strings = [];
$result = $stmt->getResult();
while($result->next())
$strings[] = new EmoteStringInfo($result);
return $strings;
}
private static function checkEmoteStringInternal(string $string): string {

View file

@ -12,20 +12,19 @@ use Misuzu\Pagination;
use Misuzu\Users\UserInfo;
class ForumCategories {
private IDbConnection $dbConn;
private DbStatementCache $cache;
public function __construct(IDbConnection $dbConn) {
$this->dbConn = $dbConn;
$this->cache = new DbStatementCache($dbConn);
}
public static function convertCategoryListToTree(
iterable $catInfos,
array $catInfos,
ForumCategoryInfo|string|null $parentInfo = null,
?Colour $colour = null
): array {
if(!is_array($catInfos))
$catInfos = iterator_to_array($catInfos);
$colour ??= Colour::none();
$tree = [];
$predicate = $parentInfo
@ -104,7 +103,7 @@ class ForumCategories {
?bool $hidden = null,
bool $asTree = false,
?Pagination $pagination = null
): iterable {
): array {
$isRootParent = false;
$hasParentInfo = $parentInfo !== false;
$hasType = $type !== null;
@ -156,7 +155,11 @@ class ForumCategories {
}
$stmt->execute();
$cats = $stmt->getResult()->getIterator(ForumCategoryInfo::fromResult(...));
$result = $stmt->getResult();
$cats = [];
while($result->next())
$cats[] = new ForumCategoryInfo($result);
if($asTree)
$cats = self::convertCategoryListToTree($cats);
@ -213,7 +216,7 @@ class ForumCategories {
if(!$result->next())
throw new RuntimeException('Forum category info not found.');
return ForumCategoryInfo::fromResult($result);
return new ForumCategoryInfo($result);
}
public function updateCategory(
@ -258,7 +261,7 @@ class ForumCategories {
public function getCategoryAncestry(
ForumCategoryInfo|ForumTopicInfo|ForumPostInfo|string $categoryInfo
): iterable {
): array {
if($categoryInfo instanceof ForumCategoryInfo)
$categoryInfo = $categoryInfo->getId();
elseif($categoryInfo instanceof ForumTopicInfo || $categoryInfo instanceof ForumPostInfo)
@ -274,7 +277,13 @@ class ForumCategories {
$stmt->addParameter(1, $categoryInfo);
$stmt->execute();
return $stmt->getResult()->getIterator(ForumCategoryInfo::fromResult(...));
$result = $stmt->getResult();
$cats = [];
while($result->next())
$cats[] = new ForumCategoryInfo($result);
return $cats;
}
public function getCategoryChildren(
@ -282,7 +291,7 @@ class ForumCategories {
bool $includeSelf = false,
?bool $hidden = null,
bool $asTree = false
): iterable {
): array {
if($parentInfo instanceof ForumCategoryInfo)
$parentInfo = $parentInfo->getId();
@ -310,7 +319,11 @@ class ForumCategories {
$stmt->addParameter(++$args, $parentInfo);
$stmt->execute();
$cats = $stmt->getResult()->getIterator(ForumCategoryInfo::fromResult(...));
$result = $stmt->getResult();
$cats = [];
while($result->next())
$cats[] = new ForumCategoryInfo($result);
if($asTree)
$cats = self::convertCategoryListToTree($cats, $parentInfo);

View file

@ -26,42 +26,38 @@ class ForumCategoryInfo {
self::TYPE_DISCUSSION,
];
public function __construct(
private string $id,
private int $order,
private ?string $parentId,
private string $name,
private int $type,
private ?string $desc,
private ?string $icon,
private ?int $colour,
private ?string $link,
private ?int $clicks,
private int $created,
private bool $archived,
private bool $hidden,
private int $topicsCount,
private int $postsCount,
) {}
private string $id;
private int $order;
private ?string $parentId;
private string $name;
private int $type;
private ?string $desc;
private ?string $icon;
private ?int $colour;
private ?string $link;
private ?int $clicks;
private int $created;
private bool $archived;
private bool $hidden;
private int $topicsCount;
private int $postsCount;
public static function fromResult(IDbResult $result): ForumCategoryInfo {
return new ForumCategoryInfo(
id: $result->getString(0),
order: $result->getInteger(1),
parentId: $result->getStringOrNull(2),
name: $result->getString(3),
type: $result->getInteger(4),
desc: $result->getStringOrNull(5),
icon: $result->getStringOrNull(6),
colour: $result->getIntegerOrNull(7),
link: $result->getStringOrNull(8),
clicks: $result->getIntegerOrNull(9),
created: $result->getInteger(10),
archived: $result->getBoolean(11),
hidden: $result->getBoolean(12),
topicsCount: $result->getInteger(13),
postsCount: $result->getInteger(14),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->order = $result->getInteger(1);
$this->parentId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->name = $result->getString(3);
$this->type = $result->getInteger(4);
$this->desc = $result->isNull(5) ? null : $result->getString(5);
$this->icon = $result->isNull(6) ? null : $result->getString(6);
$this->colour = $result->isNull(7) ? null : $result->getInteger(7);
$this->link = $result->isNull(8) ? null : $result->getString(8);
$this->clicks = $result->isNull(9) ? null : $result->getInteger(9);
$this->created = $result->getInteger(10);
$this->archived = $result->getInteger(11) !== 0;
$this->hidden = $result->getInteger(12) !== 0;
$this->topicsCount = $result->getInteger(13);
$this->postsCount = $result->getInteger(14);
}
public function getId(): string {

View file

@ -7,34 +7,30 @@ use Index\Net\IPAddress;
use Misuzu\Parsers\Parser;
class ForumPostInfo {
public function __construct(
private string $id,
private string $topicId,
private string $categoryId,
private ?string $userId,
private string $remoteAddr,
private string $body,
private int $parser,
private bool $displaySignature,
private int $created,
private ?int $edited,
private ?int $deleted,
) {}
private string $id;
private string $topicId;
private string $categoryId;
private ?string $userId;
private string $remoteAddr;
private string $body;
private int $parser;
private bool $displaySignature;
private int $created;
private ?int $edited;
private ?int $deleted;
public static function fromResult(IDbResult $result): ForumPostInfo {
return new ForumPostInfo(
id: $result->getString(0),
topicId: $result->getString(1),
categoryId: $result->getString(2),
userId: $result->getStringOrNull(3),
remoteAddr: $result->getString(4),
body: $result->getString(5),
parser: $result->getInteger(6),
displaySignature: $result->getBoolean(7),
created: $result->getInteger(8),
edited: $result->getIntegerOrNull(9),
deleted: $result->getIntegerOrNull(10),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->topicId = (string)$result->getInteger(1);
$this->categoryId = (string)$result->getInteger(2);
$this->userId = $result->isNull(3) ? null : (string)$result->getInteger(3);
$this->remoteAddr = $result->getString(4);
$this->body = $result->getString(5);
$this->parser = $result->getInteger(6);
$this->displaySignature = $result->getInteger(7) !== 0;
$this->created = $result->getInteger(8);
$this->edited = $result->isNull(9) ? null : $result->getInteger(9);
$this->deleted = $result->isNull(10) ? null : $result->getInteger(10);
}
public function getId(): string {

View file

@ -84,7 +84,7 @@ class ForumPosts {
?array $searchQuery = null,
?bool $deleted = null,
?Pagination $pagination = null
): iterable {
): array {
// remove this hack when search server
$hasSearchQuery = $searchQuery !== null;
$doSearchOrder = false;
@ -189,7 +189,13 @@ class ForumPosts {
}
$stmt->execute();
return $stmt->getResult()->getIterator(ForumPostInfo::fromResult(...));
$result = $stmt->getResult();
$posts = [];
while($result->next())
$posts[] = new ForumPostInfo($result);
return $posts;
}
public function getPost(
@ -261,7 +267,7 @@ class ForumPosts {
if(!$result->next())
throw new RuntimeException('Forum post not found.');
return ForumPostInfo::fromResult($result);
return new ForumPostInfo($result);
}
public function createPost(

View file

@ -17,36 +17,32 @@ class ForumTopicInfo {
'global' => self::TYPE_GLOBAL,
];
public function __construct(
private string $id,
private string $categoryId,
private ?string $userId,
private int $type,
private string $title,
private int $postsCount,
private int $deletedPostsCount,
private int $viewsCount,
private int $created,
private int $bumped,
private ?int $deleted,
private ?int $locked,
) {}
private string $id;
private string $categoryId;
private ?string $userId;
private int $type;
private string $title;
private int $postsCount;
private int $deletedPostsCount;
private int $viewsCount;
private int $created;
private int $bumped;
private ?int $deleted;
private ?int $locked;
public static function fromResult(IDbResult $result): ForumTopicInfo {
return new ForumTopicInfo(
id: $result->getString(0),
categoryId: $result->getString(1),
userId: $result->getStringOrNull(2),
type: $result->getInteger(3),
title: $result->getString(4),
viewsCount: $result->getInteger(5),
created: $result->getInteger(6),
bumped: $result->getInteger(7),
deleted: $result->getIntegerOrNull(8),
locked: $result->getIntegerOrNull(9),
postsCount: $result->getInteger(10),
deletedPostsCount: $result->getInteger(11),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->categoryId = (string)$result->getInteger(1);
$this->userId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->type = $result->getInteger(3);
$this->title = $result->getString(4);
$this->viewsCount = $result->getInteger(5);
$this->created = $result->getInteger(6);
$this->bumped = $result->getInteger(7);
$this->deleted = $result->isNull(8) ? null : $result->getInteger(8);
$this->locked = $result->isNull(9) ? null : $result->getInteger(9);
$this->postsCount = $result->getInteger(10);
$this->deletedPostsCount = $result->getInteger(11);
}
public function getId(): string {

View file

@ -5,20 +5,16 @@ use Index\DateTime;
use Index\Data\IDbResult;
class ForumTopicRedirectInfo {
public function __construct(
private string $topicId,
private ?string $userId,
private string $link,
private int $created,
) {}
private string $topicId;
private ?string $userId;
private string $link;
private int $created;
public static function fromResult(IDbResult $result): ForumTopicRedirectInfo {
return new ForumTopicRedirectInfo(
topicId: $result->getString(0),
userId: $result->getStringOrNull(1),
link: $result->getString(2),
created: $result->getInteger(3),
);
public function __construct(IDbResult $result) {
$this->topicId = (string)$result->getInteger(0);
$this->userId = $result->isNull(1) ? null : (string)$result->getInteger(1);
$this->link = $result->getString(2);
$this->created = $result->getInteger(3);
}
public function getTopicId(): string {

View file

@ -38,7 +38,7 @@ class ForumTopicRedirects {
public function getTopicRedirects(
UserInfo|string|null $userInfo = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -61,7 +61,13 @@ class ForumTopicRedirects {
}
$stmt->execute();
return $stmt->getResult()->getIterator(ForumTopicRedirectInfo::fromResult(...));
$result = $stmt->getResult();
$redirs = [];
while($result->next())
$redirs[] = new ForumTopicRedirectInfo($result);
return $redirs;
}
public function hasTopicRedirect(ForumTopicInfo|string $topicInfo): bool {
@ -91,7 +97,7 @@ class ForumTopicRedirects {
if(!$result->next())
throw new RuntimeException('Could not find that forum topic redirect.');
return ForumTopicRedirectInfo::fromResult($result);
return new ForumTopicRedirectInfo($result);
}
public function createTopicRedirect(

View file

@ -91,7 +91,7 @@ class ForumTopics {
?bool $global = null,
?bool $deleted = null,
?Pagination $pagination = null
): iterable {
): array {
// remove this hack when search server
$hasSearchQuery = $searchQuery !== null;
$hasAfterTopicId = false;
@ -194,7 +194,13 @@ class ForumTopics {
}
$stmt->execute();
return $stmt->getResult()->getIterator(ForumTopicInfo::fromResult(...));
$result = $stmt->getResult();
$topics = [];
while($result->next())
$topics[] = new ForumTopicInfo($result);
return $topics;
}
public function getTopic(
@ -233,7 +239,7 @@ class ForumTopics {
if(!$result->next())
throw new RuntimeException('Forum topic not found.');
return ForumTopicInfo::fromResult($result);
return new ForumTopicInfo($result);
}
public function createTopic(

View file

@ -3,10 +3,14 @@ namespace Misuzu\Home;
use RuntimeException;
use Index\DateTime;
use Index\Data\{DbTools,IDbConnection};
use Index\Http\Routing\{HttpGet,RouteHandler};
use Index\Data\DbTools;
use Index\Data\IDbConnection;
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Syokuhou\IConfig;
use Misuzu\{Pagination,SiteInfo,Template};
use Misuzu\Pagination;
use Misuzu\SiteInfo;
use Misuzu\Template;
use Misuzu\Auth\AuthInfo;
use Misuzu\Changelog\Changelog;
use Misuzu\Comments\Comments;
@ -39,7 +43,7 @@ class HomeRoutes extends RouteHandler {
]);
}
private function getOnlineUsers(): iterable {
private function getOnlineUsers(): array {
return $this->usersCtx->getUsers()->getUsers(
lastActiveInMinutes: 5,
deleted: false,
@ -49,14 +53,14 @@ class HomeRoutes extends RouteHandler {
private array $newsCategoryInfos = [];
private function getFeaturedNewsPosts(int $amount, bool $decorate): iterable {
private function getFeaturedNewsPosts(int $amount, bool $decorate): array {
$postInfos = $this->news->getPosts(
onlyFeatured: true,
pagination: new Pagination($amount)
);
if(!$decorate)
return iterator_to_array($postInfos);
return $postInfos;
$posts = [];
@ -150,7 +154,7 @@ class HomeRoutes extends RouteHandler {
return $topics;
}
#[HttpGet('/')]
#[Route('GET', '/')]
#[URLInfo('index', '/')]
public function getIndex(...$args) {
return $this->authInfo->isLoggedIn()
@ -160,9 +164,9 @@ class HomeRoutes extends RouteHandler {
public function getHome() {
$stats = $this->getStats();
$onlineUserInfos = iterator_to_array($this->getOnlineUsers());
$onlineUserInfos = $this->getOnlineUsers();
$featuredNews = $this->getFeaturedNewsPosts(5, true);
$changelog = iterator_to_array($this->changelog->getChanges(pagination: new Pagination(10)));
$changelog = $this->changelog->getChanges(pagination: new Pagination(10));
$stats['users:online:recent'] = count($onlineUserInfos);
@ -197,7 +201,7 @@ class HomeRoutes extends RouteHandler {
]);
}
#[HttpGet('/_landing')]
#[Route('GET', '/_landing')]
public function getLanding($response, $request) {
$config = $this->config->getValues([
['social.embed_linked:b'],
@ -217,7 +221,7 @@ class HomeRoutes extends RouteHandler {
} else $linkedData = null;
$stats = $this->getStats();
$onlineUserInfos = iterator_to_array($this->getOnlineUsers());
$onlineUserInfos = $this->getOnlineUsers();
$featuredNews = $this->getFeaturedNewsPosts(3, false);
$popularTopics = $this->getPopularForumTopics($config['landing.forum_categories']);
$activeTopics = $this->getActiveForumTopics($config['landing.forum_categories']);

View file

@ -1,7 +1,8 @@
<?php
namespace Misuzu\Info;
use Index\Http\Routing\{HttpGet,RouteHandler};
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Misuzu\Template;
use Misuzu\Parsers\Parser;
use Misuzu\URLs\URLInfo;
@ -17,16 +18,23 @@ class InfoRoutes extends RouteHandler {
'index' => 'Index Project » %s',
];
#[HttpGet('/info')]
private static function checkName(string $name): bool {
return preg_match('#^([A-Za-z0-9_]+)$#', $name) === 1;
}
#[Route('GET', '/info')]
#[URLInfo('info-index', '/info')]
public function getIndex() {
return Template::renderRaw('info.index');
}
#[HttpGet('/info/([A-Za-z0-9_]+)')]
#[Route('GET', '/info/:name')]
#[URLInfo('info', '/info/<title>')]
#[URLInfo('info-doc', '/info/<title>')]
public function getDocsPage($response, $request, string $name) {
if(!self::checkName($name))
return 404;
return $this->serveMarkdownDocument(
sprintf('%s/%s.md', self::DOCS_PATH, $name)
);
@ -70,11 +78,13 @@ class InfoRoutes extends RouteHandler {
return '';
}
#[HttpGet('/info/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)')]
#[Route('GET', '/info/:project/:name')]
#[URLInfo('info-project-doc', '/info/<project>/<title>')]
public function getProjectPage($response, $request, string $project, string $name) {
if(!array_key_exists($project, self::PROJECT_PATHS))
return 404;
if(!self::checkName($name))
return 404;
$projectPath = self::PROJECT_PATHS[$project];
$titleSuffix = array_key_exists($project, self::PROJECT_SUFFIXES) ? self::PROJECT_SUFFIXES[$project] : '';

View file

@ -1,8 +1,11 @@
<?php
namespace Misuzu;
use Index\Http\Routing\{HttpGet,RouteHandler};
use Misuzu\URLs\{IURLSource,URLInfo,URLRegistry};
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Misuzu\URLs\IURLSource;
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;
class LegacyRoutes extends RouteHandler implements IURLSource {
public function __construct(
@ -121,27 +124,27 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
$urls->register('manage-role', '/manage/users/role.php', ['r' => '<role>']);
}
#[HttpGet('/index.php')]
#[Route('GET', '/index.php')]
public function getIndexPHP($response): void {
$response->redirect($this->urls->format('index'), true);
}
#[HttpGet('/info.php')]
#[Route('GET', '/info.php')]
public function getInfoPHP($response): void {
$response->redirect($this->urls->format('info'), true);
}
#[HttpGet('/info.php/([A-Za-z0-9_]+)')]
#[Route('GET', '/info.php/:name')]
public function getInfoDocsPHP($response, $request, string $name): void {
$response->redirect($this->urls->format('info', ['title' => $name]), true);
}
#[HttpGet('/info.php/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)')]
#[Route('GET', '/info.php/:project/:name')]
public function getInfoProjectPHP($response, $request, string $project, string $name): void {
$response->redirect($this->urls->format('info', ['title' => $project . '/' . $name]), true);
}
#[HttpGet('/news.php')]
#[Route('GET', '/news.php')]
public function getNewsPHP($response, $request): void {
$postId = (int)($request->getParam('n', FILTER_SANITIZE_NUMBER_INT) ?? $request->getParam('p', FILTER_SANITIZE_NUMBER_INT));
@ -156,28 +159,28 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
$response->redirect($location, true);
}
#[HttpGet('/news.php/rss')]
#[Route('GET', '/news.php/rss')]
public function getNewsRssPHP($response, $request): void {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = $this->urls->format($catId > 0 ? 'news-category-feed-rss' : 'news-feed-rss', ['category' => $catId]);
$response->redirect($location, true);
}
#[HttpGet('/news.php/atom')]
#[Route('GET', '/news.php/atom')]
public function getNewsAtomPHP($response, $request): void {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = $this->urls->format($catId > 0 ? 'news-category-feed-atom' : 'news-feed-atom', ['category' => $catId]);
$response->redirect($location, true);
}
#[HttpGet('/news/index.php')]
#[Route('GET', '/news/index.php')]
public function getNewsIndexPHP($response, $request): void {
$response->redirect($this->urls->format('news-index', [
'page' => $request->getParam('page', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
#[HttpGet('/news/category.php')]
#[Route('GET', '/news/category.php')]
public function getNewsCategoryPHP($response, $request): void {
$response->redirect($this->urls->format('news-category', [
'category' => $request->getParam('c', FILTER_SANITIZE_NUMBER_INT),
@ -185,19 +188,19 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
]), true);
}
#[HttpGet('/news/post.php')]
#[Route('GET', '/news/post.php')]
public function getNewsPostPHP($response, $request): void {
$response->redirect($this->urls->format('news-post', [
'post' => $request->getParam('p', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
#[HttpGet('/news/feed.php')]
#[Route('GET', '/news/feed.php')]
public function getNewsFeedPHP($response, $request): int {
return 400;
}
#[HttpGet('/news/feed.php/rss')]
#[Route('GET', '/news/feed.php/rss')]
public function getNewsFeedRssPHP($response, $request): void {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect($this->urls->format(
@ -206,7 +209,7 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
), true);
}
#[HttpGet('/news/feed.php/atom')]
#[Route('GET', '/news/feed.php/atom')]
public function getNewsFeedAtomPHP($response, $request): void {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect($this->urls->format(
@ -215,7 +218,7 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
), true);
}
#[HttpGet('/changelog.php')]
#[Route('GET', '/changelog.php')]
public function getChangelogPHP($response, $request): void {
$changeId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
if($changeId) {
@ -229,7 +232,7 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
]), true);
}
#[HttpGet('/auth.php')]
#[Route('GET', '/auth.php')]
public function getAuthPHP($response, $request): void {
$response->redirect($this->urls->format(match($request->getParam('m')) {
'logout' => 'auth-logout',
@ -240,44 +243,44 @@ class LegacyRoutes extends RouteHandler implements IURLSource {
}), true);
}
#[HttpGet('/auth')]
#[HttpGet('/auth/index.php')]
#[Route('GET', '/auth')]
#[Route('GET', '/auth/index.php')]
public function getAuthIndexPHP($response, $request): void {
$response->redirect($this->urls->format('auth-login'), true);
}
#[HttpGet('/settings.php')]
#[Route('GET', '/settings.php')]
public function getSettingsPHP($response): void {
$response->redirect($this->urls->format('settings-index'), true);
}
#[HttpGet('/settings')]
#[Route('GET', '/settings')]
public function getSettingsIndex($response): void {
$response->redirect($this->urls->format('settings-account'));
}
#[HttpGet('/settings/index.php')]
#[Route('GET', '/settings/index.php')]
public function getSettingsIndexPHP($response): void {
$response->redirect($this->urls->format('settings-account'), true);
}
#[HttpGet('/manage')]
#[Route('GET', '/manage')]
#[URLInfo('manage-index', '/manage')]
public function getManageIndex($response): void {
$response->redirect($this->urls->format('manage-general-overview'));
}
#[HttpGet('/manage/index.php')]
#[Route('GET', '/manage/index.php')]
public function getManageIndexPHP($response): void {
$response->redirect($this->urls->format('manage-general-overview'), true);
}
#[HttpGet('/manage/news')]
#[Route('GET', '/manage/news')]
public function getManageNewsIndex($response): void {
$response->redirect($this->urls->format('manage-news-categories'));
}
#[HttpGet('/manage/news/index.php')]
#[Route('GET', '/manage/news/index.php')]
public function getManageNewsIndexPHP($response): void {
$response->redirect($this->urls->format('manage-news-categories'), true);
}

View file

@ -6,36 +6,32 @@ use Index\Data\IDbResult;
use Misuzu\Parsers\Parser;
class MessageInfo {
public function __construct(
private string $messageId,
private string $ownerId,
private ?string $authorId,
private ?string $recipientId,
private ?string $replyTo,
private string $title,
private string $body,
private int $parser,
private int $created,
private ?int $sent,
private ?int $read,
private ?int $deleted,
) {}
private string $messageId;
private string $ownerId;
private ?string $authorId;
private ?string $recipientId;
private ?string $replyTo;
private string $title;
private string $body;
private int $parser;
private int $created;
private ?int $sent;
private ?int $read;
private ?int $deleted;
public static function fromResult(IDbResult $result): MessageInfo {
return new MessageInfo(
messageId: $result->getString(0),
ownerId: $result->getString(1),
authorId: $result->getStringOrNull(2),
recipientId: $result->getStringOrNull(3),
replyTo: $result->getStringOrNull(4),
title: $result->getString(5),
body: $result->getString(6),
parser: $result->getInteger(7),
created: $result->getInteger(8),
sent: $result->getIntegerOrNull(9),
read: $result->getIntegerOrNull(10),
deleted: $result->getIntegerOrNull(11),
);
public function __construct(IDbResult $result) {
$this->messageId = $result->getString(0);
$this->ownerId = $result->getString(1);
$this->authorId = $result->getStringOrNull(2);
$this->recipientId = $result->getStringOrNull(3);
$this->replyTo = $result->getStringOrNull(4);
$this->title = $result->getString(5);
$this->body = $result->getString(6);
$this->parser = $result->getInteger(7);
$this->created = $result->getInteger(8);
$this->sent = $result->getIntegerOrNull(9);
$this->read = $result->getIntegerOrNull(10);
$this->deleted = $result->getIntegerOrNull(11);
}
public function getId(): string {

View file

@ -11,7 +11,7 @@ use Misuzu\Users\UserInfo;
class MessagesDatabase {
private DbStatementCache $cache;
public function __construct(IDbConnection $dbConn) {
public function __construct(private IDbConnection $dbConn) {
$this->cache = new DbStatementCache($dbConn);
}
@ -92,7 +92,7 @@ class MessagesDatabase {
?bool $read = null,
?bool $deleted = null,
?Pagination $pagination = null
): iterable {
): array {
$hasOwnerInfo = $ownerInfo !== null;
$hasAuthorInfo = $authorInfo !== null;
$hasRecipientInfo = $recipientInfo !== null;
@ -104,7 +104,7 @@ class MessagesDatabase {
$hasPagination = $pagination !== null;
$args = 0;
$query = 'SELECT msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, FROM_BASE64(msg_title), FROM_BASE64(msg_body), msg_parser, UNIX_TIMESTAMP(msg_created), UNIX_TIMESTAMP(msg_sent), UNIX_TIMESTAMP(msg_read), UNIX_TIMESTAMP(msg_deleted) FROM msz_messages';
$query = 'SELECT msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, msg_title, msg_body, msg_parser, UNIX_TIMESTAMP(msg_created), UNIX_TIMESTAMP(msg_sent), UNIX_TIMESTAMP(msg_read), UNIX_TIMESTAMP(msg_deleted) FROM msz_messages';
if($hasOwnerInfo) {
++$args;
$query .= ' WHERE msg_owner_id = ?';
@ -153,7 +153,13 @@ class MessagesDatabase {
$stmt->execute();
return $stmt->getResult()->getIterator(MessageInfo::fromResult(...));
$infos = [];
$result = $stmt->getResult();
while($result->next())
$infos[] = new MessageInfo($result);
return $infos;
}
public function getMessageInfo(
@ -162,7 +168,7 @@ class MessagesDatabase {
bool $useReplyTo = false
): MessageInfo {
$stmt = $this->cache->get(sprintf(
'SELECT msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, FROM_BASE64(msg_title), FROM_BASE64(msg_body), msg_parser, UNIX_TIMESTAMP(msg_created), UNIX_TIMESTAMP(msg_sent), UNIX_TIMESTAMP(msg_read), UNIX_TIMESTAMP(msg_deleted) FROM msz_messages WHERE msg_id = %s AND msg_owner_id = ?',
'SELECT msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, msg_title, msg_body, msg_parser, UNIX_TIMESTAMP(msg_created), UNIX_TIMESTAMP(msg_sent), UNIX_TIMESTAMP(msg_read), UNIX_TIMESTAMP(msg_deleted) FROM msz_messages WHERE msg_id = %s AND msg_owner_id = ?',
!$useReplyTo || $messageInfoOrId instanceof MessageInfo ? '?' : '(SELECT msg_reply_to FROM msz_messages WHERE msg_id = ?)'
));
@ -177,7 +183,7 @@ class MessagesDatabase {
if(!$result->next())
throw new RuntimeException('Message not found.');
return MessageInfo::fromResult($result);
return new MessageInfo($result);
}
public function createMessage(
@ -192,7 +198,7 @@ class MessagesDatabase {
DateTime|int|null $sentAt = null,
DateTime|int|null $readAt = null
): MessageInfo {
$stmt = $this->cache->get('INSERT INTO msz_messages (msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, msg_title, msg_body, msg_parser, msg_sent, msg_read) VALUES (?, ?, ?, ?, ?, TO_BASE64(?), TO_BASE64(?), ?, FROM_UNIXTIME(?), FROM_UNIXTIME(?))');
$stmt = $this->cache->get('INSERT INTO msz_messages (msg_id, msg_owner_id, msg_author_id, msg_recipient_id, msg_reply_to, msg_title, msg_body, msg_parser, msg_sent, msg_read) VALUES (?, ?, ?, ?, ?, ?, ?, ?, FROM_UNIXTIME(?), FROM_UNIXTIME(?))');
$stmt->addParameter(1, $messageId);
$stmt->addParameter(2, $ownerInfo instanceof UserInfo ? $ownerInfo->getId() : $ownerInfo);
$stmt->addParameter(3, $authorInfo instanceof UserInfo ? $authorInfo->getId() : $authorInfo);
@ -233,12 +239,12 @@ class MessagesDatabase {
}
if($title !== null) {
$setQuery[] = 'msg_title = TO_BASE64(?)';
$setQuery[] = 'msg_title = ?';
$setValues[] = $title;
}
if($body !== null) {
$setQuery[] = 'msg_body = TO_BASE64(?)';
$setQuery[] = 'msg_body = ?';
$setValues[] = $body;
}

View file

@ -5,7 +5,7 @@ use stdClass;
use InvalidArgumentException;
use RuntimeException;
use Index\XString;
use Index\Http\Routing\{HttpGet,HttpMiddleware,HttpPost,RouteHandler};
use Index\Routing\{Route,RouteHandler};
use Syokuhou\IConfig;
use Misuzu\{CSRF,Pagination,Perm,Template};
use Misuzu\Auth\AuthInfo;
@ -33,16 +33,12 @@ class MessagesRoutes extends RouteHandler {
private bool $canSendMessages;
#[HttpMiddleware('/messages')]
#[Route('/messages')]
public function checkAccess($response, $request) {
// should probably be a permission or something too
if(!$this->authInfo->isLoggedIn())
return 401;
// do not allow access to PMs when impersonating in production mode
if(!MSZ_DEBUG && $this->authInfo->isImpersonating())
return 403;
$globalPerms = $this->authInfo->getPerms('global');
if(!$globalPerms->check(Perm::G_MESSAGES_VIEW))
return 403;
@ -76,7 +72,7 @@ class MessagesRoutes extends RouteHandler {
return $message;
}
#[HttpGet('/messages')]
#[Route('GET', '/messages')]
#[URLInfo('messages-index', '/messages', ['folder' => '<folder>', 'page' => '<page>'])]
public function getIndex($response, $request, string $folderName = '') {
$folderName = (string)$request->getParam('folder');
@ -129,7 +125,7 @@ class MessagesRoutes extends RouteHandler {
]);
}
#[HttpGet('/messages/stats')]
#[Route('GET', '/messages/stats')]
#[URLInfo('messages-stats', '/messages/stats')]
public function getStats() {
$selfInfo = $this->authInfo->getUserInfo();
@ -146,7 +142,7 @@ class MessagesRoutes extends RouteHandler {
];
}
#[HttpPost('/messages/recipient')]
#[Route('POST', '/messages/recipient')]
#[URLInfo('messages-recipient', '/messages/recipient')]
public function postRecipient($response, $request) {
if(!$request->isFormContent())
@ -186,7 +182,7 @@ class MessagesRoutes extends RouteHandler {
];
}
#[HttpGet('/messages/compose')]
#[Route('GET', '/messages/compose')]
#[URLInfo('messages-compose', '/messages/compose', ['recipient' => '<recipient>'])]
public function getEditor($response, $request) {
if(!$this->canSendMessages)
@ -197,7 +193,7 @@ class MessagesRoutes extends RouteHandler {
]);
}
#[HttpGet('/messages/([A-Za-z0-9]+)')]
#[Route('GET', '/messages/:message')]
#[URLInfo('messages-view', '/messages/<message>')]
public function getView($response, $request, string $messageId) {
if(strlen($messageId) !== 8)
@ -327,7 +323,7 @@ class MessagesRoutes extends RouteHandler {
return null;
}
#[HttpPost('/messages/create')]
#[Route('POST', '/messages/create')]
#[URLInfo('messages-create', '/messages/create')]
public function postCreate($response, $request) {
if(!$request->isFormContent())
@ -431,7 +427,7 @@ class MessagesRoutes extends RouteHandler {
];
}
#[HttpPost('/messages/([A-Za-z0-9]+)')]
#[Route('POST', '/messages/:message')]
#[URLInfo('messages-update', '/messages/<message>')]
public function postUpdate($response, $request, string $messageId) {
if(!$request->isFormContent())
@ -522,7 +518,7 @@ class MessagesRoutes extends RouteHandler {
];
}
#[HttpPost('/messages/mark')]
#[Route('POST', '/messages/mark')]
#[URLInfo('messages-mark', '/messages/mark')]
public function postMark($response, $request) {
if(!$request->isFormContent())
@ -553,16 +549,16 @@ class MessagesRoutes extends RouteHandler {
return [];
}
#[HttpPost('/messages/delete')]
#[Route('POST', '/messages/delete')]
#[URLInfo('messages-delete', '/messages/delete')]
public function postDelete($response, $request) {
if(!$request->isFormContent())
return 400;
$content = $request->getContent();
$messages = explode(',', (string)$content->getParam('messages'));
$messages = (string)$content->getParam('messages');
if($messages === '')
if(empty($messages))
return [
'error' => [
'name' => 'msgs:empty',
@ -570,8 +566,6 @@ class MessagesRoutes extends RouteHandler {
],
];
$messages = explode(',', $messages);
$this->msgsCtx->getDatabase()->deleteMessages(
$this->authInfo->getUserInfo(),
$messages
@ -580,16 +574,16 @@ class MessagesRoutes extends RouteHandler {
return [];
}
#[HttpPost('/messages/restore')]
#[Route('POST', '/messages/restore')]
#[URLInfo('messages-restore', '/messages/restore')]
public function postRestore($response, $request) {
if(!$request->isFormContent())
return 400;
$content = $request->getContent();
$messages = explode(',', (string)$content->getParam('messages'));
$messages = (string)$content->getParam('messages');
if($messages === '')
if(empty($messages))
return [
'error' => [
'name' => 'msgs:empty',
@ -597,8 +591,6 @@ class MessagesRoutes extends RouteHandler {
],
];
$messages = explode(',', $messages);
$this->msgsCtx->getDatabase()->restoreMessages(
$this->authInfo->getUserInfo(),
$messages
@ -607,16 +599,16 @@ class MessagesRoutes extends RouteHandler {
return [];
}
#[HttpPost('/messages/nuke')]
#[Route('POST', '/messages/nuke')]
#[URLInfo('messages-nuke', '/messages/nuke')]
public function postNuke($response, $request) {
if(!$request->isFormContent())
return 400;
$content = $request->getContent();
$messages = explode(',', (string)$content->getParam('messages'));
$messages = (string)$content->getParam('messages');
if($messages === '')
if(empty($messages))
return [
'error' => [
'name' => 'msgs:empty',
@ -624,8 +616,6 @@ class MessagesRoutes extends RouteHandler {
],
];
$messages = explode(',', $messages);
$this->msgsCtx->getDatabase()->nukeMessages(
$this->authInfo->getUserInfo(),
$messages

View file

@ -212,6 +212,7 @@ class MisuzuContext {
$routingCtx = new RoutingContext();
$this->urls = $routingCtx->getURLs();
$routingCtx->registerDefaultErrorPages();
$routingCtx->register(new \Misuzu\Home\HomeRoutes(
$this->config,
@ -262,7 +263,6 @@ class MisuzuContext {
$routingCtx->register(new \Misuzu\SharpChat\SharpChatRoutes(
$this->config->scopeTo('sockChat'),
$this->config->scopeTo('impersonate'),
$this->urls,
$this->usersCtx,
$this->authCtx,

View file

@ -41,7 +41,7 @@ class News {
public function getCategories(
?bool $hidden = null,
?Pagination $pagination = null
): iterable {
): array {
$hasHidden = $hidden !== null;
$hasPagination = $pagination !== null;
@ -61,7 +61,13 @@ class News {
$stmt->execute();
return $stmt->getResult()->getIterator(NewsCategoryInfo::fromResult(...));
$result = $stmt->getResult();
$categories = [];
while($result->next())
$categories[] = new NewsCategoryInfo($result);
return $categories;
}
public function getCategory(
@ -101,7 +107,7 @@ class News {
if(!$result->next())
throw new RuntimeException('News category not found.');
return NewsCategoryInfo::fromResult($result);
return new NewsCategoryInfo($result);
}
public function createCategory(
@ -218,7 +224,7 @@ class News {
bool $includeScheduled = false,
bool $includeDeleted = false,
?Pagination $pagination = null
): iterable {
): array {
if($categoryInfo instanceof NewsCategoryInfo)
$categoryInfo = $categoryInfo->getId();
@ -265,7 +271,13 @@ class News {
$stmt->execute();
return $stmt->getResult()->getIterator(NewsPostInfo::fromResult(...));
$result = $stmt->getResult();
$posts = [];
while($result->next())
$posts[] = new NewsPostInfo($result);
return $posts;
}
public function getPost(string $postId): NewsPostInfo {
@ -277,7 +289,7 @@ class News {
if(!$result->next())
throw new RuntimeException('No news post with that ID exists.');
return NewsPostInfo::fromResult($result);
return new NewsPostInfo($result);
}
public function createPost(

View file

@ -5,24 +5,20 @@ use Index\DateTime;
use Index\Data\IDbResult;
class NewsCategoryInfo {
public function __construct(
private string $id,
private string $name,
private string $description,
private bool $hidden,
private int $created,
private int $posts,
) {}
private string $id;
private string $name;
private string $description;
private bool $hidden;
private int $created;
private int $posts;
public static function fromResult(IDbResult $result): NewsCategoryInfo {
return new NewsCategoryInfo(
id: $result->getString(0),
name: $result->getString(1),
description: $result->getString(2),
hidden: $result->getBoolean(3),
created: $result->getInteger(4),
posts: $result->getInteger(5),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->name = $result->getString(1);
$this->description = $result->getString(2);
$this->hidden = $result->getInteger(3) !== 0;
$this->created = $result->getInteger(4);
$this->posts = $result->getInteger(5);
}
public function getId(): string {

View file

@ -5,34 +5,30 @@ use Index\DateTime;
use Index\Data\IDbResult;
class NewsPostInfo {
public function __construct(
private string $id,
private string $categoryId,
private ?string $userId,
private ?string $commentsSectionId,
private bool $featured,
private string $title,
private string $body,
private int $scheduled,
private int $created,
private int $updated,
private ?int $deleted,
) {}
private string $id;
private string $categoryId;
private ?string $userId;
private ?string $commentsSectionId;
private bool $featured;
private string $title;
private string $body;
private int $scheduled;
private int $created;
private int $updated;
private ?int $deleted;
public static function fromResult(IDbResult $result): NewsPostInfo {
return new NewsPostInfo(
id: $result->getString(0),
categoryId: $result->getString(1),
userId: $result->getStringOrNull(2),
commentsSectionId: $result->getStringOrNull(3),
featured: $result->getBoolean(4),
title: $result->getString(5),
body: $result->getString(6),
scheduled: $result->getInteger(7),
created: $result->getInteger(8),
updated: $result->getInteger(9),
deleted: $result->getIntegerOrNull(10),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->categoryId = (string)$result->getInteger(1);
$this->userId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->commentsSectionId = $result->isNull(3) ? null : (string)$result->getInteger(3);
$this->featured = $result->getInteger(4) !== 0;
$this->title = $result->getString(5);
$this->body = $result->getString(6);
$this->scheduled = $result->getInteger(7);
$this->created = $result->getInteger(8);
$this->updated = $result->getInteger(9);
$this->deleted = $result->isNull(10) ? null : $result->getInteger(10);
}
public function getId(): string {

View file

@ -3,14 +3,24 @@ namespace Misuzu\News;
use RuntimeException;
use Index\DateTime;
use Index\Data\{DbTools,IDbConnection};
use Index\Http\Routing\{HttpGet,RouteHandler};
use Misuzu\{Pagination,SiteInfo,Template};
use Index\Data\DbTools;
use Index\Data\IDbConnection;
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Misuzu\Pagination;
use Misuzu\SiteInfo;
use Misuzu\Template;
use Misuzu\Auth\AuthInfo;
use Misuzu\Comments\{Comments,CommentsCategory,CommentsEx};
use Misuzu\Feeds\{Feed,FeedItem,AtomFeedSerializer,RssFeedSerializer};
use Misuzu\Comments\Comments;
use Misuzu\Comments\CommentsCategory;
use Misuzu\Comments\CommentsEx;
use Misuzu\Feeds\Feed;
use Misuzu\Feeds\FeedItem;
use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\Parsers\Parser;
use Misuzu\URLs\{URLInfo,URLRegistry};
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\UsersContext;
class NewsRoutes extends RouteHandler {
@ -81,7 +91,7 @@ class NewsRoutes extends RouteHandler {
return $posts;
}
#[HttpGet('/news')]
#[Route('GET', '/news')]
#[URLInfo('news-index', '/news', ['p' => '<page>'])]
public function getIndex() {
$categories = $this->news->getCategories(hidden: false);
@ -99,21 +109,24 @@ class NewsRoutes extends RouteHandler {
]);
}
#[HttpGet('/news.rss')]
#[Route('GET', '/news.rss')]
#[URLInfo('news-feed-rss', '/news.rss')]
public function getFeedRss($response) {
return $this->getFeed($response, 'rss');
}
#[HttpGet('/news.atom')]
#[Route('GET', '/news.atom')]
#[URLInfo('news-feed-atom', '/news.atom')]
public function getFeedAtom($response) {
return $this->getFeed($response, 'atom');
}
#[HttpGet('/news/([0-9]+)(?:\.(rss|atom))?')]
#[Route('GET', '/news/:category')]
#[URLInfo('news-category', '/news/<category>', ['p' => '<page>'])]
public function getCategory($response, $request, string $categoryId, string $type = '') {
public function getCategory($response, $request, string $fileName) {
$categoryId = pathinfo($fileName, PATHINFO_FILENAME);
$type = pathinfo($fileName, PATHINFO_EXTENSION);
try {
$categoryInfo = $this->news->getCategory(categoryId: $categoryId);
} catch(RuntimeException $ex) {
@ -150,7 +163,7 @@ class NewsRoutes extends RouteHandler {
return $this->getFeed($response, 'atom', $categoryInfo);
}
#[HttpGet('/news/post/([0-9]+)')]
#[Route('GET', '/news/post/:id')]
#[URLInfo('news-post', '/news/post/<post>')]
#[URLInfo('news-post-comments', '/news/post/<post>', fragment: 'comments')]
public function getPost($response, $request, string $postId) {

View file

@ -6,30 +6,24 @@ use Index\Data\IDbResult;
class PermissionInfo implements IPermissionResult {
use PermissionResultShared;
private ?string $userId;
private ?string $roleId;
private ?string $forumCategoryId;
private string $category;
private int $allow;
private int $deny;
private int $calculated;
public function __construct(
private ?string $userId,
private ?string $roleId,
private ?string $forumCategoryId,
private string $category,
private int $allow,
private int $deny,
) {
public function __construct(IDbResult $result) {
$this->userId = $result->isNull(0) ? null : $result->getString(0);
$this->roleId = $result->isNull(1) ? null : $result->getString(1);
$this->forumCategoryId = $result->isNull(2) ? null : $result->getString(2);
$this->category = $result->getString(3);
$this->allow = $result->getInteger(4);
$this->deny = $result->getInteger(5);
$this->calculated = $this->allow & ~$this->deny;
}
public static function fromResult(IDbResult $result): PermissionInfo {
return new PermissionInfo(
userId: $result->getStringOrNull(0),
roleId: $result->getStringOrNull(1),
forumCategoryId: $result->getStringOrNull(2),
category: $result->getString(3),
allow: $result->getInteger(4),
deny: $result->getInteger(5),
);
}
public function hasUserId(): bool {
return $this->userId !== null;
}

View file

@ -76,11 +76,11 @@ class Permissions {
$result = $stmt->getResult();
if(is_string($categoryNames))
return $result->next() ? PermissionInfo::fromResult($result) : null;
return $result->next() ? new PermissionInfo($result) : null;
$perms = [];
while($result->next())
$perms[$result->getString(3)] = PermissionInfo::fromResult($result);
$perms[$result->getString(3)] = new PermissionInfo($result);
return $perms;
}

View file

@ -4,22 +4,18 @@ namespace Misuzu\Profile;
use Index\Data\IDbResult;
class ProfileFieldFormatInfo {
public function __construct(
private string $id,
private string $fieldId,
private ?string $regex,
private ?string $linkFormat,
private string $displayFormat,
) {}
private string $id;
private string $fieldId;
private ?string $regex;
private ?string $linkFormat;
private string $displayFormat;
public static function fromResult(IDbResult $result): ProfileFieldFormatInfo {
return new ProfileFieldFormatInfo(
id: $result->getString(0),
fieldId: $result->getString(1),
regex: $result->getStringOrNull(2),
linkFormat: $result->getStringOrNull(3),
displayFormat: $result->getString(4),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->fieldId = (string)$result->getInteger(1);
$this->regex = $result->isNull(2) ? null : $result->getString(2);
$this->linkFormat = $result->isNull(3) ? null : $result->getString(3);
$this->displayFormat = $result->getString(4);
}
public function getId(): string {

View file

@ -4,22 +4,18 @@ namespace Misuzu\Profile;
use Index\Data\IDbResult;
class ProfileFieldInfo {
public function __construct(
private string $id,
private int $order,
private string $name,
private string $title,
private string $regex,
) {}
private string $id;
private int $order;
private string $name;
private string $title;
private string $regex;
public static function fromResult(IDbResult $result): ProfileFieldInfo {
return new ProfileFieldInfo(
id: $result->getString(0),
order: $result->getInteger(1),
name: $result->getString(2),
title: $result->getString(3),
regex: $result->getString(4),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->order = $result->getInteger(1);
$this->name = $result->getString(2);
$this->title = $result->getString(3);
$this->regex = $result->getString(4);
}
public function getId(): string {

View file

@ -4,20 +4,16 @@ namespace Misuzu\Profile;
use Index\Data\IDbResult;
class ProfileFieldValueInfo {
public function __construct(
private string $fieldId,
private string $userId,
private string $formatId,
private string $value,
) {}
private string $fieldId;
private string $userId;
private string $formatId;
private string $value;
public static function fromResult(IDbResult $result): ProfileFieldValueInfo {
return new ProfileFieldValueInfo(
fieldId: $result->getString(0),
userId: $result->getString(1),
formatId: $result->getString(2),
value: $result->getString(3)
);
public function __construct(IDbResult $result) {
$this->fieldId = (string)$result->getInteger(0);
$this->userId = (string)$result->getInteger(1);
$this->formatId = (string)$result->getInteger(2);
$this->value = $result->getString(3);
}
public function getFieldId(): string {

View file

@ -16,15 +16,10 @@ class ProfileFields {
$this->cache = new DbStatementCache($dbConn);
}
public function getFields(?iterable $fieldValueInfos = null): iterable {
public function getFields(?array $fieldValueInfos = null): array {
$hasFieldValueInfos = $fieldValueInfos !== null;
if($hasFieldValueInfos) {
if(!is_array($fieldValueInfos))
$fieldValueInfos = iterator_to_array($fieldValueInfos);
if(empty($fieldValueInfos))
return [];
}
if($hasFieldValueInfos && empty($fieldValueInfos))
return [];
$query = 'SELECT field_id, field_order, field_key, field_title, field_regex FROM msz_profile_fields';
if($hasFieldValueInfos)
@ -42,8 +37,13 @@ class ProfileFields {
}
$stmt->execute();
$result = $stmt->getResult();
$fields = [];
return $stmt->getResult()->getIterator(ProfileFieldInfo::fromResult(...));
while($result->next())
$fields[] = new ProfileFieldInfo($result);
return $fields;
}
public function getField(string $fieldId): ProfileFieldInfo {
@ -55,30 +55,20 @@ class ProfileFields {
if(!$result->next())
throw new RuntimeException('No field found with the provided field id.');
return ProfileFieldInfo::fromResult($result);
return new ProfileFieldInfo($result);
}
public function getFieldFormats(
?iterable $fieldInfos = null,
?iterable $fieldValueInfos = null
): iterable {
?array $fieldInfos = null,
?array $fieldValueInfos = null
): array {
$hasFieldInfos = $fieldInfos !== null;
$hasFieldValueInfos = $fieldValueInfos !== null;
if($hasFieldInfos) {
if(!is_array($fieldInfos))
$fieldInfos = iterator_to_array($fieldInfos);
if(empty($fieldInfos))
return [];
}
if($hasFieldValueInfos) {
if(!is_array($fieldValueInfos))
$fieldValueInfos = iterator_to_array($fieldValueInfos);
if(empty($fieldValueInfos))
return [];
}
if($hasFieldInfos && empty($fieldInfos))
return [];
if($hasFieldValueInfos && empty($fieldValueInfos))
return [];
$args = 0;
$query = 'SELECT format_id, field_id, format_regex, format_link, format_display FROM msz_profile_fields_formats';
@ -111,8 +101,13 @@ class ProfileFields {
}
$stmt->execute();
$result = $stmt->getResult();
$formats = [];
return $stmt->getResult()->getIterator(ProfileFieldFormatInfo::fromResult(...));
while($result->next())
$formats[] = new ProfileFieldFormatInfo($result);
return $formats;
}
public function getFieldFormat(string $formatId): ProfileFieldFormatInfo {
@ -124,7 +119,7 @@ class ProfileFields {
if(!$result->next())
throw new RuntimeException('No format found with the provided format id.');
return ProfileFieldFormatInfo::fromResult($result);
return new ProfileFieldFormatInfo($result);
}
public function selectFieldFormat(
@ -143,10 +138,10 @@ class ProfileFields {
if(!$result->next())
throw new RuntimeException('Could not determine an appropriate format for this field (missing default formatting)');
return ProfileFieldFormatInfo::fromResult($result);
return new ProfileFieldFormatInfo($result);
}
public function getFieldValues(UserInfo|string $userInfo): iterable {
public function getFieldValues(UserInfo|string $userInfo): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -156,7 +151,13 @@ class ProfileFields {
$stmt->addParameter(1, $userInfo);
$stmt->execute();
return $stmt->getResult()->getIterator(ProfileFieldValueInfo::fromResult(...));
$result = $stmt->getResult();
$values = [];
while($result->next())
$values[] = new ProfileFieldValueInfo($result);
return $values;
}
public function getFieldValue(
@ -178,7 +179,7 @@ class ProfileFields {
if(!$result->next())
throw new RuntimeException('No value for this field and user combination found.');
return ProfileFieldValueInfo::fromResult($result);
return new ProfileFieldValueInfo($result);
}
public function setFieldValues(

View file

@ -1,16 +1,21 @@
<?php
namespace Misuzu;
use Index\Http\Routing\{HttpRouter,IRouter,IRouteHandler};
use Misuzu\URLs\{IURLSource,URLInfo,URLRegistry};
use Index\Http\HttpFx;
use Index\Http\HttpRequest;
use Index\Routing\IRouter;
use Index\Routing\IRouteHandler;
use Misuzu\URLs\IURLSource;
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;
class RoutingContext {
private URLRegistry $urls;
private HttpRouter $router;
private HttpFx $router;
public function __construct() {
$this->urls = new URLRegistry;
$this->router = new HttpRouter(errorHandler: new RoutingErrorHandler);
$this->router = new HttpFx;
$this->router->use('/', fn($resp) => $resp->setPoweredBy('Misuzu'));
}
@ -22,6 +27,25 @@ class RoutingContext {
return $this->router;
}
public function registerDefaultErrorPages(): void {
$this->router->addErrorHandler(400, fn($resp) => $resp->setContent(Template::renderRaw('errors.400')));
$this->router->addErrorHandler(403, fn($resp) => $resp->setContent(Template::renderRaw('errors.403')));
$this->router->addErrorHandler(404, fn($resp) => $resp->setContent(Template::renderRaw('errors.404')));
$this->router->addErrorHandler(500, fn($resp) => $resp->setContent(file_get_contents(MSZ_TEMPLATES . '/500.html')));
$this->router->addErrorHandler(503, fn($resp) => $resp->setContent(file_get_contents(MSZ_TEMPLATES . '/503.html')));
}
public static function registerSimpleErrorPages(IRouter $router, string $path): void {
if($router instanceof HttpFx)
$router->use($path, function() use($router) {
$router->addErrorHandler(400, fn($resp) => $resp->setContent('HTTP 400'));
$router->addErrorHandler(403, fn($resp) => $resp->setContent('HTTP 403'));
$router->addErrorHandler(404, fn($resp) => $resp->setContent('HTTP 404'));
$router->addErrorHandler(500, fn($resp) => $resp->setContent('HTTP 500'));
$router->addErrorHandler(503, fn($resp) => $resp->setContent('HTTP 503'));
});
}
public function register(IRouteHandler|IURLSource $handler): void {
if($handler instanceof IRouteHandler)
$this->router->register($handler);
@ -30,7 +54,7 @@ class RoutingContext {
URLInfo::handleAttributes($this->urls, $handler);
}
public function dispatch(...$args): void {
$this->router->dispatch(...$args);
public function dispatch(?HttpRequest $request = null): void {
$this->router->dispatch($request);
}
}

View file

@ -1,29 +0,0 @@
<?php
namespace Misuzu;
use Index\Http\{HttpResponseBuilder,HttpRequest};
use Index\Http\ErrorHandling\HtmlErrorHandler;
class RoutingErrorHandler extends HtmlErrorHandler {
public function handle(HttpResponseBuilder $response, HttpRequest $request, int $code, string $message): void {
if(str_starts_with($request->getPath(), '/_')) {
$response->setTypePlain();
$response->setContent(sprintf('HTTP %03d', $code));
return;
}
if($code === 500 || $code === 503) {
$response->setTypeHTML();
$response->setContent(file_get_contents(sprintf('%s/%03d.html', MSZ_TEMPLATES, $code)));
return;
}
if($code === 401 || $code === 403 || $code === 404) {
$response->setTypeHTML();
$response->setContent(Template::renderRaw(sprintf('errors.%03d', $code)));
return;
}
parent::handle($response, $request, $code, $message);
}
}

View file

@ -3,7 +3,9 @@ namespace Misuzu\Satori;
use RuntimeException;
use Index\Colour\Colour;
use Index\Http\Routing\{HttpGet,HttpMiddleware,RouteHandler};
use Index\Routing\IRouter;
use Index\Routing\IRouteHandler;
use Index\Routing\Route;
use Syokuhou\IConfig;
use Misuzu\Pagination;
use Misuzu\RoutingContext;
@ -11,7 +13,7 @@ use Misuzu\Forum\ForumContext;
use Misuzu\Profile\ProfileFields;
use Misuzu\Users\UsersContext;
final class SatoriRoutes extends RouteHandler {
final class SatoriRoutes implements IRouteHandler {
public function __construct(
private IConfig $config,
private UsersContext $usersCtx,
@ -19,7 +21,12 @@ final class SatoriRoutes extends RouteHandler {
private ProfileFields $profileFields
) {}
#[HttpMiddleware('/_satori')]
public function registerRoutes(IRouter $router): void {
RoutingContext::registerSimpleErrorPages($router, '/_satori');
Route::handleAttributes($router, $this);
}
#[Route('/_satori')]
public function verifyRequest($response, $request) {
$secretKey = $this->config->getString('secret');
@ -39,7 +46,7 @@ final class SatoriRoutes extends RouteHandler {
}
}
#[HttpGet('/_satori/get-profile-field')]
#[Route('GET', '/_satori/get-profile-field')]
public function getProfileField($response, $request): array {
$userId = (string)$request->getParam('user', FILTER_SANITIZE_NUMBER_INT);
$fieldId = (string)$request->getParam('field', FILTER_SANITIZE_NUMBER_INT);
@ -55,7 +62,7 @@ final class SatoriRoutes extends RouteHandler {
];
}
#[HttpGet('/_satori/get-recent-forum-posts')]
#[Route('GET', '/_satori/get-recent-forum-posts')]
public function getRecentForumPosts($response, $request): array {
$categoryIds = $this->config->getArray('forum.categories');
if(empty($categoryIds))
@ -97,7 +104,7 @@ final class SatoriRoutes extends RouteHandler {
return $posts;
}
#[HttpGet('/_satori/get-recent-registrations')]
#[Route('GET', '/_satori/get-recent-registrations')]
public function getRecentRegistrations($response, $request) {
$batchSize = $this->config->getInteger('users.batch', 10);
$backlogDays = $this->config->getInteger('users.backlog', 7);

View file

@ -3,21 +3,25 @@ namespace Misuzu\SharpChat;
use RuntimeException;
use Index\Colour\Colour;
use Index\Http\Routing\{HandlerAttribute,HttpDelete,HttpGet,HttpOptions,HttpPost,RouteHandler};
use Index\Routing\IRouter;
use Index\Routing\IRouteHandler;
use Index\Routing\Route;
use Syokuhou\IConfig;
use Misuzu\RoutingContext;
use Misuzu\Auth\{AuthContext,AuthInfo,Sessions};
use Misuzu\Auth\AuthContext;
use Misuzu\Auth\AuthInfo;
use Misuzu\Auth\Sessions;
use Misuzu\Emoticons\Emotes;
use Misuzu\Perms\Permissions;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\{Bans,UsersContext,UserInfo};
use Misuzu\Users\Bans;
use Misuzu\Users\UsersContext;
final class SharpChatRoutes extends RouteHandler {
final class SharpChatRoutes implements IRouteHandler {
private string $hashKey;
public function __construct(
private IConfig $config,
private IConfig $impersonateConfig, // this sucks lol
private URLRegistry $urls,
private UsersContext $usersCtx,
private AuthContext $authCtx,
@ -28,8 +32,13 @@ final class SharpChatRoutes extends RouteHandler {
$this->hashKey = $this->config->getString('hashKey', 'woomy');
}
#[HttpOptions('/_sockchat/emotes')]
#[HttpGet('/_sockchat/emotes')]
public function registerRoutes(IRouter $router): void {
RoutingContext::registerSimpleErrorPages($router, '/_sockchat');
Route::handleAttributes($router, $this);
}
#[Route('OPTIONS', '/_sockchat/emotes')]
#[Route('GET', '/_sockchat/emotes')]
public function getEmotes($response, $request): array|int {
$response->setHeader('Access-Control-Allow-Origin', '*');
$response->setHeader('Access-Control-Allow-Methods', 'GET');
@ -57,7 +66,7 @@ final class SharpChatRoutes extends RouteHandler {
return $out;
}
#[HttpGet('/_sockchat/login')]
#[Route('GET', '/_sockchat/login')]
public function getLogin($response, $request) {
if(!$this->authInfo->isLoggedIn()) {
$response->redirect($this->urls->format('auth-login'));
@ -70,16 +79,8 @@ final class SharpChatRoutes extends RouteHandler {
));
}
private function canImpersonateUserId(UserInfo $impersonator, string $targetId): bool {
if($impersonator->isSuperUser())
return true;
$whitelist = $this->impersonateConfig->getArray(sprintf('allow.u%s', $impersonator->getId()));
return in_array($targetId, $whitelist, true);
}
#[HttpOptions('/_sockchat/token')]
#[HttpGet('/_sockchat/token')]
#[Route('OPTIONS', '/_sockchat/token')]
#[Route('GET', '/_sockchat/token')]
public function getToken($response, $request) {
$host = $request->hasHeader('Host') ? $request->getHeaderFirstLine('Host') : '';
$origin = $request->hasHeader('Origin') ? $request->getHeaderFirstLine('Origin') : '';
@ -120,7 +121,7 @@ final class SharpChatRoutes extends RouteHandler {
return ['ok' => false, 'err' => 'user'];
$userInfo = $this->usersCtx->getUsers()->getUser($sessionInfo->getUserId(), 'id');
$userId = $tokenInfo->hasImpersonatedUserId() && $this->canImpersonateUserId($userInfo, $tokenInfo->getImpersonatedUserId())
$userId = $tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser()
? $tokenInfo->getImpersonatedUserId()
: $userInfo->getId();
@ -133,7 +134,7 @@ final class SharpChatRoutes extends RouteHandler {
];
}
#[HttpPost('/_sockchat/bump')]
#[Route('POST', '/_sockchat/bump')]
public function postBump($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature'))
return 400;
@ -163,7 +164,7 @@ final class SharpChatRoutes extends RouteHandler {
$this->usersCtx->getUsers()->recordUserActivity($userId, remoteAddr: $ipAddr);
}
#[HttpPost('/_sockchat/verify')]
#[Route('POST', '/_sockchat/verify')]
public function postVerify($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature'))
return 400;
@ -214,7 +215,7 @@ final class SharpChatRoutes extends RouteHandler {
$this->authCtx->getSessions()->recordSessionActivity(sessionInfo: $sessionInfo, remoteAddr: $ipAddress);
$userInfo = $this->usersCtx->getUsers()->getUser($sessionInfo->getUserId(), 'id');
if($tokenInfo->hasImpersonatedUserId() && $this->canImpersonateUserId($userInfo, $tokenInfo->getImpersonatedUserId())) {
if($tokenInfo->hasImpersonatedUserId() && $userInfo->isSuperUser()) {
$userInfoReal = $userInfo;
try {
@ -244,7 +245,7 @@ final class SharpChatRoutes extends RouteHandler {
];
}
#[HttpGet('/_sockchat/bans/list')]
#[Route('GET', '/_sockchat/bans/list')]
public function getBanList($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature'))
return 400;
@ -279,7 +280,7 @@ final class SharpChatRoutes extends RouteHandler {
return $list;
}
#[HttpGet('/_sockchat/bans/check')]
#[Route('GET', '/_sockchat/bans/check')]
public function getBanCheck($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature'))
return 400;
@ -317,7 +318,7 @@ final class SharpChatRoutes extends RouteHandler {
];
}
#[HttpPost('/_sockchat/bans/create')]
#[Route('POST', '/_sockchat/bans/create')]
public function postBanCreate($response, $request): int {
if(!$request->hasHeader('X-SharpChat-Signature') || !$request->isFormContent())
return 400;
@ -391,7 +392,7 @@ final class SharpChatRoutes extends RouteHandler {
return 201;
}
#[HttpDelete('/_sockchat/bans/revoke')]
#[Route('DELETE', '/_sockchat/bans/revoke')]
public function deleteBanRevoke($response, $request): int {
if(!$request->hasHeader('X-SharpChat-Signature'))
return 400;

View file

@ -1,6 +1,9 @@
<?php
namespace Misuzu;
use Index\Routing\IRouter;
use Index\Http\HttpFx;
final class Tools {
public static function isLocalURL(
string $url,

View file

@ -3,11 +3,14 @@ namespace Misuzu\Users\Assets;
use InvalidArgumentException;
use RuntimeException;
use Index\Http\Routing\{HttpGet,RouteHandler};
use Index\Routing\Route;
use Index\Routing\RouteHandler;
use Misuzu\Perm;
use Misuzu\Auth\AuthInfo;
use Misuzu\URLs\{URLInfo,URLRegistry};
use Misuzu\Users\{UsersContext,UserInfo};
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\UsersContext;
use Misuzu\Users\UserInfo;
class AssetsRoutes extends RouteHandler {
public function __construct(
@ -26,10 +29,11 @@ class AssetsRoutes extends RouteHandler {
return true;
}
#[HttpGet('/assets/avatar')]
#[HttpGet('/assets/avatar/([0-9]+)(?:\.[a-z]+)?')]
#[Route('GET', '/assets/avatar')]
#[Route('GET', '/assets/avatar/:filename')]
#[URLInfo('user-avatar', '/assets/avatar/<user>', ['res' => '<res>'])]
public function getAvatar($response, $request, string $userId = '') {
public function getAvatar($response, $request, string $fileName = '') {
$userId = pathinfo($fileName, PATHINFO_FILENAME);
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC);
try {
@ -48,10 +52,12 @@ class AssetsRoutes extends RouteHandler {
$this->serveAsset($response, $request, $assetInfo);
}
#[HttpGet('/assets/profile-background')]
#[HttpGet('/assets/profile-background/([0-9]+)(?:\.[a-z]+)?')]
#[Route('GET', '/assets/profile-background')]
#[Route('GET', '/assets/profile-background/:filename')]
#[URLInfo('user-background', '/assets/profile-background/<user>')]
public function getProfileBackground($response, $request, string $userId = '') {
public function getProfileBackground($response, $request, string $fileName = '') {
$userId = pathinfo($fileName, PATHINFO_FILENAME);
try {
$userInfo = $this->usersCtx->getUserInfo($userId);
} catch(RuntimeException $ex) {
@ -72,7 +78,7 @@ class AssetsRoutes extends RouteHandler {
$this->serveAsset($response, $request, $assetInfo);
}
#[HttpGet('/user-assets.php')]
#[Route('GET', '/user-assets.php')]
public function getUserAssets($response, $request) {
$userId = (string)$request->getParam('u', FILTER_SANITIZE_NUMBER_INT);
$mode = (string)$request->getParam('m');

View file

@ -5,28 +5,24 @@ use Index\DateTime;
use Index\Data\IDbResult;
class BanInfo {
public function __construct(
private string $id,
private string $userId,
private ?string $modId,
private int $severity,
private string $publicReason,
private string $privateReason,
private int $created,
private ?int $expires,
) {}
private string $id;
private string $userId;
private ?string $modId;
private int $severity;
private string $publicReason;
private string $privateReason;
private int $created;
private ?int $expires;
public static function fromResult(IDbResult $result): BanInfo {
return new BanInfo(
id: $result->getString(0),
userId: $result->getString(1),
modId: $result->getStringOrNull(2),
severity: $result->getInteger(3),
publicReason: $result->getString(4),
privateReason: $result->getString(5),
created: $result->getInteger(6),
expires: $result->getIntegerOrNull(7),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->userId = (string)$result->getInteger(1);
$this->modId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->severity = $result->getInteger(3);
$this->publicReason = $result->getString(4);
$this->privateReason = $result->getString(5);
$this->created = $result->getInteger(6);
$this->expires = $result->isNull(7) ? null : $result->getInteger(7);
}
public function getId(): string {

View file

@ -64,7 +64,7 @@ class Bans {
?bool $activeOnly = null,
?bool $activeFirst = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -101,7 +101,13 @@ class Bans {
}
$stmt->execute();
return $stmt->getResult()->getIterator(BanInfo::fromResult(...));
$result = $stmt->getResult();
$bans = [];
while($result->next())
$bans[] = new BanInfo($result);
return $bans;
}
public function getBan(string $banId): BanInfo {
@ -113,7 +119,7 @@ class Bans {
if(!$result->next())
throw new RuntimeException('No ban with ID $banId found.');
return BanInfo::fromResult($result);
return new BanInfo($result);
}
public function countActiveBans(
@ -147,7 +153,7 @@ class Bans {
$stmt->execute();
$result = $stmt->getResult();
return $result->next() ? BanInfo::fromResult($result) : null;
return $result->next() ? new BanInfo($result) : null;
}
public function createBan(

View file

@ -5,24 +5,20 @@ use Index\DateTime;
use Index\Data\IDbResult;
class ModNoteInfo {
public function __construct(
private string $noteId,
private string $userId,
private ?string $authorId,
private int $created,
private string $title,
private string $body,
) {}
private string $noteId;
private string $userId;
private ?string $authorId;
private int $created;
private string $title;
private string $body;
public static function fromResult(IDbResult $result): ModNoteInfo {
return new ModNoteInfo(
noteId: $result->getString(0),
userId: $result->getString(1),
authorId: $result->getStringOrNull(2),
created: $result->getInteger(3),
title: $result->getString(4),
body: $result->getString(5)
);
public function __construct(IDbResult $result) {
$this->noteId = (string)$result->getInteger(0);
$this->userId = (string)$result->getInteger(1);
$this->authorId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->created = $result->getInteger(3);
$this->title = $result->getString(4);
$this->body = $result->getString(5);
}
public function getId(): string {

View file

@ -59,7 +59,7 @@ class ModNotes {
UserInfo|string|null $userInfo = null,
UserInfo|string|null $authorInfo = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($authorInfo instanceof UserInfo)
@ -93,7 +93,13 @@ class ModNotes {
}
$stmt->execute();
return $stmt->getResult()->getIterator(ModNoteInfo::fromResult(...));
$result = $stmt->getResult();
$notes = [];
while($result->next())
$notes[] = new ModNoteInfo($result);
return $notes;
}
public function getNote(string $noteId): ModNoteInfo {
@ -105,7 +111,7 @@ class ModNotes {
if(!$result->next())
throw new RuntimeException('No note with ID $noteId found.');
return ModNoteInfo::fromResult($result);
return new ModNoteInfo($result);
}
public function createNote(

View file

@ -7,30 +7,26 @@ use Index\Colour\Colour;
use Index\Data\IDbResult;
class RoleInfo implements Stringable {
public function __construct(
private string $id,
private int $rank,
private string $name,
private ?string $title,
private ?string $description,
private bool $hidden,
private bool $leavable,
private ?int $colour,
private int $created,
) {}
private string $id;
private int $rank;
private string $name;
private ?string $title;
private ?string $description;
private bool $hidden;
private bool $leavable;
private ?int $colour;
private int $created;
public static function fromResult(IDbResult $result): RoleInfo {
return new RoleInfo(
id: $result->getString(0),
rank: $result->getInteger(1),
name: $result->getString(2),
title: $result->getStringOrNull(3),
description: $result->getStringOrNull(4),
hidden: $result->getBoolean(5),
leavable: $result->getBoolean(6),
colour: $result->getIntegerOrNull(7),
created: $result->getInteger(8),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->rank = $result->getInteger(1);
$this->name = $result->getString(2);
$this->title = $result->isNull(3) ? null : $result->getString(3);
$this->description = $result->isNull(4) ? null : $result->getString(4);
$this->hidden = $result->getInteger(5) !== 0;
$this->leavable = $result->getInteger(6) !== 0;
$this->colour = $result->isNull(7) ? null : $result->getInteger(7);
$this->created = $result->getInteger(8);
}
public function getId(): string {

View file

@ -58,7 +58,7 @@ class Roles {
UserInfo|string|null $userInfo = null,
?bool $hidden = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -87,7 +87,13 @@ class Roles {
}
$stmt->execute();
return $stmt->getResult()->getIterator(RoleInfo::fromResult(...));
$roles = [];
$result = $stmt->getResult();
while($result->next())
$roles[] = new RoleInfo($result);
return $roles;
}
public function getRole(string $roleId): RoleInfo {
@ -99,7 +105,7 @@ class Roles {
if(!$result->next())
throw new RuntimeException('Could not find role with ID $roleId.');
return RoleInfo::fromResult($result);
return new RoleInfo($result);
}
public function createRole(

View file

@ -9,54 +9,50 @@ use Index\Net\IPAddress;
use Misuzu\Parsers\Parser;
class UserInfo {
public function __construct(
private string $id,
private string $name,
private ?string $passwordHash,
private string $emailAddr,
private string $registerRemoteAddr,
private string $lastRemoteAddr,
private bool $super,
private string $countryCode,
private ?int $colour,
private int $created,
private ?int $lastActive,
private ?int $deleted,
private ?string $displayRoleId,
private ?string $totpKey,
private ?string $aboutContent,
private int $aboutParser,
private ?string $signatureContent,
private int $signatureParser,
private ?string $birthdate,
private ?int $backgroundSettings,
private ?string $title,
) {}
private string $id;
private string $name;
private ?string $passwordHash;
private string $emailAddr;
private string $registerRemoteAddr;
private string $lastRemoteAddr;
private bool $super;
private string $countryCode;
private ?int $colour;
private int $created;
private ?int $lastActive;
private ?int $deleted;
private ?string $displayRoleId;
private ?string $totpKey;
private ?string $aboutContent;
private int $aboutParser;
private ?string $signatureContent;
private int $signatureParser;
private ?string $birthdate;
private ?int $backgroundSettings;
private ?string $title;
public static function fromResult(IDbResult $result): self {
return new UserInfo(
id: $result->getString(0),
name: $result->getString(1),
passwordHash: $result->getStringOrNull(2),
emailAddr: $result->getString(3),
registerRemoteAddr: $result->getString(4),
lastRemoteAddr: $result->getStringOrNull(5),
super: $result->getBoolean(6),
countryCode: $result->getString(7),
colour: $result->getIntegerOrNull(8),
created: $result->getInteger(9),
lastActive: $result->getIntegerOrNull(10),
deleted: $result->getIntegerOrNull(11),
displayRoleId: $result->getStringOrNull(12),
totpKey: $result->getStringOrNull(13),
aboutContent: $result->getStringOrNull(14),
aboutParser: $result->getInteger(15),
signatureContent: $result->getStringOrNull(16),
signatureParser: $result->getInteger(17),
birthdate: $result->getStringOrNull(18),
backgroundSettings: $result->getIntegerOrNull(19),
title: $result->getString(20),
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->name = $result->getString(1);
$this->passwordHash = $result->isNull(2) ? null : $result->getString(2);
$this->emailAddr = $result->getString(3);
$this->registerRemoteAddr = $result->getString(4);
$this->lastRemoteAddr = $result->isNull(5) ? null : $result->getString(5);
$this->super = $result->getInteger(6) !== 0;
$this->countryCode = $result->getString(7);
$this->colour = $result->isNull(8) ? null : $result->getInteger(8);
$this->created = $result->getInteger(9);
$this->lastActive = $result->isNull(10) ? null : $result->getInteger(10);
$this->deleted = $result->isNull(11) ? null : $result->getInteger(11);
$this->displayRoleId = $result->isNull(12) ? null : (string)$result->getInteger(12);
$this->totpKey = $result->isNull(13) ? null : $result->getString(13);
$this->aboutContent = $result->isNull(14) ? null : $result->getString(14);
$this->aboutParser = $result->getInteger(15);
$this->signatureContent = $result->isNull(16) ? null : $result->getString(16);
$this->signatureParser = $result->getInteger(17);
$this->birthdate = $result->isNull(18) ? null : $result->getString(18);
$this->backgroundSettings = $result->isNull(19) ? null : $result->getInteger(19);
$this->title = $result->getString(20);
}
public function getId(): string {

View file

@ -112,7 +112,7 @@ class Users {
?bool $reverseOrder = null,
?array $searchQuery = null,
?Pagination $pagination = null
): iterable {
): array {
// remove this hack when search server
$hasSearchQuery = $searchQuery !== null;
$searchLimitResults = false;
@ -211,7 +211,13 @@ class Users {
}
$stmt->execute();
return $stmt->getResult()->getIterator(UserInfo::fromResult(...));
$users = [];
$result = $stmt->getResult();
while($result->next())
$users[] = new UserInfo($result);
return $users;
}
public const GET_USER_ID = 0x01;
@ -277,7 +283,7 @@ class Users {
if(!$result->next())
throw new RuntimeException('User not found.');
return UserInfo::fromResult($result);
return new UserInfo($result);
}
public function createUser(

View file

@ -5,22 +5,18 @@ use Index\DateTime;
use Index\Data\IDbResult;
class WarningInfo {
public function __construct(
private string $id,
private string $userId,
private ?string $modId,
private string $body,
private int $created,
) {}
private string $id;
private string $userId;
private ?string $modId;
private string $body;
private int $created;
public static function fromResult(IDbResult $result): WarningInfo {
return new WarningInfo(
id: $result->getString(0),
userId: $result->getString(1),
modId: $result->getStringOrNull(2),
body: $result->getString(3),
created: $result->getInteger(4)
);
public function __construct(IDbResult $result) {
$this->id = (string)$result->getInteger(0);
$this->userId = (string)$result->getInteger(1);
$this->modId = $result->isNull(2) ? null : (string)$result->getInteger(2);
$this->body = $result->getString(3);
$this->created = $result->getInteger(4);
}
public function getId(): string {

View file

@ -53,14 +53,18 @@ class Warnings {
$stmt->execute();
$result = $stmt->getResult();
$count = 0;
return $result->next() ? $result->getInteger(0) : 0;
if($result->next())
$count = $result->getInteger(0);
return $count;
}
public function getWarningsWithDefaultBacklog(
UserInfo|string|null $userInfo = null,
?Pagination $pagination = null
): iterable {
): array {
return $this->getWarnings(
$userInfo,
self::VISIBLE_BACKLOG,
@ -72,7 +76,7 @@ class Warnings {
UserInfo|string|null $userInfo = null,
?int $backlog = null,
?Pagination $pagination = null
): iterable {
): array {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
@ -107,7 +111,13 @@ class Warnings {
}
$stmt->execute();
return $stmt->getResult()->getIterator(WarningInfo::fromResult(...));
$result = $stmt->getResult();
$warns = [];
while($result->next())
$warns[] = new WarningInfo($result);
return $warns;
}
public function getWarning(string $warnId): WarningInfo {
@ -120,7 +130,7 @@ class Warnings {
if(!$result->next())
throw new RuntimeException('Could not find warning info for ID $warnId.');
return WarningInfo::fromResult($result);
return new WarningInfo($result);
}
public function createWarning(

View file

@ -79,7 +79,7 @@
{% set show_profile_fields = not profile_is_guest and (profile_is_editing ? perms.edit_profile : profile_fields_display_values|default([]) is not empty) %}
{% set show_background_settings = profile_is_editing and perms.edit_background %}
{% set show_birthdate = profile_is_editing and perms.edit_birthdate %}
{% set show_active_forum_info = not profile_is_guest and not profile_is_deleted and not profile_is_editing and profile_active_topic_info.id|default(0) > 0 %}
{% set show_active_forum_info = not profile_is_guest and not profile_is_deleted and not profile_is_editing or (profile_active_category_info is defined and profile_active_category_info is not empty or profile_active_topic_info.topic_id|default(0) > 0) %}
{% set show_warnings = profile_warnings is defined and profile_warnings|length > 0 %}
{% set show_sidebar = (not profile_is_banned or profile_can_edit) and (profile_is_guest or show_profile_fields or show_background_settings or show_birthdate or show_active_forum_info or show_warnings) %}

View file

@ -132,15 +132,6 @@ msz_sched_task_func('Resync statistics counters.', true, function() use ($msz) {
'users:warnings:visible' => 'SELECT COUNT(*) FROM msz_users_warnings WHERE warn_created > NOW() - INTERVAL 90 DAY',
'users:bans:total' => 'SELECT COUNT(*) FROM msz_users_bans',
'users:bans:active' => 'SELECT COUNT(*) FROM msz_users_bans WHERE ban_expires IS NULL OR ban_expires > NOW()',
'pms:msgs:total' => 'SELECT COUNT(*) FROM msz_messages',
'pms:msgs:messages' => 'SELECT COUNT(DISTINCT msg_id) FROM msz_messages',
'pms:msgs:replies' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_reply_to IS NULL',
'pms:msgs:drafts' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_sent IS NULL',
'pms:msgs:unread' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_read IS NULL',
'pms:msgs:deleted' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_deleted IS NOT NULL',
'pms:msgs:plain' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_parser = 0',
'pms:msgs:bbcode' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_parser = 1',
'pms:msgs:markdown' => 'SELECT COUNT(*) FROM msz_messages WHERE msg_parser = 2',
];
foreach($stats as $name => $query) {
@ -158,88 +149,6 @@ msz_sched_task_func('Recalculate permissions (maybe)...', false, function() use
$msz->getPerms()->precalculatePermissions($msz->getForumContext()->getCategories());
});
msz_sched_task_func('Omega disliking comments...', true, function() use ($msz) {
$commentIds = $msz->getConfig()->getArray('comments.omegadislike');
if(!is_array($commentIds))
return;
$dbConn = $msz->getDbConn();
$stmt = $dbConn->prepare('REPLACE INTO msz_comments_votes (comment_id, user_id, comment_vote) SELECT ?, user_id, -1 FROM msz_users');
foreach($commentIds as $commentId) {
$stmt->addParameter(1, $commentId);
$stmt->execute();
}
});
msz_sched_task_func('Announcing random topics...', true, function() use ($msz) {
$categoryIds = $msz->getConfig()->getArray('forum.rngannounce');
if(!is_array($categoryIds))
return;
$dbConn = $msz->getDbConn();
$stmtRevert = $dbConn->prepare('UPDATE msz_forum_topics SET topic_type = 0 WHERE forum_id = ? AND topic_type = 2');
$stmtRandom = $dbConn->prepare('SELECT topic_id FROM msz_forum_topics WHERE forum_id = ? AND topic_deleted IS NULL ORDER BY RAND() LIMIT 1');
$stmtAnnounce = $dbConn->prepare('UPDATE msz_forum_topics SET topic_type = 2 WHERE topic_id = ?');
foreach($categoryIds as $categoryId) {
$stmtRevert->addParameter(1, $categoryId);
$stmtRevert->execute();
$stmtRandom->addParameter(1, $categoryId);
$stmtRandom->execute();
$resultRandom = $stmtRandom->getResult();
if($resultRandom->next()) {
$stmtAnnounce->addParameter(1, $resultRandom->getInteger(0));
$stmtAnnounce->execute();
}
}
});
msz_sched_task_func('Changing category icons...', false, function() use ($msz) {
$config = $msz->getConfig();
$categoryIds = $config->getArray('forum.rngicon');
if(!is_array($categoryIds))
return;
$dbConn = $msz->getDbConn();
$stmtIcon = $dbConn->prepare('UPDATE msz_forum_categories SET forum_icon = COALESCE(?, forum_icon), forum_name = COALESCE(?, forum_name), forum_colour = ((ROUND(RAND() * 255) << 16) | (ROUND(RAND() * 255) << 8) | ROUND(RAND() * 255)) WHERE forum_id = ?');
$stmtUnlock = $dbConn->prepare('UPDATE msz_forum_topics SET topic_locked = IF(?, NULL, COALESCE(topic_locked, NOW())) WHERE topic_id = ?');
foreach($categoryIds as $categoryId) {
$scoped = $config->scopeTo(sprintf('forum.rngicon.fc%d', $categoryId));
$icons = $scoped->getArray('icons');
$icon = $icons[array_rand($icons)];
$name = null;
$names = $scoped->getArray('names');
for($i = 0; $i < count($names); $i += 2)
if($names[$i] === $icon) {
$name = $names[$i + 1] ?? null;
break;
}
$name ??= $scoped->getString('name');
$stmtIcon->addParameter(1, $icon);
$stmtIcon->addParameter(2, empty($name) ? null : $name);
$stmtIcon->addParameter(3, $categoryId);
$stmtIcon->execute();
$unlockModes = $scoped->getArray('unlock');
foreach($unlockModes as $unlockMode) {
$unlockScoped = $scoped->scopeTo(sprintf('unlock.%s', $unlockMode));
$topicId = $unlockScoped->getInteger('topic');
$match = $unlockScoped->getArray('match');
$matches = in_array($icon, $match);
$stmtUnlock->addParameter(1, $matches ? 1 : 0);
$stmtUnlock->addParameter(2, $topicId);
$stmtUnlock->execute();
}
}
});
echo 'Running ' . count($schedTasks) . ' tasks...' . PHP_EOL;
$dbConn = $msz->getDbConn();