Compare commits

..

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

61 changed files with 884 additions and 1987 deletions

View file

@ -1,5 +1,5 @@
#include csrfp.js
#include msgbox.jsx
#include msgbox.js
#include utility.js
#include messages/actbtn.js
#include messages/list.js

171
build.js
View file

@ -1,30 +1,157 @@
const assproc = require('@railcomm/assproc');
const { join: pathJoin } = require('path');
// IMPORTS
const fs = require('fs');
const swc = require('@swc/core');
const path = require('path');
const util = require('util');
const postcss = require('postcss');
const utils = require('./assets/utils.js');
const assproc = require('./assets/assproc.js');
(async () => {
const isDebug = fs.existsSync(pathJoin(__dirname, '.debug'));
const env = {
root: __dirname,
source: pathJoin(__dirname, 'assets'),
public: pathJoin(__dirname, 'public'),
debug: isDebug,
swc: {
es: 'es2021',
// CONFIG
const rootDir = __dirname;
const srcDir = path.join(rootDir, 'assets');
const srcCurrentInfo = path.join(srcDir, 'current.json');
const pubDir = path.join(rootDir, 'public');
const pubAssetsDir = path.join(pubDir, 'assets');
const isDebugBuild = fs.existsSync(path.join(rootDir, '.debug'));
const buildTasks = {
js: [
{ source: 'misuzu.js', target: '/assets', name: 'misuzu.{hash}.js', },
],
css: [
{ source: 'misuzu.css', target: '/assets', name: 'misuzu.{hash}.css', },
],
};
// PREP
const postcssPlugins = [ require('autoprefixer')({ remove: false }) ];
if(!isDebugBuild)
postcssPlugins.push(require('cssnano')({
preset: [
'cssnano-preset-default',
{
minifyGradients: false,
reduceIdents: false,
zindex: true,
}
],
}));
const swcJscOptions = {
target: 'es2021',
loose: false,
externalHelpers: false,
keepClassNames: true,
preserveAllComments: false,
transform: {},
parser: {
syntax: 'ecmascript',
jsx: true,
dynamicImport: false,
privateMethod: false,
functionBind: false,
exportDefaultFrom: false,
exportNamespaceFrom: false,
decorators: false,
decoratorsBeforeExport: false,
topLevelAwait: true,
importMeta: false,
},
transform: {
react: {
runtime: 'classic',
pragma: '$er',
},
};
},
};
const tasks = {
js: [
{ source: 'misuzu.js', target: '/assets', name: 'misuzu.{hash}.js', },
],
css: [
{ source: 'misuzu.css', target: '/assets', name: 'misuzu.{hash}.css', },
],
};
const files = await assproc.process(env, tasks);
// BUILD
(async () => {
const files = {};
fs.writeFileSync(pathJoin(__dirname, 'assets/current.json'), JSON.stringify(files));
console.log('Ensuring assets directory exists...');
fs.mkdirSync(pubAssetsDir, { recursive: true });
console.log();
console.log('JS assets');
for(const info of buildTasks.js) {
console.log(`=> Building ${info.source}...`);
let origTarget = undefined;
if('es' in info) {
origTarget = swcJscOptions.target;
swcJscOptions.target = info.es;
}
const assprocOpts = {
prefix: '#',
entry: info.entry || 'main.js',
};
const swcOpts = {
filename: info.source,
sourceMaps: false,
isModule: false,
minify: !isDebugBuild,
jsc: swcJscOptions,
};
const pubName = await assproc.process(path.join(srcDir, info.source), assprocOpts)
.then(output => swc.transform(output, swcOpts))
.then(output => {
const name = utils.strtr(info.name, { hash: utils.shortHash(output.code) });
const pubName = path.join(info.target || '', name);
console.log(` Saving to ${pubName}...`);
fs.writeFileSync(path.join(pubDir, pubName), output.code);
return pubName;
});
if(origTarget !== undefined)
swcJscOptions.target = origTarget;
files[info.source] = pubName;
}
console.log();
console.log('CSS assets');
for(const info of buildTasks.css) {
console.log(`=> Building ${info.source}...`);
const sourcePath = path.join(srcDir, info.source);
const assprocOpts = {
prefix: '@',
entry: info.entry || 'main.css',
};
const postcssOpts = { from: sourcePath };
files[info.source] = await assproc.process(sourcePath, assprocOpts)
.then(output => postcss(postcssPlugins).process(output, postcssOpts)
.then(output => {
const name = utils.strtr(info.name, { hash: utils.shortHash(output.css) });
const pubName = path.join(info.target || '', name);
console.log(` Saving to ${pubName}...`);
fs.writeFileSync(path.join(pubDir, pubName), output.css);
return pubName;
}));
}
console.log();
console.log('Writing assets info...');
fs.writeFileSync(srcCurrentInfo, JSON.stringify(files));
console.log();
console.log('Cleaning up old builds...');
assproc.housekeep(pubAssetsDir);
})();

View file

@ -1,15 +1,15 @@
{
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"flashwave/index": "^0.2408.40014",
"flashwave/sasae": "^1.1",
"flashwave/syokuhou": "^1.2",
"flashwave/index": "dev-master",
"flashwave/sasae": "dev-master",
"erusev/parsedown": "~1.6",
"chillerlan/php-qrcode": "^4.3",
"symfony/mailer": "^6.0",
"matomo/device-detector": "^6.1",
"sentry/sdk": "^4.0",
"nesbot/carbon": "^3.7",
"flashwave/aiwass": "^1.0"
"flashwave/syokuhou": "dev-master"
},
"autoload": {
"classmap": [
@ -34,6 +34,6 @@
}
},
"require-dev": {
"phpstan/phpstan": "^1.11"
"phpstan/phpstan": "^1.10"
}
}

843
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`;
');
}
}

View file

@ -1,13 +0,0 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
final class AddRoleIdString_20240916_205613 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
$conn->execute(<<<SQL
ALTER TABLE msz_roles
ADD COLUMN role_string VARCHAR(20) NULL DEFAULT NULL COLLATE 'ascii_general_ci' AFTER role_id,
ADD UNIQUE INDEX roles_string_unique (role_string);
SQL);
}
}

View file

@ -1,9 +1,10 @@
<?php
namespace Misuzu;
use Index\Environment;
use Index\Data\DbTools;
use Syokuhou\DbConfig;
use Syokuhou\FileConfig;
use Syokuhou\SharpConfig;
define('MSZ_STARTUP', microtime(true));
define('MSZ_ROOT', __DIR__);
@ -18,11 +19,11 @@ define('MSZ_ASSETS', MSZ_ROOT . '/assets');
require_once MSZ_ROOT . '/vendor/autoload.php';
error_reporting(MSZ_DEBUG ? -1 : 0);
Environment::setDebug(MSZ_DEBUG);
mb_internal_encoding('UTF-8');
date_default_timezone_set('GMT');
date_default_timezone_set('UTC');
$cfg = FileConfig::fromFile(MSZ_CONFIG . '/config.cfg');
$cfg = SharpConfig::fromFile(MSZ_CONFIG . '/config.cfg');
if($cfg->hasValues('sentry:dsn'))
(function($cfg) {

793
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,8 @@
{
"dependencies": {
"@railcomm/assproc": "^1.0.0"
"@swc/core": "^1.5.24",
"autoprefixer": "^10.4.19",
"cssnano": "^6.1.2",
"postcss": "^8.4.38"
}
}

View file

@ -4,6 +4,3 @@ parameters:
- src
bootstrapFiles:
- misuzu.php
dynamicConstantNames:
- MSZ_CLI
- MSZ_DEBUG

View file

@ -3,10 +3,9 @@ namespace Misuzu;
use stdClass;
use RuntimeException;
use Index\DateTime;
use Misuzu\Forum\ForumTopicInfo;
use Misuzu\Parsers\Parser;
use Index\XDateTime;
use Carbon\CarbonImmutable;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
@ -153,11 +152,11 @@ if(!empty($_POST)) {
if($mode === 'create') {
$postTimeout = $cfg->getInteger('forum.posting.timeout', 5);
if($postTimeout > 0) {
$postTimeoutThreshold = new CarbonImmutable(sprintf('-%d seconds', $postTimeout));
$postTimeoutThreshold = DateTime::now()->modify(sprintf('-%d seconds', $postTimeout));
$lastPostCreatedAt = $forumPosts->getUserLastPostCreatedAt($currentUser);
if(XDateTime::compare($lastPostCreatedAt, $postTimeoutThreshold) > 0) {
$waitSeconds = $postTimeout + ((int)$lastPostCreatedAt->format('U') - time());
if($lastPostCreatedAt->isMoreThan($postTimeoutThreshold)) {
$waitSeconds = $postTimeout + ($lastPostCreatedAt->getUnixTimeSeconds() - time());
$notices[] = sprintf("You're posting too quickly! Please wait %s seconds before posting again.", number_format($waitSeconds));
$notices[] = "It's possible that your post went through successfully and you pressed the submit button twice by accident.";

View file

@ -3,9 +3,9 @@ namespace Misuzu;
use DateTimeInterface;
use RuntimeException;
use Index\DateTime;
use Index\XArray;
use Misuzu\Changelog\Changelog;
use Carbon\CarbonImmutable;
use Index\{XArray,XDateTime};
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
@ -58,8 +58,8 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
if(empty($createdAt))
$createdAt = null;
else {
$createdAt = CarbonImmutable::createFromFormat(DateTimeInterface::ATOM, $createdAt . ':00Z');
if((int)$createdAt->format('U') < 0)
$createdAt = DateTime::createFromFormat(DateTimeInterface::ATOM, $createdAt . ':00Z');
if($createdAt->getUnixTimeSeconds() < 0)
$createdAt = null;
}
@ -72,7 +72,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$summary = null;
if($body === $changeInfo->getBody())
$body = null;
if($createdAt !== null && XDateTime::compare($createdAt, $changeInfo->getCreatedAt()) === 0)
if($createdAt !== null && $createdAt->equals($changeInfo->getCreatedAt()))
$createdAt = null;
$updateUserInfo = $userId !== $changeInfo->getUserId();

View file

@ -3,7 +3,7 @@ namespace Misuzu;
use DateTimeInterface;
use RuntimeException;
use Carbon\CarbonImmutable;
use Index\DateTime;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('user')->check(Perm::U_BANS_MANAGE))
@ -56,7 +56,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
if($expires === -1) {
$expires = null;
} elseif($expires === -2) {
$expires = CarbonImmutable::createFromFormat(DateTimeInterface::ATOM, $expiresCustom . ':00Z');
$expires = DateTime::createFromFormat(DateTimeInterface::ATOM, $expiresCustom . ':00Z');
} else {
echo 'Invalid duration specified.';
break;

View file

@ -42,7 +42,6 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
break;
}
$roleString = (string)filter_input(INPUT_POST, 'ur_string');
$roleName = (string)filter_input(INPUT_POST, 'ur_name');
$roleHide = !empty($_POST['ur_hidden']);
$roleLeavable = !empty($_POST['ur_leavable']);
@ -55,7 +54,6 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$colourBlue = (int)filter_input(INPUT_POST, 'ur_col_blue', FILTER_SANITIZE_NUMBER_INT);
Template::set([
'role_ur_string' => $roleString,
'role_ur_name' => $roleName,
'role_ur_hidden' => $roleHide,
'role_ur_leavable' => $roleLeavable,
@ -98,31 +96,11 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
break;
}
if(strlen($roleString) > 20) {
echo 'Role string may not be longer than 20 characters.';
break;
}
if(strlen($roleString) > 1 && !ctype_alpha($roleString[0])) {
echo 'Role string most start with an alphabetical character.';
break;
}
if($isNew) {
$roleInfo = $roles->createRole(
$roleName,
$roleRank,
$roleColour,
string: $roleString,
title: $roleTitle,
description: $roleDesc,
hidden: $roleHide,
leavable: $roleLeavable
);
$roleInfo = $roles->createRole($roleName, $roleRank, $roleColour, $roleTitle, $roleDesc, $roleHide, $roleLeavable);
} else {
if($roleName === $roleInfo->getName())
$roleName = null;
if($roleString === $roleInfo->getString())
$roleString = null;
if($roleHide === $roleInfo->isHidden())
$roleHide = null;
if($roleLeavable === $roleInfo->isLeavable())
@ -137,17 +115,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
if((string)$roleColour === (string)$roleInfo->getColour())
$roleColour = null;
$roles->updateRole(
$roleInfo,
string: $roleString,
name: $roleName,
rank: $roleRank,
colour: $roleColour,
title: $roleTitle,
description: $roleDesc,
hidden: $roleHide,
leavable: $roleLeavable
);
$roles->updateRole($roleInfo, $roleName, $roleRank, $roleColour, $roleTitle, $roleDesc, $roleHide, $roleLeavable);
}
$msz->createAuditLog(

View file

@ -5,6 +5,7 @@ use stdClass;
use InvalidArgumentException;
use RuntimeException;
use Index\ByteFormat;
use Index\DateTime;
use Misuzu\Parsers\Parser;
use Misuzu\Users\User;
use Misuzu\Users\Assets\UserAvatarAsset;

View file

@ -2,7 +2,7 @@
namespace Misuzu\AuditLog;
use ValueError;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
@ -47,8 +47,8 @@ class AuditLogInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getRemoteAddressRaw(): string {

View file

@ -1,6 +1,7 @@
<?php
namespace Misuzu\Auth;
use Index\XArray;
use Misuzu\Auth\SessionInfo;
use Misuzu\Forum\ForumCategoryInfo;
use Misuzu\Perms\IPermissionResult;

View file

@ -1,63 +0,0 @@
<?php
namespace Misuzu\Auth;
use RuntimeException;
use Misuzu\Users\{UsersContext,UserInfo};
use Aiwass\Server\{RpcActionHandler,RpcProcedure};
use Syokuhou\IConfig;
final class AuthRpcActions extends RpcActionHandler {
public function __construct(
private IConfig $impersonateConfig,
private UsersContext $usersCtx,
private AuthContext $authCtx
) {}
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);
}
#[RpcProcedure('misuzu:auth:attemptMisuzuAuth')]
public function procAttemptMisuzuAuth(string $remoteAddr, string $token): array {
$tokenInfo = $this->authCtx->createAuthTokenPacker()->unpack($token);
if(!$tokenInfo->isEmpty())
$token = $tokenInfo->getSessionToken();
$sessions = $this->authCtx->getSessions();
try {
$sessionInfo = $sessions->getSession(sessionToken: $token);
} catch(RuntimeException $ex) {
return ['method' => 'misuzu', 'error' => 'token'];
}
if($sessionInfo->hasExpired()) {
$sessions->deleteSessions(sessionInfos: $sessionInfo);
return ['method' => 'misuzu', 'error' => 'expired'];
}
$sessions->recordSessionActivity(sessionInfo: $sessionInfo, remoteAddr: $remoteAddr);
$users = $this->usersCtx->getUsers();
$userInfo = $users->getUser($sessionInfo->getUserId(), 'id');
if($tokenInfo->hasImpersonatedUserId() && $this->canImpersonateUserId($userInfo, $tokenInfo->getImpersonatedUserId())) {
$userInfoReal = $userInfo;
try {
$userInfo = $users->getUser($tokenInfo->getImpersonatedUserId(), 'id');
} catch(RuntimeException $ex) {
$userInfo = $userInfoReal;
}
}
return [
'method' => 'misuzu',
'type' => 'user',
'user' => $userInfo->getId(),
'expires' => $sessionInfo->getExpiresTime(),
];
}
}

View file

@ -2,8 +2,8 @@
namespace Misuzu\Auth;
use RuntimeException;
use Index\UriBase64;
use Index\IO\MemoryStream;
use Index\Serialisation\UriBase64;
class AuthTokenPacker {
private const EPOCH_V2 = 1682985600;

View file

@ -1,10 +1,10 @@
<?php
namespace Misuzu\Auth;
use Misuzu\ClientInfo;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
use Misuzu\ClientInfo;
class LoginAttemptInfo {
public function __construct(
@ -57,8 +57,8 @@ class LoginAttemptInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getUserAgentString(): string {

View file

@ -1,6 +1,7 @@
<?php
namespace Misuzu\Auth;
use Index\TimeSpan;
use Index\Data\DbStatementCache;
use Index\Data\IDbConnection;
use Index\Net\IPAddress;
@ -22,12 +23,14 @@ class LoginAttempts {
?bool $success = null,
UserInfo|string|null $userInfo = null,
IPAddress|string|null $remoteAddr = null,
int|null $timeRange = null
TimeSpan|int|null $timeRange = null
): int {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($remoteAddr instanceof IPAddress)
$remoteAddr = (string)$remoteAddr;
if($timeRange instanceof TimeSpan)
$timeRange = (int)$timeRange->totalSeconds();
$hasSuccess = $success !== null;
$hasUserInfo = $userInfo !== null;
@ -78,13 +81,15 @@ class LoginAttempts {
?bool $success = null,
UserInfo|string|null $userInfo = null,
IPAddress|string|null $remoteAddr = null,
int|null $timeRange = null,
TimeSpan|int|null $timeRange = null,
?Pagination $pagination = null
): iterable {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($remoteAddr instanceof IPAddress)
$remoteAddr = (string)$remoteAddr;
if($timeRange instanceof TimeSpan)
$timeRange = (int)$timeRange->totalSeconds();
$hasSuccess = $success !== null;
$hasUserInfo = $userInfo !== null;

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Auth;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
@ -36,16 +36,16 @@ class RecoveryTokenInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getExpiresTime(): int {
return $this->created + self::LIFETIME;
}
public function getExpiresAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->getExpiresTime());
public function getExpiresAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created + self::LIFETIME);
}
public function hasExpired(): bool {

View file

@ -3,10 +3,10 @@ namespace Misuzu\Auth;
use InvalidArgumentException;
use RuntimeException;
use Index\Base32;
use Index\Data\DbStatementCache;
use Index\Data\IDbConnection;
use Index\Net\IPAddress;
use Index\Serialisation\Base32;
use Misuzu\ClientInfo;
use Misuzu\Pagination;
use Misuzu\Users\UserInfo;

View file

@ -1,10 +1,10 @@
<?php
namespace Misuzu\Auth;
use Misuzu\ClientInfo;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
use Misuzu\ClientInfo;
class SessionInfo {
public function __construct(
@ -91,8 +91,8 @@ class SessionInfo {
return $this->expires;
}
public function getExpiresAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->expires);
public function getExpiresAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->expires);
}
public function shouldBumpExpires(): bool {
@ -107,8 +107,8 @@ class SessionInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function hasLastActive(): bool {
@ -119,7 +119,7 @@ class SessionInfo {
return $this->lastActive;
}
public function getLastActiveAt(): ?CarbonImmutable {
return $this->lastActive === null ? null : CarbonImmutable::createFromTimestampUTC($this->lastActive);
public function getLastActiveAt(): ?DateTime {
return $this->lastActive === null ? null : DateTime::fromUnixTimeSeconds($this->lastActive);
}
}

View file

@ -1,23 +1,13 @@
<?php
namespace Misuzu;
use Index\CSRFP;
use Index\Security\CSRFP;
final class CSRF {
private static CSRFP $instance;
private static string $secretKey = '';
public static function create(string $identity, ?string $secretKey = null): CSRFP {
if($secretKey === null)
$secretKey = self::$secretKey;
else
self::$secretKey = $secretKey;
return new CSRFP($secretKey, $identity);
}
public static function init(string $secretKey, string $identity): void {
self::$instance = self::create($identity, $secretKey);
self::$instance = new CSRFP($secretKey, $identity);
}
public static function validate(string $token, int $tolerance = -1): bool {

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Changelog;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class ChangeInfo {
@ -53,8 +53,8 @@ class ChangeInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getDate(): string {

View file

@ -2,7 +2,7 @@
namespace Misuzu\Changelog;
use Stringable;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class ChangeTagInfo implements Stringable {
@ -38,16 +38,16 @@ class ChangeTagInfo implements Stringable {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getArchivedTime(): int {
return $this->archived;
}
public function getArchivedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->archived);
public function getArchivedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function isArchived(): bool {

View file

@ -3,7 +3,7 @@ namespace Misuzu\Changelog;
use InvalidArgumentException;
use RuntimeException;
use DateTimeInterface;
use Index\DateTime;
use Index\Data\DbStatementCache;
use Index\Data\DbTools;
use Index\Data\IDbConnection;
@ -66,13 +66,13 @@ class Changelog {
public function countChanges(
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $dateTime = null,
DateTime|int|null $dateTime = null,
?array $tags = null
): int {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($dateTime instanceof DateTimeInterface)
$dateTime = (int)$dateTime->format('U');
if($dateTime instanceof DateTime)
$dateTime = $dateTime->getUnixTimeSeconds();
$args = 0;
$hasUserInfo = $userInfo !== null;
@ -118,14 +118,14 @@ class Changelog {
public function getChanges(
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $dateTime = null,
DateTime|int|null $dateTime = null,
?array $tags = null,
?Pagination $pagination = null
): iterable {
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($dateTime instanceof DateTimeInterface)
$dateTime = (int)$dateTime->format('U');
if($dateTime instanceof DateTime)
$dateTime = $dateTime->getUnixTimeSeconds();
$args = 0;
$hasUserInfo = $userInfo !== null;
@ -189,14 +189,14 @@ class Changelog {
string $summary,
string $body = '',
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $createdAt = null
DateTime|int|null $createdAt = null
): ChangeInfo {
if(is_string($action))
$action = self::convertToActionId($action);
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($createdAt instanceof DateTimeInterface)
$createdAt = (int)$createdAt->format('U');
if($createdAt instanceof DateTime)
$createdAt = $createdAt->getUnixTimeSeconds();
$summary = trim($summary);
if(empty($summary))
@ -233,7 +233,7 @@ class Changelog {
?string $body = null,
bool $updateUserInfo = false,
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $createdAt = null
DateTime|int|null $createdAt = null
): void {
if($infoOrId instanceof ChangeInfo)
$infoOrId = $infoOrId->getId();
@ -242,8 +242,8 @@ class Changelog {
$action = self::convertToActionId($action);
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($createdAt instanceof DateTimeInterface)
$createdAt = (int)$createdAt->format('U');
if($createdAt instanceof DateTime)
$createdAt = $createdAt->getUnixTimeSeconds();
if($summary !== null) {
$summary = trim($summary);

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu\Comments;
use Misuzu\Users\UserInfo;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Misuzu\Users\UserInfo;
class CommentsCategoryInfo {
public function __construct(
@ -54,17 +54,16 @@ class CommentsCategoryInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getLockedTime(): ?int {
return $this->locked;
}
public function getLockedAt(): ?CarbonImmutable {
return $this->locked === null ? null : CarbonImmutable::createFromTimestampUTC($this->locked);
public function getLockedAt(): ?DateTime {
return $this->locked === null ? null : DateTime::fromUnixTimeSeconds($this->locked);
}
public function isLocked(): bool {

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Comments;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class CommentsPostInfo {
@ -86,16 +86,16 @@ class CommentsPostInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getPinnedTime(): ?int {
return $this->pinned;
}
public function getPinnedAt(): ?CarbonImmutable {
return $this->pinned === null ? null : CarbonImmutable::createFromTimestampUTC($this->pinned);
public function getPinnedAt(): DateTime {
return $this->pinned === null ? null : DateTime::fromUnixTimeSeconds($this->pinned);
}
public function isPinned(): bool {
@ -106,8 +106,8 @@ class CommentsPostInfo {
return $this->updated;
}
public function getUpdatedAt(): ?CarbonImmutable {
return $this->updated === null ? null : CarbonImmutable::createFromTimestampUTC($this->updated);
public function getUpdatedAt(): DateTime {
return $this->updated === null ? null : DateTime::fromUnixTimeSeconds($this->updated);
}
public function isEdited(): bool {
@ -118,8 +118,8 @@ class CommentsPostInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
public function isDeleted(): bool {

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Counters;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class CounterInfo {
@ -31,7 +31,7 @@ class CounterInfo {
return $this->updated;
}
public function getUpdatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->updated);
public function getUpdatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->updated);
}
}

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Forum;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Colour\Colour;
use Index\Data\IDbResult;
@ -176,8 +176,8 @@ class ForumCategoryInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function isArchived(): bool {

View file

@ -1,11 +1,10 @@
<?php
namespace Misuzu\Forum;
use Misuzu\Parsers\Parser;
use Carbon\CarbonImmutable;
use Index\XDateTime;
use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
use Misuzu\Parsers\Parser;
class ForumPostInfo {
public function __construct(
@ -94,17 +93,16 @@ class ForumPostInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
private static ?CarbonImmutable $markAsEditedThreshold = null;
private static ?DateTime $markAsEditedThreshold = null;
public function shouldMarkAsEdited(): bool {
if(self::$markAsEditedThreshold === null)
self::$markAsEditedThreshold = new CarbonImmutable('-5 minutes');
self::$markAsEditedThreshold = DateTime::now()->modify('-5 minutes');
return XDateTime::compare($this->getCreatedAt(), self::$markAsEditedThreshold) < 0;
return $this->getCreatedAt()->isLessThan(self::$markAsEditedThreshold);
}
public function isEdited(): bool {
@ -115,17 +113,16 @@ class ForumPostInfo {
return $this->edited;
}
public function getEditedAt(): ?CarbonImmutable {
return $this->edited === null ? null : CarbonImmutable::createFromTimestampUTC($this->edited);
public function getEditedAt(): ?DateTime {
return $this->edited === null ? null : DateTime::fromUnixTimeSeconds($this->edited);
}
private static ?CarbonImmutable $canBeDeletedThreshold = null;
private static ?DateTime $canBeDeletedThreshold = null;
public function canBeDeleted(): bool {
if(self::$canBeDeletedThreshold === null)
self::$canBeDeletedThreshold = new CarbonImmutable('-1 week');
self::$canBeDeletedThreshold = DateTime::now()->modify('-1 week');
return XDateTime::compare($this->getCreatedAt(), self::$canBeDeletedThreshold) >= 0;
return $this->getCreatedAt()->isMoreThanOrEqual(self::$canBeDeletedThreshold);
}
public function isDeleted(): bool {
@ -136,7 +133,7 @@ class ForumPostInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): ?DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
}

View file

@ -4,7 +4,7 @@ namespace Misuzu\Forum;
use InvalidArgumentException;
use RuntimeException;
use stdClass;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\DbStatementCache;
use Index\Data\DbTools;
use Index\Data\IDbConnection;
@ -395,8 +395,8 @@ class ForumPosts {
return $result->getInteger(0);
}
public function getUserLastPostCreatedAt(UserInfo|string $userInfo): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->getUserLastPostCreatedTime($userInfo));
public function getUserLastPostCreatedAt(UserInfo|string $userInfo): DateTime {
return DateTime::fromUnixTimeSeconds($this->getUserLastPostCreatedTime($userInfo));
}
public function generatePostRankings(

View file

@ -1,8 +1,7 @@
<?php
namespace Misuzu\Forum;
use Carbon\CarbonImmutable;
use Index\XDateTime;
use Index\DateTime;
use Index\Data\IDbResult;
class ForumTopicInfo {
@ -137,25 +136,25 @@ class ForumTopicInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
private static ?CarbonImmutable $lastActiveAt = null;
private static ?DateTime $lastActiveAt = null;
public function isActive(): bool {
if(self::$lastActiveAt === null)
self::$lastActiveAt = new CarbonImmutable('-1 month');
self::$lastActiveAt = DateTime::now()->modify('-1 month');
return XDateTime::compare($this->getBumpedAt(), self::$lastActiveAt) >= 0;
return $this->getBumpedAt()->isMoreThanOrEqual(self::$lastActiveAt);
}
public function getBumpedTime(): int {
return $this->bumped;
}
public function getBumpedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->bumped);
public function getBumpedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->bumped);
}
public function isDeleted(): bool {
@ -166,8 +165,8 @@ class ForumTopicInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): ?DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
public function isLocked(): bool {
@ -178,7 +177,7 @@ class ForumTopicInfo {
return $this->locked;
}
public function getLockedAt(): ?CarbonImmutable {
return $this->locked === null ? null : CarbonImmutable::createFromTimestampUTC($this->locked);
public function getLockedAt(): ?DateTime {
return $this->locked === null ? null : DateTime::fromUnixTimeSeconds($this->locked);
}
}

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Forum;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class ForumTopicRedirectInfo {
@ -41,7 +41,7 @@ class ForumTopicRedirectInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
}

View file

@ -1,162 +0,0 @@
<?php
namespace Misuzu\Hanyuu;
use RuntimeException;
use Misuzu\CSRF;
use Misuzu\Auth\AuthContext;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\{UsersContext,UserInfo};
use Aiwass\Server\{RpcActionHandler,RpcProcedure};
use Index\Colour\Colour;
use Syokuhou\IConfig;
final class HanyuuRpcActions extends RpcActionHandler {
public function __construct(
private $getBaseUrl,
private IConfig $impersonateConfig,
private URLRegistry $urls,
private UsersContext $usersCtx,
private AuthContext $authCtx
) {}
private static function createPayload(string $name, array $attrs = []): array {
$payload = ['name' => $name, 'attrs' => []];
foreach($attrs as $name => $value) {
if($value === null)
continue;
$payload['attrs'][(string)$name] = $value;
}
return $payload;
}
private static function createErrorPayload(string $code, ?string $text = null): array {
$attrs = ['code' => $code];
if($text !== null && $text !== '')
$attrs['text'] = $text;
return self::createPayload('error', $attrs);
}
private function canImpersonateUserId(UserInfo $impersonator, string $targetId): bool {
if($impersonator->isSuperUser())
return true;
return in_array(
$targetId,
$this->impersonateConfig->getArray(sprintf('allow.u%s', $impersonator->getId())),
true
);
}
#[RpcProcedure('mszhau:authCheck')]
public function procAuthCheck(string $method, string $remoteAddr, string $token, string $avatars = '') {
if($method !== 'Misuzu')
return self::createErrorPayload('auth:check:method', 'Requested auth method is not supported.');
if(filter_var($remoteAddr, FILTER_VALIDATE_IP) === false)
return self::createErrorPayload('auth:check:remote_addr', 'Provided remote address is not in a valid format.');
$avatarResolutions = trim($avatars);
if($avatarResolutions === '') {
$avatarResolutions = [];
} else {
$avatarResolutions = explode(',', $avatarResolutions);
foreach($avatarResolutions as $key => $avatarRes) {
if(!ctype_digit($avatarRes))
return self::createErrorPayload('auth:check:avatars', 'Avatar resolution set must be a comma separated set of numbers or empty.');
$avatarResolutions[$key] = (int)$avatarRes;
}
$avatarResolutions = array_unique($avatarResolutions);
}
$baseUrl = ($this->getBaseUrl)();
$loginUrl = $baseUrl . $this->urls->format('auth-login');
$registerUrl = $baseUrl . $this->urls->format('auth-register');
$tokenPacker = $this->authCtx->createAuthTokenPacker();
$tokenInfo = $tokenPacker->unpack(trim($token));
if($tokenInfo->isEmpty())
return self::createPayload('auth:check:fail', ['reason' => 'empty', 'login_url' => $loginUrl, 'register_url' => $registerUrl]);
$sessions = $this->authCtx->getSessions();
try {
$sessionInfo = $sessions->getSession(sessionToken: $tokenInfo->getSessionToken());
} catch(RuntimeException $ex) {
return self::createPayload('auth:check:fail', ['reason' => 'session', 'login_url' => $loginUrl, 'register_url' => $registerUrl]);
}
if($sessionInfo->hasExpired()) {
$sessions->deleteSessions(sessionInfos: $sessionInfo);
return self::createPayload('auth:check:fail', ['reason' => 'expired', 'login_url' => $loginUrl, 'register_url' => $registerUrl]);
}
$sessions->recordSessionActivity(sessionInfo: $sessionInfo, remoteAddr: $remoteAddr);
$users = $this->usersCtx->getUsers();
$userInfo = $userInfoReal = $users->getUser($sessionInfo->getUserId(), 'id');
if($tokenInfo->hasImpersonatedUserId() && $this->canImpersonateUserId($userInfo, $tokenInfo->getImpersonatedUserId())) {
try {
$userInfo = $users->getUser($tokenInfo->getImpersonatedUserId(), 'id');
} catch(RuntimeException $ex) {
$userInfo = $userInfoReal;
}
}
$response = [];
$response['session'] = [
'token' => $sessionInfo->getToken(),
'created_at' => $sessionInfo->getCreatedTime(),
'expires_at' => $sessionInfo->getExpiresTime(),
'lifetime_extends' => $sessionInfo->shouldBumpExpires(),
];
$banInfo = $this->usersCtx->tryGetActiveBan($userInfo);
if($banInfo !== null)
$response['ban'] = [
'severity' => $banInfo->getSeverity(),
'reason' => $banInfo->getPublicReason(),
'created_at' => $banInfo->getCreatedTime(),
'is_permanent' => $banInfo->isPermanent(),
'expires_at' => $banInfo->getExpiresTime(),
'duration_str' => $banInfo->getDurationString(),
'remaining_str' => $banInfo->getRemainingString(),
];
$gatherRequestedAvatars = function($userInfo) use ($avatarResolutions, $baseUrl) {
$formatAvatarUrl = fn($res = 0) => (
$baseUrl . $this->urls->format('user-avatar', ['user' => $userInfo->getId(), 'res' => $res])
);
$avatars = ['original' => $formatAvatarUrl()];
foreach($avatarResolutions as $avatarRes)
$avatars[sprintf('x%d', $avatarRes)] = $formatAvatarUrl($avatarRes);
return $avatars;
};
$extractUserInfo = fn($userInfo) => [
'id' => $userInfo->getId(),
'name' => $userInfo->getName(),
'colour' => (string)$users->getUserColour($userInfo),
'rank' => $users->getUserRank($userInfo),
'is_super' => $userInfo->isSuperUser(),
'country_code' => $userInfo->getCountryCode(),
'is_deleted' => $userInfo->isDeleted(),
'has_totp' => $userInfo->hasTOTPKey(),
'profile_url' => $baseUrl . $this->urls->format('user-profile', ['user' => $userInfo->getId()]),
'avatars' => $gatherRequestedAvatars($userInfo),
];
$response['user'] = $extractUserInfo($userInfo);
if($userInfo !== $userInfoReal) {
$response['guise'] = $extractUserInfo($userInfoReal);
$csrfp = CSRF::create($sessionInfo->getToken());
$response['guise']['revert_url'] = $baseUrl . $this->urls->format('auth-revert', ['csrf' => $csrfp->createToken()]);
}
return self::createPayload('auth:check:success', $response);
}
}

View file

@ -2,7 +2,7 @@
namespace Misuzu\Home;
use RuntimeException;
use Index\XDateTime;
use Index\DateTime;
use Index\Data\{DbTools,IDbConnection};
use Index\Http\Routing\{HttpGet,RouteHandler};
use Syokuhou\IConfig;
@ -167,7 +167,7 @@ class HomeRoutes extends RouteHandler {
$stats['users:online:recent'] = count($onlineUserInfos);
$birthdays = [];
$birthdayInfos = $this->usersCtx->getUsers()->getUsers(deleted: false, birthdate: XDateTime::now(), orderBy: 'random');
$birthdayInfos = $this->usersCtx->getUsers()->getUsers(deleted: false, birthdate: DateTime::now(), orderBy: 'random');
foreach($birthdayInfos as $birthdayInfo)
$birthdays[] = [
'info' => $birthdayInfo,

View file

@ -1,9 +1,9 @@
<?php
namespace Misuzu\Messages;
use Misuzu\Parsers\Parser;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
use Misuzu\Parsers\Parser;
class MessageInfo {
public function __construct(
@ -98,8 +98,8 @@ class MessageInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function isSent(): bool {
@ -110,8 +110,8 @@ class MessageInfo {
return $this->sent;
}
public function getSentAt(): ?CarbonImmutable {
return $this->sent === null ? null : CarbonImmutable::createFromTimestampUTC($this->sent);
public function getSentAt(): ?DateTime {
return $this->sent === null ? null : DateTime::fromUnixTimeSeconds($this->sent);
}
public function isRead(): bool {
@ -122,8 +122,8 @@ class MessageInfo {
return $this->read;
}
public function getReadAt(): ?CarbonImmutable {
return $this->read === null ? null : CarbonImmutable::createFromTimestampUTC($this->read);
public function getReadAt(): ?DateTime {
return $this->read === null ? null : DateTime::fromUnixTimeSeconds($this->read);
}
public function isDeleted(): bool {
@ -134,8 +134,8 @@ class MessageInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): ?DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
public function getDisplayTime(): int {
@ -144,7 +144,7 @@ class MessageInfo {
return $this->getCreatedTime();
}
public function getDisplayAt(): CarbonImmutable {
public function getDisplayAt(): DateTime {
if($this->isSent())
return $this->getSentAt();
return $this->getCreatedAt();

View file

@ -3,7 +3,7 @@ namespace Misuzu\Messages;
use InvalidArgumentException;
use RuntimeException;
use DateTimeInterface;
use Index\DateTime;
use Index\Data\{DbStatementCache,DbTools,IDbConnection};
use Misuzu\Pagination;
use Misuzu\Users\UserInfo;
@ -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 = ?';
@ -162,7 +162,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 = ?)'
));
@ -189,10 +189,10 @@ class MessagesDatabase {
string $body,
int $parser,
MessageInfo|string|null $replyTo = null,
DateTimeInterface|int|null $sentAt = null,
DateTimeInterface|int|null $readAt = null
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);
@ -201,8 +201,8 @@ class MessagesDatabase {
$stmt->addParameter(6, $title);
$stmt->addParameter(7, $body);
$stmt->addParameter(8, $parser);
$stmt->addParameter(9, $sentAt instanceof DateTimeInterface ? (int)$sentAt->format('U') : $sentAt);
$stmt->addParameter(10, $readAt instanceof DateTimeInterface ? (int)$readAt->format('U') : $readAt);
$stmt->addParameter(9, $sentAt instanceof DateTime ? $sentAt->getUnixTimeSeconds() : $sentAt);
$stmt->addParameter(10, $readAt instanceof DateTime ? $readAt->getUnixTimeSeconds() : $readAt);
$stmt->execute();
return $this->getMessageInfo($ownerInfo, $messageId);
@ -214,8 +214,8 @@ class MessagesDatabase {
?string $title = null,
?string $body = null,
?int $parser = null,
DateTimeInterface|int|null|false $sentAt = false,
DateTimeInterface|int|null|false $readAt = false
DateTime|int|null|false $sentAt = false,
DateTime|int|null|false $readAt = false
): void {
$setQuery = [];
$setValues = [];
@ -233,12 +233,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;
}
@ -249,12 +249,12 @@ class MessagesDatabase {
if($sentAt !== false) {
$setQuery[] = 'msg_sent = FROM_UNIXTIME(?)';
$setValues[] = $sentAt instanceof DateTimeInterface ? (int)$sentAt->format('U') : $sentAt;
$setValues[] = $sentAt instanceof DateTime ? $sentAt->getUnixTimeSeconds() : $sentAt;
}
if($readAt !== false) {
$setQuery[] = 'msg_read = FROM_UNIXTIME(?)';
$setValues[] = $readAt instanceof DateTimeInterface ? (int)$readAt->format('U') : $readAt;
$setValues[] = $readAt instanceof DateTime ? $readAt->getUnixTimeSeconds() : $readAt;
}
if(empty($whereQuery))

View file

@ -39,10 +39,6 @@ class MessagesRoutes extends RouteHandler {
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;
@ -357,6 +353,7 @@ class MessagesRoutes extends RouteHandler {
'error' => [
'name' => 'msgs:recipient_invalid',
'text' => 'Name of the recipient was incorrectly formatted.',
'jeff' => $recipient,
],
];
} catch(RuntimeException $ex) {

View file

@ -1,6 +1,11 @@
<?php
namespace Misuzu;
use Index\Environment;
use Index\Data\IDbConnection;
use Index\Data\Migration\{IDbMigrationRepo,DbMigrationManager,FsDbMigrationRepo};
use Sasae\SasaeEnvironment;
use Syokuhou\IConfig;
use Misuzu\Template;
use Misuzu\Auth\{AuthContext,AuthInfo};
use Misuzu\AuditLog\AuditLog;
@ -15,12 +20,6 @@ use Misuzu\Perms\Permissions;
use Misuzu\Profile\ProfileFields;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\{UsersContext,UserInfo};
use Aiwass\HmacVerificationProvider;
use Aiwass\Server\RpcServer;
use Index\Data\IDbConnection;
use Index\Data\Migration\{IDbMigrationRepo,DbMigrationManager,FsDbMigrationRepo};
use Sasae\SasaeEnvironment;
use Syokuhou\IConfig;
// this class should function as the root for everything going forward
// no more magical static classes that are just kind of assumed to exist
@ -192,7 +191,7 @@ class MisuzuContext {
['eeprom.appmsgs:s', '', 'eeprom_app_messages'],
]);
$isDebug = MSZ_DEBUG;
$isDebug = Environment::isDebug();
$globals['site_info'] = $this->siteInfo;
$globals['auth_info'] = $this->authInfo;
$globals['active_ban_info'] = $this->usersCtx->tryGetActiveBan($this->authInfo->getUserInfo());
@ -281,37 +280,6 @@ class MisuzuContext {
$routingCtx->register(new LegacyRoutes($this->urls));
$rpcServer = new RpcServer;
$routingCtx->getRouter()->register($rpcServer->createRouteHandler(
new HmacVerificationProvider(fn() => $this->config->getString('aleister.secret'))
));
$rpcServer->register(new Auth\AuthRpcActions(
$this->config->scopeTo('impersonate'),
$this->usersCtx,
$this->authCtx
));
$rpcServer->register(new Users\UsersRpcActions(
$this->siteInfo,
$this->urls,
$this->usersCtx
));
// This RPC server will eventually despawn when Hanyuu fully owns auth
$hanyuuRpcServer = new RpcServer;
$routingCtx->getRouter()->scopeTo('/_hanyuu')->register($hanyuuRpcServer->createRouteHandler(
new HmacVerificationProvider(fn() => $this->config->getString('hanyuu.secret'))
));
$hanyuuRpcServer->register(new Hanyuu\HanyuuRpcActions(
fn() => $this->config->getString('hanyuu.endpoint'),
$this->config->scopeTo('impersonate'),
$this->urls,
$this->usersCtx,
$this->authCtx
));
return $routingCtx;
}
}

View file

@ -1,11 +1,10 @@
<?php
namespace Misuzu;
use DateTimeInterface;
use Index\DateTime;
use Misuzu\MisuzuContext;
use Misuzu\Tools;
use Misuzu\Parsers\Parser;
use Carbon\CarbonImmutable;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
@ -47,18 +46,30 @@ final class MisuzuSasaeExtension extends AbstractExtension {
return $this->assets?->{$name} ?? '';
}
public function timeFormat(DateTimeInterface|string|int|null $dateTime): string {
public function timeFormat(DateTime|string|int|null $dateTime): string {
if($dateTime === null)
return 'never';
if(is_string($dateTime))
$dateTime = new CarbonImmutable($dateTime);
$dateTime = new DateTime($dateTime);
elseif(is_int($dateTime))
$dateTime = CarbonImmutable::createFromTimestampUTC($dateTime);
elseif(!($dateTime instanceof CarbonImmutable))
$dateTime = new CarbonImmutable($dateTime);
$dateTime = DateTime::fromUnixTimeSeconds($dateTime);
return $dateTime->diffForHumans();
$string = '';
$now = DateTime::now();
$isDiffYear = $now->getYear() !== $dateTime->getYear();
if($isDiffYear || $now->getMonth() !== $dateTime->getMonth() || $now->getDay() !== $dateTime->getDay()) {
$string .= $dateTime->format('M jS');
if($isDiffYear)
$string .= $dateTime->format(' Y');
$string .= ', ';
}
$string .= $dateTime->format('G:i ');
$string .= $dateTime->isUTC() ? 'UTC' : $dateTime->format('T');
return $string;
}
public function getHeaderMenu(): array {

View file

@ -3,7 +3,7 @@ namespace Misuzu\News;
use InvalidArgumentException;
use RuntimeException;
use DateTimeInterface;
use Index\DateTime;
use Index\Data\DbStatementCache;
use Index\Data\IDbConnection;
use Index\Data\IDbResult;
@ -286,14 +286,14 @@ class News {
string $body,
bool $featured = false,
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $schedule = null
DateTime|int|null $schedule = null
): NewsPostInfo {
if($categoryInfo instanceof NewsCategoryInfo)
$categoryInfo = $categoryInfo->getId();
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($schedule instanceof DateTimeInterface)
$schedule = (int)$schedule->format('U');
if($schedule instanceof DateTime)
$schedule = $schedule->getUnixTimeSeconds();
$title = trim($title);
if(empty($title))
@ -351,7 +351,7 @@ class News {
?bool $featured = null,
bool $updateUserInfo = false,
UserInfo|string|null $userInfo = null,
DateTimeInterface|int|null $schedule = null
DateTime|int|null $schedule = null
): void {
if($postInfo instanceof NewsPostInfo)
$postInfo = $postInfo->getId();
@ -359,8 +359,8 @@ class News {
$categoryInfo = $categoryInfo->getId();
if($userInfo instanceof UserInfo)
$userInfo = $userInfo->getId();
if($schedule instanceof DateTimeInterface)
$schedule = (int)$schedule->format('U');
if($schedule instanceof DateTime)
$schedule = $schedule->getUnixTimeSeconds();
if($title !== null) {
$title = trim($title);

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\News;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class NewsCategoryInfo {
@ -45,8 +45,8 @@ class NewsCategoryInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getPostsCount(): int {

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\News;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class NewsPostInfo {
@ -84,8 +84,8 @@ class NewsPostInfo {
return $this->scheduled;
}
public function getScheduledAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->scheduled);
public function getScheduledAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->scheduled);
}
public function isPublished(): bool {
@ -96,16 +96,16 @@ class NewsPostInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getUpdatedTime(): int {
return $this->updated;
}
public function getUpdatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->updated);
public function getUpdatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->updated);
}
public function isEdited(): bool {
@ -120,7 +120,7 @@ class NewsPostInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): ?DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
}

View file

@ -2,6 +2,7 @@
namespace Misuzu\News;
use RuntimeException;
use Index\DateTime;
use Index\Data\{DbTools,IDbConnection};
use Index\Http\Routing\{HttpGet,RouteHandler};
use Misuzu\{Pagination,SiteInfo,Template};

View file

@ -4,7 +4,8 @@ namespace Misuzu\Perms;
use stdClass;
use InvalidArgumentException;
use RuntimeException;
use Index\XDateTime;
use Index\DateTime;
use Index\Environment;
use Index\Data\DbStatementCache;
use Index\Data\DbTools;
use Index\Data\IDbConnection;
@ -370,10 +371,10 @@ class Permissions {
}
private static function precalculatePermissionsLog(string $fmt, ...$args): void {
if(!MSZ_CLI)
if(!Environment::isConsole())
return;
echo XDateTime::now()->format('[H:i:s.u] ');
echo DateTime::now()->format('[H:i:s.u] ');
vprintf($fmt, $args);
echo PHP_EOL;
}

View file

@ -2,15 +2,15 @@
namespace Misuzu\SharpChat;
use RuntimeException;
use Index\Colour\Colour;
use Index\Http\Routing\{HandlerAttribute,HttpDelete,HttpGet,HttpOptions,HttpPost,RouteHandler};
use Syokuhou\IConfig;
use Misuzu\RoutingContext;
use Misuzu\Auth\{AuthContext,AuthInfo,Sessions};
use Misuzu\Emoticons\Emotes;
use Misuzu\Perms\Permissions;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\{Bans,UsersContext,UserInfo};
use Index\Colour\Colour;
use Index\Http\Routing\{HandlerAttribute,HttpDelete,HttpGet,HttpOptions,HttpPost,RouteHandler};
use Syokuhou\IConfig;
final class SharpChatRoutes extends RouteHandler {
private string $hashKey;
@ -188,50 +188,7 @@ final class SharpChatRoutes extends RouteHandler {
if(!hash_equals($realHash, $userHash))
return ['success' => false, 'reason' => 'hash'];
if(strcasecmp($authMethod, 'Bearer') === 0) {
$bearerCheck = $this->config->getString('bearerCheck');
if($bearerCheck === '')
return ['success' => false, 'reason' => 'unsupported'];
$req = curl_init($bearerCheck);
try {
curl_setopt_array($req, [
CURLOPT_AUTOREFERER => false,
CURLOPT_FAILONERROR => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TCP_FASTOPEN => true,
CURLOPT_CONNECTTIMEOUT => 2,
CURLOPT_MAXREDIRS => 2,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_TIMEOUT => 5,
CURLOPT_USERAGENT => 'Misuzu',
CURLOPT_HTTPHEADER => [
sprintf('Authorization: Bearer %s', $authToken),
],
]);
$response = curl_exec($req);
if($response === false)
return ['success' => false, 'reason' => 'request'];
} finally {
curl_close($req);
}
$decoded = json_decode($response);
if($decoded === null)
return ['success' => false, 'reason' => 'decode'];
if(empty($decoded->user_id))
return ['success' => false, 'reason' => 'token'];
try {
$userInfo = $this->usersCtx->getUsers()->getUser($decoded->user_id, 'id');
} catch(RuntimeException $ex) {
return ['success' => false, 'reason' => 'user'];
}
} elseif($authMethod === 'SESS' || strcasecmp($authMethod, 'Misuzu') === 0) {
if($authMethod === 'SESS' || $authMethod === 'Misuzu') {
$tokenPacker = $this->authCtx->createAuthTokenPacker();
$tokenInfo = $tokenPacker->unpack($authToken);
if($tokenInfo->isEmpty()) {

View file

@ -2,7 +2,7 @@
namespace Misuzu;
use InvalidArgumentException;
use Index\Base32;
use Index\Serialisation\Base32;
class TOTPGenerator {
public const DIGITS = 6;

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Users;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class BanInfo {
@ -69,8 +69,8 @@ class BanInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function isPermanent(): bool {
@ -81,8 +81,8 @@ class BanInfo {
return $this->expires;
}
public function getExpiresAt(): ?CarbonImmutable {
return $this->expires === null ? null : CarbonImmutable::createFromTimestampUTC($this->expires);
public function getExpiresAt(): ?DateTime {
return $this->expires === null ? null : DateTime::fromUnixTimeSeconds($this->expires);
}
public function isActive(): bool {

View file

@ -3,11 +3,11 @@ namespace Misuzu\Users;
use InvalidArgumentException;
use RuntimeException;
use DateTimeInterface;
use Misuzu\Pagination;
use Index\DateTime;
use Index\Data\DbStatementCache;
use Index\Data\DbTools;
use Index\Data\IDbConnection;
use Misuzu\Pagination;
class Bans {
public const SEVERITY_MAX = 10;
@ -152,7 +152,7 @@ class Bans {
public function createBan(
UserInfo|string $userInfo,
DateTimeInterface|int|null $expires,
DateTime|int|null $expires,
string $publicReason,
string $privateReason,
int $severity = self::SEVERITY_DEFAULT,
@ -164,8 +164,8 @@ class Bans {
$userInfo = $userInfo->getId();
if($modInfo instanceof UserInfo)
$modInfo = $modInfo->getId();
if($expires instanceof DateTimeInterface)
$expires = (int)$expires->format('U');
if($expires instanceof DateTime)
$expires = $expires->getUnixTimeSeconds();
$stmt = $this->cache->get('INSERT INTO msz_users_bans (user_id, mod_id, ban_severity, ban_reason_public, ban_reason_private, ban_expires) VALUES (?, ?, ?, ?, ?, FROM_UNIXTIME(?))');
$stmt->addParameter(1, $userInfo);

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Users;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class ModNoteInfo {
@ -45,8 +45,8 @@ class ModNoteInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function getTitle(): string {

View file

@ -2,14 +2,13 @@
namespace Misuzu\Users;
use Stringable;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Colour\Colour;
use Index\Data\IDbResult;
class RoleInfo implements Stringable {
public function __construct(
private string $id,
private ?string $string,
private int $rank,
private string $name,
private ?string $title,
@ -23,15 +22,14 @@ class RoleInfo implements Stringable {
public static function fromResult(IDbResult $result): RoleInfo {
return new RoleInfo(
id: $result->getString(0),
string: $result->getStringOrNull(1),
rank: $result->getInteger(2),
name: $result->getString(3),
title: $result->getStringOrNull(4),
description: $result->getStringOrNull(5),
hidden: $result->getBoolean(6),
leavable: $result->getBoolean(7),
colour: $result->getIntegerOrNull(8),
created: $result->getInteger(9),
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),
);
}
@ -43,14 +41,6 @@ class RoleInfo implements Stringable {
return $this->id === Roles::DEFAULT_ROLE;
}
public function hasString(): bool {
return $this->string !== null && $this->string !== '';
}
public function getString(): ?string {
return $this->string;
}
public function getRank(): int {
return $this->rank;
}
@ -99,8 +89,8 @@ class RoleInfo implements Stringable {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function __toString(): string {

View file

@ -57,8 +57,6 @@ class Roles {
public function getRoles(
UserInfo|string|null $userInfo = null,
?bool $hidden = null,
?bool $hasString = null,
bool $orderByRank = false,
?Pagination $pagination = null
): iterable {
if($userInfo instanceof UserInfo)
@ -69,26 +67,23 @@ class Roles {
$hasPagination = $pagination !== null;
$args = 0;
$query = 'SELECT role_id, role_string, role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour, UNIX_TIMESTAMP(role_created) FROM msz_roles';
$query = 'SELECT role_id, role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour, UNIX_TIMESTAMP(role_created) FROM msz_roles';
if($hasUserInfo) {
++$args;
$query .= ' WHERE role_id IN (SELECT role_id FROM msz_users_roles WHERE user_id = ?)';
}
if($hasHidden)
$query .= sprintf(' %s role_hidden %s 0', ++$args > 1 ? 'AND' : 'WHERE', $hidden ? '<>' : '=');
if($hasString)
$query .= sprintf(' %s role_string %s NULL', ++$args > 1 ? 'AND' : 'WHERE', $hasString ? 'IS NOT' : 'IS');
if($orderByRank)
$query .= ' ORDER BY role_hierarchy DESC';
if($hasPagination)
$query .= ' LIMIT ? OFFSET ?';
$args = 0;
$stmt = $this->cache->get($query);
if($hasUserInfo)
$stmt->nextParameter($userInfo);
$stmt->addParameter(++$args, $userInfo);
if($hasPagination) {
$stmt->nextParameter($pagination->getRange());
$stmt->nextParameter($pagination->getOffset());
$stmt->addParameter(++$args, $pagination->getRange());
$stmt->addParameter(++$args, $pagination->getOffset());
}
$stmt->execute();
@ -96,7 +91,7 @@ class Roles {
}
public function getRole(string $roleId): RoleInfo {
$stmt = $this->cache->get('SELECT role_id, role_string, role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour, UNIX_TIMESTAMP(role_created) FROM msz_roles WHERE role_id = ?');
$stmt = $this->cache->get('SELECT role_id, role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour, UNIX_TIMESTAMP(role_created) FROM msz_roles WHERE role_id = ?');
$stmt->addParameter(1, $roleId);
$stmt->execute();
@ -111,7 +106,6 @@ class Roles {
string $name,
int $rank,
Colour $colour,
string $string = '',
string $title = '',
string $description = '',
bool $hidden = false,
@ -119,22 +113,18 @@ class Roles {
): RoleInfo {
$colour = $colour->shouldInherit() ? null : Colour::toMisuzu($colour);
if($string === '')
$string = null;
// should these continue to accept NULL?
if($title === '') $title = null;
if($description === '') $description = null;
$stmt = $this->cache->get('INSERT INTO msz_roles (role_string, role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->nextParameter($string);
$stmt->nextParameter($rank);
$stmt->nextParameter($name);
$stmt->nextParameter($title);
$stmt->nextParameter($description);
$stmt->nextParameter($hidden ? 1 : 0);
$stmt->nextParameter($leavable ? 1 : 0);
$stmt->nextParameter($colour);
$stmt = $this->cache->get('INSERT INTO msz_roles (role_hierarchy, role_name, role_title, role_description, role_hidden, role_can_leave, role_colour) VALUES (?, ?, ?, ?, ?, ?, ?)');
$stmt->addParameter(1, $rank);
$stmt->addParameter(2, $name);
$stmt->addParameter(3, $title);
$stmt->addParameter(4, $description);
$stmt->addParameter(5, $hidden ? 1 : 0);
$stmt->addParameter(6, $leavable ? 1 : 0);
$stmt->addParameter(7, $colour);
$stmt->execute();
return $this->getRole((string)$this->dbConn->getLastInsertId());
@ -166,7 +156,6 @@ class Roles {
public function updateRole(
RoleInfo|string $roleInfo,
?string $string = null,
?string $name = null,
?int $rank = null,
?Colour $colour = null,
@ -178,7 +167,6 @@ class Roles {
if($roleInfo instanceof RoleInfo)
$roleInfo = $roleInfo->getId();
$applyString = $string !== null;
$applyTitle = $title !== null;
$applyDescription = $description !== null;
$applyColour = $colour !== null;
@ -188,29 +176,24 @@ class Roles {
if($applyColour)
$colour = $colour->shouldInherit() ? null : Colour::toMisuzu($colour);
if($string === '')
$string = null;
// should these continue to accept NULL?
if($title === '') $title = null;
if($description === '') $description = null;
$stmt = $this->cache->get('UPDATE msz_roles SET role_string = IF(?, ?, role_string), role_hierarchy = COALESCE(?, role_hierarchy), role_name = COALESCE(?, role_name), role_title = IF(?, ?, role_title), role_description = IF(?, ?, role_description), role_hidden = IF(?, ?, role_hidden), role_can_leave = IF(?, ?, role_can_leave), role_colour = IF(?, ?, role_colour) WHERE role_id = ?');
$stmt->nextParameter($applyString ? 1 : 0);
$stmt->nextParameter($string);
$stmt->nextParameter($rank);
$stmt->nextParameter($name);
$stmt->nextParameter($applyTitle ? 1 : 0);
$stmt->nextParameter($title);
$stmt->nextParameter($applyDescription ? 1 : 0);
$stmt->nextParameter($description);
$stmt->nextParameter($applyHidden ? 1 : 0);
$stmt->nextParameter($hidden ? 1 : 0);
$stmt->nextParameter($applyLeavable ? 1 : 0);
$stmt->nextParameter($leavable ? 1 : 0);
$stmt->nextParameter($applyColour ? 1 : 0);
$stmt->nextParameter($colour);
$stmt->nextParameter($roleInfo);
$stmt = $this->cache->get('UPDATE msz_roles SET role_hierarchy = COALESCE(?, role_hierarchy), role_name = COALESCE(?, role_name), role_title = IF(?, ?, role_title), role_description = IF(?, ?, role_description), role_hidden = IF(?, ?, role_hidden), role_can_leave = IF(?, ?, role_can_leave), role_colour = IF(?, ?, role_colour) WHERE role_id = ?');
$stmt->addParameter(1, $rank);
$stmt->addParameter(2, $name);
$stmt->addParameter(3, $applyTitle ? 1 : 0);
$stmt->addParameter(4, $title);
$stmt->addParameter(5, $applyDescription ? 1 : 0);
$stmt->addParameter(6, $description);
$stmt->addParameter(7, $applyHidden ? 1 : 0);
$stmt->addParameter(8, $hidden ? 1 : 0);
$stmt->addParameter(9, $applyLeavable ? 1 : 0);
$stmt->addParameter(10, $leavable ? 1 : 0);
$stmt->addParameter(11, $applyColour ? 1 : 0);
$stmt->addParameter(12, $colour);
$stmt->addParameter(13, $roleInfo);
$stmt->execute();
}

View file

@ -1,11 +1,12 @@
<?php
namespace Misuzu\Users;
use Misuzu\Parsers\Parser;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\TimeZoneInfo;
use Index\Colour\Colour;
use Index\Data\IDbResult;
use Index\Net\IPAddress;
use Misuzu\Parsers\Parser;
class UserInfo {
public function __construct(
@ -130,8 +131,8 @@ class UserInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
public function hasLastActive(): bool {
@ -142,8 +143,8 @@ class UserInfo {
return $this->lastActive;
}
public function getLastActiveAt(): ?CarbonImmutable {
return $this->lastActive === null ? null : CarbonImmutable::createFromTimestampUTC($this->lastActive);
public function getLastActiveAt(): ?DateTime {
return $this->lastActive === null ? null : DateTime::fromUnixTimeSeconds($this->lastActive);
}
public function isDeleted(): bool {
@ -154,8 +155,8 @@ class UserInfo {
return $this->deleted;
}
public function getDeletedAt(): ?CarbonImmutable {
return $this->deleted === null ? null : CarbonImmutable::createFromTimestampUTC($this->deleted);
public function getDeletedAt(): ?DateTime {
return $this->deleted === null ? null : DateTime::fromUnixTimeSeconds($this->deleted);
}
public function hasDisplayRoleId(): bool {
@ -230,15 +231,15 @@ class UserInfo {
return $this->birthdate;
}
public function getBirthdate(): ?CarbonImmutable {
return $this->birthdate === null ? null : CarbonImmutable::createFromFormat('Y-m-d', $this->birthdate, 'UTC');
public function getBirthdate(): ?DateTime {
return $this->birthdate === null ? null : DateTime::createFromFormat('Y-m-d', $this->birthdate, TimeZoneInfo::utc());
}
public function getAge(): int {
$birthdate = $this->getBirthdate();
if($birthdate === null || (int)$birthdate->format('Y') < 1900)
if($birthdate === null || $birthdate->getYear() < 1900)
return -1;
return (int)$birthdate->diff(CarbonImmutable::now())->format('%y');
return (int)$birthdate->diff(DateTime::now())->format('%y');
}
public function hasBackgroundSettings(): bool {

View file

@ -3,7 +3,7 @@ namespace Misuzu\Users;
use InvalidArgumentException;
use RuntimeException;
use DateTimeInterface;
use Index\DateTime;
use Index\XString;
use Index\Colour\Colour;
use Index\Data\DbStatementCache;
@ -46,7 +46,7 @@ class Users {
UserInfo|string|null $after = null,
?int $lastActiveInMinutes = null,
?int $newerThanDays = null,
?DateTimeInterface $birthdate = null,
?DateTime $birthdate = null,
?bool $deleted = null
): int {
if($roleInfo instanceof RoleInfo)
@ -106,7 +106,7 @@ class Users {
UserInfo|string|null $after = null,
?int $lastActiveInMinutes = null,
?int $newerThanDays = null,
?DateTimeInterface $birthdate = null,
?DateTime $birthdate = null,
?bool $deleted = null,
?string $orderBy = null,
?bool $reverseOrder = null,

View file

@ -1,86 +0,0 @@
<?php
namespace Misuzu\Users;
use RuntimeException;
use Misuzu\SiteInfo;
use Misuzu\URLs\URLRegistry;
use Misuzu\Users\Assets\UserAvatarAsset;
use Aiwass\Server\{RpcActionHandler,RpcQuery};
use Index\XArray;
use Index\Colour\{Colour,ColourRGB};
final class UsersRpcActions extends RpcActionHandler {
public function __construct(
private SiteInfo $siteInfo,
private URLRegistry $urls,
private UsersContext $usersCtx
) {}
#[RpcQuery('misuzu:users:getUser')]
public function queryGetUser(string $userId): array {
try {
$userInfo = $this->usersCtx->getUserInfo($userId, Users::GET_USER_ID);
} catch(RuntimeException) {
return ['error' => 'notfound'];
}
// TODO: there should be some kinda privacy controls for users
$rank = $this->usersCtx->getUserRank($userInfo);
$colour = $this->usersCtx->getUserColour($userInfo);
if($colour->shouldInherit()) {
$colourRaw = null;
$colourCSS = (string)$colour;
} else {
// Index doesn't have a proper toRawRGB func???
$colourRaw = Colour::toMisuzu($colour) & 0xFFFFFF;
$colourCSS = (string)ColourRGB::convert($colour);
}
$baseUrl = $this->siteInfo->getURL();
$avatars = [];
$formatAvatarUrl = fn($res = 0) => (
$baseUrl . $this->urls->format('user-avatar', ['user' => $userInfo->getId(), 'res' => $res])
);
$avatars[] = ['res' => 0, 'url' => $formatAvatarUrl()];
foreach(UserAvatarAsset::DIMENSIONS as $res)
$avatars[] = ['res' => $res, 'url' => $formatAvatarUrl($res)];
$avatars = array_reverse($avatars);
$output = [
'id' => $userInfo->getId(),
'name' => $userInfo->getName(),
'colour_raw' => $colourRaw,
'colour_css' => $colourCSS,
'rank' => $rank,
'country_code' => $userInfo->getCountryCode(),
'avatar_urls' => $avatars,
'profile_url' => $baseUrl . $this->urls->format('user-profile', ['user' => $userInfo->getId()]),
'created_at' => $userInfo->getCreatedAt()->toIso8601ZuluString(),
];
if($userInfo->hasLastActive())
$output['last_active_at'] = $userInfo->getLastActiveAt()->toIso8601ZuluString();
$roles = XArray::select(
$this->usersCtx->getRoles()->getRoles(userInfo: $userInfo, hasString: true, orderByRank: true),
fn($roleInfo) => $roleInfo->getString(),
);
if(!empty($roles))
$output['roles'] = $roles;
if($userInfo->hasTitle())
$output['title'] = $userInfo->getTitle();
if($userInfo->isSuperUser())
$output['is_super'] = true;
if($userInfo->isDeleted())
$output['is_deleted'] = true;
return $output;
}
}

View file

@ -1,7 +1,7 @@
<?php
namespace Misuzu\Users;
use Carbon\CarbonImmutable;
use Index\DateTime;
use Index\Data\IDbResult;
class WarningInfo {
@ -55,7 +55,7 @@ class WarningInfo {
return $this->created;
}
public function getCreatedAt(): CarbonImmutable {
return CarbonImmutable::createFromTimestampUTC($this->created);
public function getCreatedAt(): DateTime {
return DateTime::fromUnixTimeSeconds($this->created);
}
}

View file

@ -17,13 +17,6 @@
</div>
</label>
<label class="form__label">
<div class="form__label__text">Role String (used in API)</div>
<div class="form__label__input">
{{ input_text('ur_string', '', role_ur_string|default(role_info.string|default()), 'text', '', false, {'maxlength':20}) }}
</div>
</label>
<label class="form__label">
<div class="form__label__text">Hide Role</div>
<div class="form__label__input">
@ -51,6 +44,7 @@
{{ input_text('ur_title', '', role_ur_title|default(role_info.title|default()), 'text', '', false, {'maxlength':64}) }}
</div>
</label>
</div>
<div class="container">

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) {