Moved constants out of misuzu.php.

This commit is contained in:
flash 2025-02-09 20:44:10 +00:00
parent 1d54d41f6b
commit 4110cd5190
16 changed files with 77 additions and 50 deletions

View file

@ -5,21 +5,10 @@ use Index\Config\Fs\FsConfig;
define('MSZ_STARTUP', microtime(true)); define('MSZ_STARTUP', microtime(true));
define('MSZ_ROOT', __DIR__); define('MSZ_ROOT', __DIR__);
define('MSZ_CLI', PHP_SAPI === 'cli');
define('MSZ_DEBUG', is_file(MSZ_ROOT . '/.debug'));
define('MSZ_PUBLIC', MSZ_ROOT . '/public');
define('MSZ_SOURCE', MSZ_ROOT . '/src');
define('MSZ_CONFIG', MSZ_ROOT . '/config');
define('MSZ_TEMPLATES', MSZ_ROOT . '/templates');
define('MSZ_MIGRATIONS', MSZ_ROOT . '/database');
require_once MSZ_ROOT . '/vendor/autoload.php'; require_once __DIR__ . '/vendor/autoload.php';
error_reporting(MSZ_DEBUG ? -1 : 0); $env = FsConfig::fromFile(Misuzu::PATH_CONFIG . '/config.cfg');
mb_internal_encoding('UTF-8');
date_default_timezone_set('GMT');
$env = FsConfig::fromFile(MSZ_CONFIG . '/config.cfg');
if($env->hasValues('sentry:dsn')) if($env->hasValues('sentry:dsn'))
(function($env) { (function($env) {

View file

@ -6,11 +6,9 @@ parameters:
- src - src
- public - public
- public-legacy - public-legacy
- tools
bootstrapFiles: bootstrapFiles:
- misuzu.php - misuzu.php
dynamicConstantNames:
- MSZ_CLI
- MSZ_DEBUG
ignoreErrors: ignoreErrors:
- -
identifier: variable.undefined identifier: variable.undefined

View file

@ -46,7 +46,7 @@ header('Content-Type: text/plain; charset=utf-8');
if($_SERVER['REQUEST_METHOD'] !== 'POST') if($_SERVER['REQUEST_METHOD'] !== 'POST')
die('no'); die('no');
$config = MSZ_CONFIG . '/github.ini'; $config = Misuzu::PATH_CONFIG . '/github.ini';
if(!is_file($config)) if(!is_file($config))
die('config missing'); die('config missing');

View file

@ -29,17 +29,17 @@ else
// The whole wall of shit before the router setup and dispatch should be worked away // The whole wall of shit before the router setup and dispatch should be worked away
// Lockdown things should be middleware when there's no more legacy files // Lockdown things should be middleware when there's no more legacy files
$request = \Index\Http\HttpRequest::fromRequest();
ob_start(); ob_start();
if(is_file(MSZ_ROOT . '/.migrating')) { if(is_file($msz->dbCtx->getMigrateLockPath())) {
http_response_code(503); http_response_code(503);
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
header('X-Accel-Redirect: /error-503.html'); header('X-Accel-Redirect: /error-503.html');
exit; exit;
} }
$request = \Index\Http\HttpRequest::fromRequest();
$tokenPacker = $msz->authCtx->createAuthTokenPacker(); $tokenPacker = $msz->authCtx->createAuthTokenPacker();
if(filter_has_var(INPUT_COOKIE, 'msz_auth')) if(filter_has_var(INPUT_COOKIE, 'msz_auth'))
@ -130,7 +130,7 @@ $msz->startTemplating();
if(in_array('main', $msz->env->getArray(sprintf('domain:%s', $request->getHeaderLine('Host'))))) { if(in_array('main', $msz->env->getArray(sprintf('domain:%s', $request->getHeaderLine('Host'))))) {
$mszRequestPath = substr($request->path, 1); $mszRequestPath = substr($request->path, 1);
$mszLegacyPathPrefix = MSZ_PUBLIC . '-legacy/'; $mszLegacyPathPrefix = Misuzu::PATH_PUBLIC_LEGACY . '/';
$mszLegacyPath = $mszLegacyPathPrefix . $mszRequestPath; $mszLegacyPath = $mszLegacyPathPrefix . $mszRequestPath;
if(str_starts_with($mszLegacyPath, $mszLegacyPathPrefix)) { if(str_starts_with($mszLegacyPath, $mszLegacyPathPrefix)) {

View file

@ -30,11 +30,11 @@ class DatabaseContext implements RouteHandler {
} }
public function createMigrationRepo(): DbMigrationRepo { public function createMigrationRepo(): DbMigrationRepo {
return new FsDbMigrationRepo(MSZ_MIGRATIONS); return new FsDbMigrationRepo(Misuzu::PATH_DATABASE);
} }
public function getMigrateLockPath(): string { public function getMigrateLockPath(): string {
return sys_get_temp_dir() . '/misuzu-migration-' . hash('sha256', MSZ_ROOT) . '.lock'; return sys_get_temp_dir() . '/misuzu-migration-' . hash('sha256', Misuzu::PATH_ROOT) . '.lock';
} }
/** @return void|int */ /** @return void|int */

View file

@ -1,23 +1,26 @@
<?php <?php
namespace Misuzu\Info; namespace Misuzu\Info;
use Index\Index;
use Index\Http\{HttpRequest,HttpResponseBuilder}; use Index\Http\{HttpRequest,HttpResponseBuilder};
use Index\Http\Routing\{HttpGet,RouteHandler,RouteHandlerCommon}; use Index\Http\Routing\{HttpGet,RouteHandler,RouteHandlerCommon};
use Index\Urls\{UrlFormat,UrlSource,UrlSourceCommon}; use Index\Urls\{UrlFormat,UrlSource,UrlSourceCommon};
use Misuzu\Template; use Misuzu\{Misuzu,Template};
use Misuzu\Parsers\{Parsers,TextFormat}; use Misuzu\Parsers\{Parsers,TextFormat};
use RPCii\RPCii;
class InfoRoutes implements RouteHandler, UrlSource { class InfoRoutes implements RouteHandler, UrlSource {
use RouteHandlerCommon, UrlSourceCommon; use RouteHandlerCommon, UrlSourceCommon;
private const DOCS_PATH = MSZ_ROOT . '/docs';
private const PROJECT_PATHS = [ private const PROJECT_PATHS = [
'misuzu' => MSZ_ROOT, 'misuzu' => Misuzu::PATH_ROOT,
'index' => MSZ_ROOT . '/vendor/flashwave/index', 'index' => Index::PATH_ROOT,
'rpcii' => RPCii::PATH_ROOT,
]; ];
private const PROJECT_SUFFIXES = [ private const PROJECT_SUFFIXES = [
'misuzu' => 'Misuzu Project » %s', 'misuzu' => 'Misuzu » %s',
'index' => 'Index Project » %s', 'index' => 'Index » %s',
'rpcii' => 'RPCii » %s',
]; ];
#[HttpGet('/info')] #[HttpGet('/info')]
@ -31,7 +34,7 @@ class InfoRoutes implements RouteHandler, UrlSource {
#[UrlFormat('info-doc', '/info/<title>')] #[UrlFormat('info-doc', '/info/<title>')]
public function getDocsPage(HttpResponseBuilder $response, HttpRequest $request, string $name): string { public function getDocsPage(HttpResponseBuilder $response, HttpRequest $request, string $name): string {
return $this->serveMarkdownDocument( return $this->serveMarkdownDocument(
sprintf('%s/%s.md', self::DOCS_PATH, $name) sprintf('%s/%s.md', Misuzu::PATH_DOCS, $name)
); );
} }

View file

@ -9,7 +9,7 @@ use Symfony\Component\Mailer\Transport as SymfonyTransport;
use Symfony\Component\Mailer\Transport\TransportInterface as SymfonyTransportInterface; use Symfony\Component\Mailer\Transport\TransportInterface as SymfonyTransportInterface;
final class Mailer { final class Mailer {
private const TEMPLATE_PATH = MSZ_ROOT . '/config/emails/%s.txt'; private const TEMPLATE_PATH = Misuzu::PATH_CONFIG . '/emails/%s.txt';
private static Config $config; private static Config $config;
private static ?SymfonyTransportInterface $transport; private static ?SymfonyTransportInterface $transport;

View file

@ -10,7 +10,7 @@ use Index\Colour\Colour;
use Index\Http\{FormHttpContent,HttpRequest,HttpResponseBuilder}; use Index\Http\{FormHttpContent,HttpRequest,HttpResponseBuilder};
use Index\Http\Routing\{HttpGet,HttpMiddleware,HttpPost,RouteHandler,RouteHandlerCommon}; use Index\Http\Routing\{HttpGet,HttpMiddleware,HttpPost,RouteHandler,RouteHandlerCommon};
use Index\Urls\{UrlFormat,UrlRegistry,UrlSource,UrlSourceCommon}; use Index\Urls\{UrlFormat,UrlRegistry,UrlSource,UrlSourceCommon};
use Misuzu\{CSRF,Pagination,Perm,Template}; use Misuzu\{CSRF,Misuzu,Pagination,Perm,Template};
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Parsers\TextFormat; use Misuzu\Parsers\TextFormat;
use Misuzu\Perms\PermissionsData; use Misuzu\Perms\PermissionsData;
@ -45,7 +45,7 @@ class MessagesRoutes implements RouteHandler, UrlSource {
return 401; return 401;
// do not allow access to PMs when impersonating in production mode // do not allow access to PMs when impersonating in production mode
if(!MSZ_DEBUG && $this->authInfo->impersonating) if(!Misuzu::debug() && $this->authInfo->impersonating)
return 403; return 403;
$globalPerms = $this->authInfo->getPerms('global'); $globalPerms = $this->authInfo->getPerms('global');

View file

@ -1,10 +1,28 @@
<?php <?php
namespace Misuzu; namespace Misuzu;
if(!defined('MSZ_ROOT')) {
define('MSZ_ROOT', (function() {
$root = __DIR__ . DIRECTORY_SEPARATOR . '..';
$path = realpath($root);
if(!is_string($path))
$path = $root;
return $path;
})());
}
final class Misuzu { final class Misuzu {
public const string PATH_SOURCE = __DIR__; public const string PATH_ROOT = MSZ_ROOT;
public const string PATH_ROOT = self::PATH_SOURCE . DIRECTORY_SEPARATOR . '..';
public const string PATH_ASSETS = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'assets'; public const string PATH_ASSETS = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'assets';
public const string PATH_CONFIG = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'config';
public const string PATH_DATABASE = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'database';
public const string PATH_DOCS = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'docs';
public const string PATH_PUBLIC = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'public';
public const string PATH_PUBLIC_LEGACY = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'public-legacy';
public const string PATH_SOURCE = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'src';
public const string PATH_STORE = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'store';
public const string PATH_TEMPLATES = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'templates';
public const string PATH_VERSION = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'VERSION'; public const string PATH_VERSION = self::PATH_ROOT . DIRECTORY_SEPARATOR . 'VERSION';
public static function version(): string { public static function version(): string {
@ -17,4 +35,8 @@ final class Misuzu {
return trim($version); return trim($version);
} }
public static function debug(): bool {
return !empty(ini_get('display_errors'));
}
} }

View file

@ -120,14 +120,14 @@ class MisuzuContext {
['eeprom.appmsgs:s', '', 'eeprom_app_messages'], ['eeprom.appmsgs:s', '', 'eeprom_app_messages'],
]); ]);
$isDebug = MSZ_DEBUG; $isDebug = Misuzu::debug();
$globals['site_info'] = $this->siteInfo; $globals['site_info'] = $this->siteInfo;
$globals['auth_info'] = $this->authInfo; $globals['auth_info'] = $this->authInfo;
$globals['active_ban_info'] = $this->usersCtx->tryGetActiveBan($this->authInfo->userInfo); $globals['active_ban_info'] = $this->usersCtx->tryGetActiveBan($this->authInfo->userInfo);
$globals['display_timings_info'] = $isDebug || $this->authInfo->getPerms('global')->check(Perm::G_TIMINGS_VIEW); $globals['display_timings_info'] = $isDebug || $this->authInfo->getPerms('global')->check(Perm::G_TIMINGS_VIEW);
$this->templating = new TplEnvironment( $this->templating = new TplEnvironment(
MSZ_TEMPLATES, Misuzu::PATH_TEMPLATES,
cache: $isDebug || !$cache ? null : ['Misuzu', GitInfo::hash(true)], cache: $isDebug || !$cache ? null : ['Misuzu', GitInfo::hash(true)],
debug: $isDebug debug: $isDebug
); );

View file

@ -381,7 +381,7 @@ class PermissionsData {
* @param bool|float|int|string|null ...$args * @param bool|float|int|string|null ...$args
*/ */
private static function precalculatePermissionsLog(string $fmt, ...$args): void { private static function precalculatePermissionsLog(string $fmt, ...$args): void {
if(!MSZ_CLI) if(php_sapi_name() === 'cli')
return; return;
echo XDateTime::now()->format('[H:i:s.u] '); echo XDateTime::now()->format('[H:i:s.u] ');

View file

@ -2,7 +2,7 @@
namespace Misuzu\Routing; namespace Misuzu\Routing;
use Index\Http\{HtmlHttpErrorHandler,HttpResponseBuilder,HttpRequest}; use Index\Http\{HtmlHttpErrorHandler,HttpResponseBuilder,HttpRequest};
use Misuzu\Template; use Misuzu\{Misuzu,Template};
class RoutingErrorHandler extends HtmlHttpErrorHandler { class RoutingErrorHandler extends HtmlHttpErrorHandler {
public function handle(HttpResponseBuilder $response, HttpRequest $request, int $code, string $message): void { public function handle(HttpResponseBuilder $response, HttpRequest $request, int $code, string $message): void {
@ -13,7 +13,7 @@ class RoutingErrorHandler extends HtmlHttpErrorHandler {
} }
$path = sprintf('/error-%03d.html', $code); $path = sprintf('/error-%03d.html', $code);
if(is_file(MSZ_PUBLIC . $path)) { if(is_file(Misuzu::PATH_PUBLIC . $path)) {
$response->setTypeHTML(); $response->setTypeHTML();
$response->accelRedirect($path); $response->accelRedirect($path);
return; return;

View file

@ -6,7 +6,7 @@ use RuntimeException;
use Index\Http\{HttpRequest,HttpResponseBuilder}; use Index\Http\{HttpRequest,HttpResponseBuilder};
use Index\Http\Routing\{HttpGet,RouteHandler,RouteHandlerCommon}; use Index\Http\Routing\{HttpGet,RouteHandler,RouteHandlerCommon};
use Index\Urls\{UrlFormat,UrlRegistry,UrlSource,UrlSourceCommon}; use Index\Urls\{UrlFormat,UrlRegistry,UrlSource,UrlSourceCommon};
use Misuzu\Perm; use Misuzu\{Misuzu,Perm};
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Users\{UsersContext,UserInfo}; use Misuzu\Users\{UsersContext,UserInfo};
@ -34,13 +34,13 @@ class AssetsRoutes implements RouteHandler, UrlSource {
#[HttpGet('/assets/avatar/([0-9]+)(?:\.[a-z]+)?')] #[HttpGet('/assets/avatar/([0-9]+)(?:\.[a-z]+)?')]
#[UrlFormat('user-avatar', '/assets/avatar/<user>', ['res' => '<res>'])] #[UrlFormat('user-avatar', '/assets/avatar/<user>', ['res' => '<res>'])]
public function getAvatar(HttpResponseBuilder $response, HttpRequest $request, string $userId = '') { public function getAvatar(HttpResponseBuilder $response, HttpRequest $request, string $userId = '') {
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC); $assetInfo = new StaticUserImageAsset(Misuzu::PATH_PUBLIC . '/images/no-avatar.png', Misuzu::PATH_PUBLIC);
try { try {
$userInfo = $this->usersCtx->getUserInfo($userId); $userInfo = $this->usersCtx->getUserInfo($userId);
if(!$this->canViewAsset($request, $userInfo)) { if(!$this->canViewAsset($request, $userInfo)) {
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/banned-avatar.png', MSZ_PUBLIC); $assetInfo = new StaticUserImageAsset(Misuzu::PATH_PUBLIC . '/images/banned-avatar.png', Misuzu::PATH_PUBLIC);
} else { } else {
$userAssetInfo = new UserAvatarAsset($userInfo); $userAssetInfo = new UserAvatarAsset($userInfo);
if($userAssetInfo->isPresent()) if($userAssetInfo->isPresent())

View file

@ -3,6 +3,7 @@ namespace Misuzu\Users\Assets;
use InvalidArgumentException; use InvalidArgumentException;
use RuntimeException; use RuntimeException;
use Misuzu\Misuzu;
use Misuzu\Users\UserInfo; use Misuzu\Users\UserInfo;
abstract class UserImageAsset implements UserImageAssetInterface { abstract class UserImageAsset implements UserImageAssetInterface {
@ -77,7 +78,7 @@ abstract class UserImageAsset implements UserImageAssetInterface {
} }
public function getStoragePath(): string { public function getStoragePath(): string {
return MSZ_ROOT . DIRECTORY_SEPARATOR . 'store'; return Misuzu::PATH_STORE;
} }
public function getPath(): string { public function getPath(): string {

View file

@ -1,13 +1,13 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
use Index\Db\Migration\FsDbMigrationRepo;
require_once __DIR__ . '/../misuzu.php'; require_once __DIR__ . '/../misuzu.php';
try { $lockPath = $msz->dbCtx->getMigrateLockPath();
touch(MSZ_ROOT . '/.migrating'); if(is_file($lockPath))
chmod(MSZ_ROOT . '/.migrating', 0777); die('A migration script is already running.' . PHP_EOL);
touch($lockPath);
try {
echo 'Creating migration manager...' . PHP_EOL; echo 'Creating migration manager...' . PHP_EOL;
$manager = $msz->dbCtx->createMigrationManager(); $manager = $msz->dbCtx->createMigrationManager();
@ -29,6 +29,8 @@ try {
} }
echo PHP_EOL; echo PHP_EOL;
} catch(Exception $ex) {
var_dump($ex);
} finally { } finally {
unlink(MSZ_ROOT . '/.migrating'); unlink($lockPath);
} }

12
tools/migrate-override-toggle Executable file
View file

@ -0,0 +1,12 @@
#!/usr/bin/env php
<?php
require_once __DIR__ . '/../misuzu.php';
$lockPath = $msz->dbCtx->getMigrateLockPath();
if(is_file($lockPath)) {
printf('Removing migration lock...%s', PHP_EOL);
unlink($lockPath);
} else {
printf('Setting migration lock...%s', PHP_EOL);
touch($lockPath);
}