Files

540 lines
18 KiB
PHP
Raw Permalink Normal View History

2026-02-04 23:31:53 +01:00
<?php
/**
* HTML-escape output in templates.
*/
2026-02-04 23:31:53 +01:00
function e($string): void
{
echo htmlspecialchars((string) $string, ENT_QUOTES, 'UTF-8');
}
/**
* Parse a string setting value as boolean.
*
* Accepts common truthy values ('1', 'true', 'yes', 'on') and returns
* the given default for null, empty strings, or unrecognized values.
*/
function settingToBool(?string $value, bool $default = false): bool
{
if ($value === null || $value === '') {
return $default;
}
$normalized = strtolower(trim($value));
if (in_array($normalized, ['1', 'true', 'yes', 'on'], true)) {
return true;
}
if (in_array($normalized, ['0', 'false', 'no', 'off'], true)) {
return false;
}
return $default;
}
/**
* Resolve the profile target for the current session user.
*/
function accountUrl(): string
{
$user = $_SESSION['user'] ?? [];
$uuid = (string) ($user['uuid'] ?? '');
return $uuid !== '' ? lurl('profile') : lurl('login');
}
/**
* Build a web asset URL relative to the app base URL.
*/
2026-02-04 23:31:53 +01:00
function asset(string $path): string
{
return \MintyPHP\Router::getBaseUrl() . ltrim($path, '/');
}
/**
* Build an absolute filesystem path inside templates/.
*/
2026-02-11 19:28:12 +01:00
function templatePath(string $path): string
{
return dirname(__DIR__, 3) . '/templates/' . ltrim($path, '/');
}
2026-03-04 15:56:58 +01:00
/**
* Register the app service container for the current request.
*/
function setAppContainer(\MintyPHP\App\AppContainer $container): void
{
$GLOBALS['minty_app_container'] = $container;
\MintyPHP\Http\ApiAuth::configure(
static fn (): \MintyPHP\Service\Tenant\TenantScopeService => $container->get(\MintyPHP\Service\Tenant\TenantScopeService::class),
2026-03-04 15:56:58 +01:00
static fn (): \MintyPHP\Service\Auth\ApiTokenService => $container->get(\MintyPHP\Service\Auth\ApiTokenService::class),
static fn (): \MintyPHP\Repository\Access\UserRoleRepository => $container->get(\MintyPHP\Repository\Access\UserRoleRepository::class),
static fn (): \MintyPHP\Repository\Access\RolePermissionRepository => $container->get(\MintyPHP\Repository\Access\RolePermissionRepository::class),
static fn (): \MintyPHP\Service\User\UserTenantContextService => $container->get(\MintyPHP\Service\User\UserTenantContextService::class),
static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class)
);
\MintyPHP\Http\ApiBootstrap::configure(
static fn (): \MintyPHP\Service\Audit\ApiAuditServiceInterface => $container->get(\MintyPHP\Service\Audit\ApiAuditServiceInterface::class),
2026-03-06 00:44:52 +01:00
static fn (): \MintyPHP\Service\Settings\SettingsApiPolicyGateway => $container->get(\MintyPHP\Service\Settings\SettingsApiPolicyGateway::class),
2026-03-04 15:56:58 +01:00
static fn (): \MintyPHP\Service\Security\RateLimiterService => $container->get(\MintyPHP\Service\Security\RateLimiterService::class),
static fn (): \MintyPHP\Service\Audit\ApiSystemAuditReporterInterface => $container->get(\MintyPHP\Service\Audit\ApiSystemAuditReporterInterface::class)
2026-03-04 15:56:58 +01:00
);
\MintyPHP\Http\ApiResponse::configure(
static fn (): \MintyPHP\Service\Audit\ApiAuditServiceInterface => $container->get(\MintyPHP\Service\Audit\ApiAuditServiceInterface::class),
2026-03-04 15:56:58 +01:00
static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class),
static fn (): \MintyPHP\Service\Audit\ApiSystemAuditReporterInterface => $container->get(\MintyPHP\Service\Audit\ApiSystemAuditReporterInterface::class)
2026-03-04 15:56:58 +01:00
);
\MintyPHP\Support\Guard::configure(
static fn (): \MintyPHP\Service\Auth\AuthService => $container->get(\MintyPHP\Service\Auth\AuthService::class),
static fn (): \MintyPHP\Service\Tenant\TenantService => $container->get(\MintyPHP\Service\Tenant\TenantService::class),
static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class)
);
\MintyPHP\Support\SearchConfig::configure(
static fn (): \MintyPHP\App\Module\ModuleRegistry => $container->get(\MintyPHP\App\Module\ModuleRegistry::class),
static fn (string $class): ?object => \MintyPHP\App\Module\ModuleClassResolver::resolve($container, $class)
);
2026-03-04 15:56:58 +01:00
}
/**
* Resolve a service from the app container.
*/
function app(string $id): mixed
{
$container = $GLOBALS['minty_app_container'] ?? null;
if (!$container instanceof \MintyPHP\App\AppContainer) {
throw new \RuntimeException('App container is not initialized');
}
return $container->get($id);
}
/**
* Build an asset URL with filemtime cache-busting when available.
*/
2026-02-11 19:28:12 +01:00
function assetVersion(string $path): string
{
$path = ltrim($path, '/');
$file = dirname(__DIR__, 3) . '/web/' . $path;
$url = asset($path);
$version = @filemtime($file);
if ($version === false) {
return $url;
}
return $url . '?v=' . $version;
}
/**
* Base URL including locale segment (e.g. /de/).
*/
2026-02-04 23:31:53 +01:00
function localeBase(): string
{
$locale = \MintyPHP\I18n::$locale ?? \MintyPHP\I18n::$defaultLocale;
$prefix = $locale !== '' ? $locale . '/' : '';
return \MintyPHP\Router::getBaseUrl() . $prefix;
}
/**
* Locale-aware URL for app routes.
*/
2026-02-04 23:31:53 +01:00
function lurl(string $path = ''): string
{
return localeBase() . ltrim($path, '/');
}
feat(core): endpointUrl() helper — query-safe URLs for module routes Introduce a helper that returns the registered route TARGET for a given source path, so URLs built for endpoints that carry query parameters do not rely on MintyPHP's applyRoutes() rewrite layer — that layer compares the full request URI (including `?query`) against source paths and silently misses modules where path ≠ target. - core/Support/helpers/app.php: endpointUrl($path) consults ModuleRegistry::getRoutes(), returns lurl(target) when the path is a registered module source path, otherwise falls through to lurl($path). Safe fallback when the container or registry is unavailable. - modules/audit/pages/audit/system-audit/index(default).phtml: replace the ad-hoc target-path workaround with endpointUrl('admin/system-audit/ export'). Callers can now write the natural source path without knowing about the rewrite trap. - Apply the same helper to modules/helpdesk/.../domains/index and pages/admin/users/index for consistency — a no-op where path already equals target, but establishes the convention: every export/data endpoint URL in page configs goes through endpointUrl(). - tests/Support/Helpers/EndpointUrlTest: 5 cases covering source→target resolution, idempotence when path == target, fall-through for unregistered paths, leading-slash normalization, and graceful degradation when the registry is missing. Uses AppContainerIsolationTrait per the contract test in tests/Architecture/AppContainerIsolationContractTest. Gates: PHPUnit 1894 OK, PHPStan 0 errors, module:sync ok. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:39:36 +02:00
/**
* Locale-aware URL for an endpoint, resolved through the module route map.
*
* Same as lurl(), but if the given path is a registered module route
* source path it returns a URL pointing at the route TARGET path instead.
*
* Why this exists: MintyPHP's Router::applyRoutes() compares the full
* request URI (including `?query`) against registered source paths, so a
* browser navigation to `/admin/foo?x=1` misses the rewrite for a module
* route `admin/foo → some/other/foo` and falls back to file-based routing
* which cannot find `admin/foo`. Using the target path up-front sidesteps
* the rewrite entirely and works regardless of query string.
*
* Use endpointUrl() for URLs that will carry query params (data endpoints,
* export downloads, AJAX calls). Plain lurl() is still fine for nav links
* without a query string.
*/
function endpointUrl(string $path = ''): string
{
$path = ltrim($path, '/');
try {
$registry = app(\MintyPHP\App\Module\ModuleRegistry::class);
} catch (\Throwable) {
return lurl($path);
}
foreach ($registry->getRoutes() as $route) {
if (($route['path'] ?? '') === $path) {
$target = (string) ($route['target'] ?? '');
if ($target !== '') {
return lurl($target);
}
}
}
return lurl($path);
}
/**
* App title from settings with APP_NAME fallback.
*/
2026-02-04 23:31:53 +01:00
function appTitle(): string
{
$default = defined('APP_NAME') ? APP_NAME : 'CoreCore';
2026-02-04 23:31:53 +01:00
$title = appSetting('app_title');
if ($title !== null) {
return $title;
}
return $default;
}
/**
* Build an absolute URL using APP_URL or request host fallback.
*/
2026-02-04 23:31:53 +01:00
function appUrl(string $path = ''): string
{
if ($path !== '' && preg_match('#^https?://#i', $path)) {
return $path;
}
// Prefer configured canonical URL to keep links stable.
2026-02-04 23:31:53 +01:00
$base = getenv('APP_URL') ?: '';
$base = rtrim((string) $base, '/');
if ($base === '') {
$scheme = 'http';
$https = $_SERVER['HTTPS'] ?? '';
$forwarded = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
if ($https === 'on' || $https === '1' || $forwarded === 'https') {
$scheme = 'https';
}
$host = $_SERVER['HTTP_HOST'] ?? '';
if ($host !== '') {
$base = $scheme . '://' . $host;
}
}
if ($base === '') {
return \MintyPHP\Router::getBaseUrl() . ltrim((string) $path, '/');
}
$path = ltrim((string) $path, '/');
return $base . '/' . $path;
}
/**
* Human-readable current user name fallback: first+last -> email.
*/
2026-02-11 19:28:12 +01:00
function currentUserDisplayName(): string
{
$user = $_SESSION['user'] ?? [];
$name = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
if ($name !== '') {
return $name;
}
return trim((string) ($user['email'] ?? ''));
}
/**
* Read one cached app setting from storage/runtime/settings.php.
*/
2026-02-04 23:31:53 +01:00
function appSetting(string $key): ?string
{
2026-03-04 15:56:58 +01:00
if (!class_exists('MintyPHP\\Service\\Settings\\SettingCacheService')) {
2026-02-04 23:31:53 +01:00
return null;
}
2026-02-23 12:58:19 +01:00
2026-03-04 15:56:58 +01:00
return app(\MintyPHP\Service\Settings\SettingCacheService::class)->get($key);
2026-02-04 23:31:53 +01:00
}
/**
* Resolve default locale only if it exists in APP_LOCALES.
*/
2026-02-04 23:31:53 +01:00
function appDefaultLocale(): ?string
{
$locale = appSetting('app_locale');
if ($locale === null) {
return null;
}
$available = defined('APP_LOCALES') ? APP_LOCALES : [];
if ($available && !in_array($locale, $available, true)) {
return null;
}
return $locale;
}
/**
* Feature flag: allow users to choose their own theme.
refactor(settings): remove global appearance settings — tenant is sole source Removes the global app_theme, app_theme_user and app_primary_color settings from the admin/settings area and the underlying service/cache/API/i18n/docs layers. The tenant columns (tenants.primary_color, default_theme, allow_user_theme) become the single source of truth for appearance. Branding helpers are tenant-only and fall back to a hardcoded 'light' theme with no brand color when no tenant context is available (login, error, pre-session pages). The APP_THEME env var is removed. Scope: - UI: Appearance tab gone from /admin/settings; tenant edit form drops the global-fallback color preview. - Service: SettingsAppGateway no longer exposes setting-backed accessors for theme/user-theme/primary-color. Theme catalog utilities (listThemes, isAllowedTheme, normalizeTheme, resolveDefaultTheme) stay and are used across Tenant / Auth / User flows; resolveDefaultTheme now hardcodes 'light' with a catalog fallback (no global/env lookup). - AdminSettingsService: buildPageData, sanitization, audit snapshot, apply step and cache payload are all stripped of the three keys. Dead helper applyAppPrimaryColor + normalizePrimaryColor removed. - Cache: SettingCacheService HOT_PATH_KEYS drops the three keys. - API: /settings (GET/PUT) and /settings/public (GET) no longer expose appearance fields; OpenAPI schemas pruned accordingly. - Audit redaction list shortened. - DB: db/init/init.sql seed rows removed. No migration for existing installs — legacy rows stay inert. - i18n + docs: setting.app_theme, setting.app_theme_user, setting.app_primary_color removed from de+en locales; reference and explanation docs updated. - Tests: covering tests for the removed methods pruned; ThemeResolutionTest rewritten for tenant-only semantics. One unrelated PHP-CS-Fixer issue in UserRegistrar.php cleaned up to keep QG-006 green. Workflow: .agents/runs/SETTINGS-APPEARANCE-TENANT-ONLY/ (gitignored). Gates: QG-001..003, QG-006, QG-008 all pass (1985 tests, 28764 assertions). Reviews: code, security, acceptance all pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 22:40:15 +02:00
*
* Resolved from the current tenant; defaults to true when no tenant is in
* session or the tenant has no explicit value. Appearance is tenant-scoped
* there is no global setting fallback.
*/
2026-02-04 23:31:53 +01:00
function allowUserTheme(): bool
{
$tenantValue = $_SESSION['current_tenant']['allow_user_theme'] ?? null;
if ($tenantValue !== null && (string) $tenantValue !== '') {
return settingToBool((string) $tenantValue, true);
}
refactor(settings): remove global appearance settings — tenant is sole source Removes the global app_theme, app_theme_user and app_primary_color settings from the admin/settings area and the underlying service/cache/API/i18n/docs layers. The tenant columns (tenants.primary_color, default_theme, allow_user_theme) become the single source of truth for appearance. Branding helpers are tenant-only and fall back to a hardcoded 'light' theme with no brand color when no tenant context is available (login, error, pre-session pages). The APP_THEME env var is removed. Scope: - UI: Appearance tab gone from /admin/settings; tenant edit form drops the global-fallback color preview. - Service: SettingsAppGateway no longer exposes setting-backed accessors for theme/user-theme/primary-color. Theme catalog utilities (listThemes, isAllowedTheme, normalizeTheme, resolveDefaultTheme) stay and are used across Tenant / Auth / User flows; resolveDefaultTheme now hardcodes 'light' with a catalog fallback (no global/env lookup). - AdminSettingsService: buildPageData, sanitization, audit snapshot, apply step and cache payload are all stripped of the three keys. Dead helper applyAppPrimaryColor + normalizePrimaryColor removed. - Cache: SettingCacheService HOT_PATH_KEYS drops the three keys. - API: /settings (GET/PUT) and /settings/public (GET) no longer expose appearance fields; OpenAPI schemas pruned accordingly. - Audit redaction list shortened. - DB: db/init/init.sql seed rows removed. No migration for existing installs — legacy rows stay inert. - i18n + docs: setting.app_theme, setting.app_theme_user, setting.app_primary_color removed from de+en locales; reference and explanation docs updated. - Tests: covering tests for the removed methods pruned; ThemeResolutionTest rewritten for tenant-only semantics. One unrelated PHP-CS-Fixer issue in UserRegistrar.php cleaned up to keep QG-006 green. Workflow: .agents/runs/SETTINGS-APPEARANCE-TENANT-ONLY/ (gitignored). Gates: QG-001..003, QG-006, QG-008 all pass (1985 tests, 28764 assertions). Reviews: code, security, acceptance all pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 22:40:15 +02:00
return true;
2026-02-04 23:31:53 +01:00
}
/**
* Feature flag: allow public self-registration.
*/
2026-02-11 19:28:12 +01:00
function allowRegistration(): bool
{
return settingToBool(appSetting('app_registration'), true);
2026-02-11 19:28:12 +01:00
}
2026-03-06 00:44:52 +01:00
/**
* Feature flag: allow frontend telemetry events.
*/
function frontendTelemetryEnabled(): bool
{
return settingToBool(appSetting('frontend_telemetry_enabled'), false);
2026-03-06 00:44:52 +01:00
}
/**
* Frontend telemetry sample rate normalized to 0..1.
*/
function frontendTelemetrySampleRate(): float
{
$value = appSetting('frontend_telemetry_sample_rate');
if ($value === null || trim($value) === '') {
return 0.2;
}
$rate = is_numeric($value) ? (float) $value : NAN;
if (!is_finite($rate) || $rate < 0 || $rate > 1) {
return 0.2;
}
return $rate;
}
/**
* Allowed frontend telemetry events as canonical short keys.
*
* @return list<string>
*/
function frontendTelemetryAllowedEvents(): array
{
$allowed = ['warn_once', 'ajax_error'];
$value = appSetting('frontend_telemetry_allowed_events');
if ($value === null || trim($value) === '') {
return $allowed;
}
$items = preg_split('/[\s,]+/', strtolower(trim($value))) ?: [];
$normalized = array_values(array_unique(array_filter(
array_map(
static fn ($entry): string => trim((string) $entry),
$items
),
static fn ($entry): bool => in_array($entry, $allowed, true)
)));
if ($normalized === []) {
return $allowed;
}
sort($normalized, SORT_STRING);
return $normalized;
}
/**
* Sort array items by 'description' case-insensitively.
*/
2026-02-04 23:31:53 +01:00
function sortByDescription(array &$items): void
{
2026-03-05 11:17:42 +01:00
usort(
$items,
static fn ($a, $b) =>
2026-02-04 23:31:53 +01:00
strcasecmp((string) ($a['description'] ?? ''), (string) ($b['description'] ?? ''))
);
}
2026-03-05 08:26:51 +01:00
/**
* Decide whether any admin panel capability is available in layout auth.
*
* @param array<string, mixed> $layoutAuth
*/
function layoutHasAdminPanel(array $layoutAuth): bool
{
// Collect capability keys contributed by modules — these are non-admin
// capabilities that should not trigger the admin panel visibility.
$moduleCapabilities = [];
try {
/** @var \MintyPHP\App\Module\ModuleRegistry $registry */
$registry = app(\MintyPHP\App\Module\ModuleRegistry::class);
foreach ($registry->getUiSlots() as $contributions) {
foreach ($contributions as $contribution) {
$perm = is_array($contribution) ? trim((string) ($contribution['permission'] ?? '')) : '';
if ($perm !== '') {
$moduleCapabilities[$perm] = true;
}
}
}
} catch (\Throwable) {
// fail-open: if module registry is not available, skip module capabilities
}
2026-03-05 08:26:51 +01:00
$capabilityKeys = array_keys(\MintyPHP\Service\Access\UiCapabilityMap::LAYOUT);
foreach ($capabilityKeys as $key) {
if (isset($moduleCapabilities[$key])) {
2026-03-05 08:26:51 +01:00
continue;
}
if (!empty($layoutAuth[$key])) {
return true;
}
}
return false;
}
/**
* Reserved top-level keys in layout navigation context that modules must not override.
2026-03-05 08:26:51 +01:00
*
* @return list<string>
2026-03-05 08:26:51 +01:00
*/
function appLayoutNavReservedKeys(): array
{
return [
'hasAdminPanel',
'moduleSlots',
'currentTenant',
'availableTenants',
'tenantQueryParam',
feat(tenant): per-theme logos + file-upload + button UI polish Replace the single tenant avatar with a pair of theme-scoped brand logos. Render only the theme-matching <img> server-side and swap src on theme toggle via a JS hook — no reload, no double request, no CSS tricks. Tenant logos - TenantLogoService (ImageUploadTrait) with theme whitelist and per-theme storage storage/tenants/{uuid}/logo/{light|dark}/, SIZES 128/256/512 - Public serving endpoint auth/tenant-logo-file so login can show the logo pre-auth; matching authenticated admin preview endpoint - appTenantLogoUrl(?size, ?theme) with 4-step fallback cascade; PDF + mail always request 'light' - Admin tenant edit: avatar block replaced by "Tenant logos" details block inside the Master-data tab, two side-by-side slots via Pico .grid with the core app-file-upload partial - Policy rename ABILITY_ADMIN_TENANTS_AVATAR_VIEW -> LOGO_VIEW, action routes logo / logo-delete / logo-file with theme body/query param - API endpoint path kept (backward compat), internals on new service - CLI tenant:logo-migrate-avatars moves legacy avatar/ -> logo/light/ idempotently (--dry-run, --yes, --cleanup) - i18n "Tenant image" removed, 12 new keys synced across de/en File upload component - Full-width preview + filename/actions below (3D stack layout) - Fixed 16:9 aspect ratio with 1rem inner padding for consistent preview size across any logo aspect - Transparency checker pattern as background so black logos stay visible on dark mode and white logos on light mode - form="" + deleteFormId support so the partial works with barrier forms inside another form Buttons - width:100% dropped from button[type="submit"]; scoped back via .login-main for the auth-flow primary CTA - .outline base rule now tints background via color-mix of --app-color so secondary/primary/danger outlines all gain a subtle surface - .outline.secondary restyled Stripe-style in both themes: solid white chip with soft shadow in light, solid elevated dark chip with white text in dark; neutral border replaces role-colored border - .app-action-success/.app-action-danger outlines get color-mix bg + theme-aware outline-text tokens for stronger contrast - Filled .primary/.app-action-success/.app-action-danger get raised box-shadow (inset highlight + drop) — opt-in via class so chrome buttons stay flat - Dropped the legacy .secondary utility that was clobbering the custom-property cascade with a hardcoded muted color Theme swap - Logo img carries data-src-light + data-src-dark; theme-toggle JS swaps src when data-theme changes, keeping the topbar/login logo in sync without a page reload Quality gates: PHPUnit (2045), PHPStan L5, CS-Fixer, docs link/drift, codex skills sync — all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 20:25:53 +02:00
'tenantLogo',
'csrfKey',
'csrfToken',
];
}
/**
* Merge one module layout-provider payload into layout navigation context.
*
* Provider keys are contract-validated and must be namespaced (`module.key`).
*
* @param array<string, mixed> $layoutNav
* @param array<string, mixed> $providerData
* @return array<string, mixed>
*/
function appMergeLayoutNavProviderData(array $layoutNav, array $providerData, string $providerClass): array
2026-03-05 08:26:51 +01:00
{
$reserved = array_fill_keys(appLayoutNavReservedKeys(), true);
foreach ($providerData as $rawKey => $value) {
$key = trim((string) $rawKey);
2026-03-05 08:26:51 +01:00
if ($key === '') {
throw new \RuntimeException(
"Layout context provider '{$providerClass}' returned an empty top-level key."
);
2026-03-05 08:26:51 +01:00
}
if (isset($reserved[$key])) {
throw new \RuntimeException(
"Layout context provider '{$providerClass}' must not override reserved layout key '{$key}'."
);
2026-03-05 08:26:51 +01:00
}
if (array_key_exists($key, $layoutNav)) {
throw new \RuntimeException(
"Layout context provider '{$providerClass}' collides on existing layout key '{$key}'."
);
2026-03-05 08:26:51 +01:00
}
if (!preg_match('/^[a-z0-9]+[a-z0-9._-]*$/', $key) || !str_contains($key, '.')) {
throw new \RuntimeException(
"Layout context provider '{$providerClass}' key '{$key}' must be namespaced (e.g. '<module_id>.data')."
);
2026-03-05 08:26:51 +01:00
}
$layoutNav[$key] = $value;
2026-03-05 08:26:51 +01:00
}
return $layoutNav;
2026-03-05 08:26:51 +01:00
}
/**
* Build precomputed layout navigation context for templates.
*
* @param array<string, mixed> $layoutAuth
* @param array<string, mixed> $session
* @param array<string, mixed> $query
* @return array<string, mixed>
*/
function appBuildLayoutNavContext(array $layoutAuth, array $session, array $query): array
{
$currentTenant = is_array($session['current_tenant'] ?? null) ? $session['current_tenant'] : null;
$availableTenants = is_array($session['available_tenants'] ?? null) ? $session['available_tenants'] : [];
$tenantUuid = trim((string) ($currentTenant['uuid'] ?? ''));
$tenantName = trim((string) ($currentTenant['description'] ?? ''));
$tenantQueryParam = '';
if (count($availableTenants) > 1 && $tenantUuid !== '') {
$tenantQueryParam = '?tenant=' . urlencode($tenantUuid);
}
feat(tenant): per-theme logos + file-upload + button UI polish Replace the single tenant avatar with a pair of theme-scoped brand logos. Render only the theme-matching <img> server-side and swap src on theme toggle via a JS hook — no reload, no double request, no CSS tricks. Tenant logos - TenantLogoService (ImageUploadTrait) with theme whitelist and per-theme storage storage/tenants/{uuid}/logo/{light|dark}/, SIZES 128/256/512 - Public serving endpoint auth/tenant-logo-file so login can show the logo pre-auth; matching authenticated admin preview endpoint - appTenantLogoUrl(?size, ?theme) with 4-step fallback cascade; PDF + mail always request 'light' - Admin tenant edit: avatar block replaced by "Tenant logos" details block inside the Master-data tab, two side-by-side slots via Pico .grid with the core app-file-upload partial - Policy rename ABILITY_ADMIN_TENANTS_AVATAR_VIEW -> LOGO_VIEW, action routes logo / logo-delete / logo-file with theme body/query param - API endpoint path kept (backward compat), internals on new service - CLI tenant:logo-migrate-avatars moves legacy avatar/ -> logo/light/ idempotently (--dry-run, --yes, --cleanup) - i18n "Tenant image" removed, 12 new keys synced across de/en File upload component - Full-width preview + filename/actions below (3D stack layout) - Fixed 16:9 aspect ratio with 1rem inner padding for consistent preview size across any logo aspect - Transparency checker pattern as background so black logos stay visible on dark mode and white logos on light mode - form="" + deleteFormId support so the partial works with barrier forms inside another form Buttons - width:100% dropped from button[type="submit"]; scoped back via .login-main for the auth-flow primary CTA - .outline base rule now tints background via color-mix of --app-color so secondary/primary/danger outlines all gain a subtle surface - .outline.secondary restyled Stripe-style in both themes: solid white chip with soft shadow in light, solid elevated dark chip with white text in dark; neutral border replaces role-colored border - .app-action-success/.app-action-danger outlines get color-mix bg + theme-aware outline-text tokens for stronger contrast - Filled .primary/.app-action-success/.app-action-danger get raised box-shadow (inset highlight + drop) — opt-in via class so chrome buttons stay flat - Dropped the legacy .secondary utility that was clobbering the custom-property cascade with a hardcoded muted color Theme swap - Logo img carries data-src-light + data-src-dark; theme-toggle JS swaps src when data-theme changes, keeping the topbar/login logo in sync without a page reload Quality gates: PHPUnit (2045), PHPStan L5, CS-Fixer, docs link/drift, codex skills sync — all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 20:25:53 +02:00
$tenantHasLogoLight = false;
$tenantHasLogoDark = false;
if ($tenantUuid !== '' && class_exists(\MintyPHP\Service\Tenant\TenantLogoService::class)) {
$logoService = app(\MintyPHP\Service\Tenant\TenantLogoService::class);
$tenantHasLogoLight = $logoService->hasLogo($tenantUuid, \MintyPHP\Service\Tenant\TenantLogoService::THEME_LIGHT);
$tenantHasLogoDark = $logoService->hasLogo($tenantUuid, \MintyPHP\Service\Tenant\TenantLogoService::THEME_DARK);
2026-03-05 08:26:51 +01:00
}
$csrfKey = \MintyPHP\Session::$csrfSessionKey;
$csrfToken = (string) ($session[$csrfKey] ?? '');
// Pre-resolve module UI slot contributions for templates (templates must not call app() directly)
$moduleUiSlots = [];
try {
/** @var \MintyPHP\App\Module\ModuleRegistry $moduleReg */
$moduleReg = app(\MintyPHP\App\Module\ModuleRegistry::class);
$moduleUiSlots = $moduleReg->getUiSlots();
} catch (\Throwable) {
// fail-open
}
$layoutNav = [
2026-03-05 08:26:51 +01:00
'hasAdminPanel' => layoutHasAdminPanel($layoutAuth),
'moduleSlots' => $moduleUiSlots,
2026-03-05 08:26:51 +01:00
'currentTenant' => $currentTenant,
'availableTenants' => $availableTenants,
'tenantQueryParam' => $tenantQueryParam,
feat(tenant): per-theme logos + file-upload + button UI polish Replace the single tenant avatar with a pair of theme-scoped brand logos. Render only the theme-matching <img> server-side and swap src on theme toggle via a JS hook — no reload, no double request, no CSS tricks. Tenant logos - TenantLogoService (ImageUploadTrait) with theme whitelist and per-theme storage storage/tenants/{uuid}/logo/{light|dark}/, SIZES 128/256/512 - Public serving endpoint auth/tenant-logo-file so login can show the logo pre-auth; matching authenticated admin preview endpoint - appTenantLogoUrl(?size, ?theme) with 4-step fallback cascade; PDF + mail always request 'light' - Admin tenant edit: avatar block replaced by "Tenant logos" details block inside the Master-data tab, two side-by-side slots via Pico .grid with the core app-file-upload partial - Policy rename ABILITY_ADMIN_TENANTS_AVATAR_VIEW -> LOGO_VIEW, action routes logo / logo-delete / logo-file with theme body/query param - API endpoint path kept (backward compat), internals on new service - CLI tenant:logo-migrate-avatars moves legacy avatar/ -> logo/light/ idempotently (--dry-run, --yes, --cleanup) - i18n "Tenant image" removed, 12 new keys synced across de/en File upload component - Full-width preview + filename/actions below (3D stack layout) - Fixed 16:9 aspect ratio with 1rem inner padding for consistent preview size across any logo aspect - Transparency checker pattern as background so black logos stay visible on dark mode and white logos on light mode - form="" + deleteFormId support so the partial works with barrier forms inside another form Buttons - width:100% dropped from button[type="submit"]; scoped back via .login-main for the auth-flow primary CTA - .outline base rule now tints background via color-mix of --app-color so secondary/primary/danger outlines all gain a subtle surface - .outline.secondary restyled Stripe-style in both themes: solid white chip with soft shadow in light, solid elevated dark chip with white text in dark; neutral border replaces role-colored border - .app-action-success/.app-action-danger outlines get color-mix bg + theme-aware outline-text tokens for stronger contrast - Filled .primary/.app-action-success/.app-action-danger get raised box-shadow (inset highlight + drop) — opt-in via class so chrome buttons stay flat - Dropped the legacy .secondary utility that was clobbering the custom-property cascade with a hardcoded muted color Theme swap - Logo img carries data-src-light + data-src-dark; theme-toggle JS swaps src when data-theme changes, keeping the topbar/login logo in sync without a page reload Quality gates: PHPUnit (2045), PHPStan L5, CS-Fixer, docs link/drift, codex skills sync — all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 20:25:53 +02:00
'tenantLogo' => [
2026-03-05 08:26:51 +01:00
'uuid' => $tenantUuid,
'name' => $tenantName,
feat(tenant): per-theme logos + file-upload + button UI polish Replace the single tenant avatar with a pair of theme-scoped brand logos. Render only the theme-matching <img> server-side and swap src on theme toggle via a JS hook — no reload, no double request, no CSS tricks. Tenant logos - TenantLogoService (ImageUploadTrait) with theme whitelist and per-theme storage storage/tenants/{uuid}/logo/{light|dark}/, SIZES 128/256/512 - Public serving endpoint auth/tenant-logo-file so login can show the logo pre-auth; matching authenticated admin preview endpoint - appTenantLogoUrl(?size, ?theme) with 4-step fallback cascade; PDF + mail always request 'light' - Admin tenant edit: avatar block replaced by "Tenant logos" details block inside the Master-data tab, two side-by-side slots via Pico .grid with the core app-file-upload partial - Policy rename ABILITY_ADMIN_TENANTS_AVATAR_VIEW -> LOGO_VIEW, action routes logo / logo-delete / logo-file with theme body/query param - API endpoint path kept (backward compat), internals on new service - CLI tenant:logo-migrate-avatars moves legacy avatar/ -> logo/light/ idempotently (--dry-run, --yes, --cleanup) - i18n "Tenant image" removed, 12 new keys synced across de/en File upload component - Full-width preview + filename/actions below (3D stack layout) - Fixed 16:9 aspect ratio with 1rem inner padding for consistent preview size across any logo aspect - Transparency checker pattern as background so black logos stay visible on dark mode and white logos on light mode - form="" + deleteFormId support so the partial works with barrier forms inside another form Buttons - width:100% dropped from button[type="submit"]; scoped back via .login-main for the auth-flow primary CTA - .outline base rule now tints background via color-mix of --app-color so secondary/primary/danger outlines all gain a subtle surface - .outline.secondary restyled Stripe-style in both themes: solid white chip with soft shadow in light, solid elevated dark chip with white text in dark; neutral border replaces role-colored border - .app-action-success/.app-action-danger outlines get color-mix bg + theme-aware outline-text tokens for stronger contrast - Filled .primary/.app-action-success/.app-action-danger get raised box-shadow (inset highlight + drop) — opt-in via class so chrome buttons stay flat - Dropped the legacy .secondary utility that was clobbering the custom-property cascade with a hardcoded muted color Theme swap - Logo img carries data-src-light + data-src-dark; theme-toggle JS swaps src when data-theme changes, keeping the topbar/login logo in sync without a page reload Quality gates: PHPUnit (2045), PHPStan L5, CS-Fixer, docs link/drift, codex skills sync — all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 20:25:53 +02:00
'hasLogoLight' => $tenantHasLogoLight,
'hasLogoDark' => $tenantHasLogoDark,
2026-03-05 08:26:51 +01:00
],
'csrfKey' => $csrfKey,
'csrfToken' => $csrfToken,
];
// ── Module layout context providers ──────────────────────────────
// Modules can contribute additional layout data via LayoutContextProvider.
// Each provider returns a key-value array that is merged into $layoutNav.
try {
/** @var \MintyPHP\App\Module\ModuleRegistry $moduleRegistry */
$moduleRegistry = app(\MintyPHP\App\Module\ModuleRegistry::class);
} catch (\Throwable) {
// fail-open: if module registry is not available, skip module providers
return $layoutNav;
}
$container = $GLOBALS['minty_app_container'] ?? null;
if (!$container instanceof \MintyPHP\App\AppContainer) {
return $layoutNav;
}
foreach ($moduleRegistry->getLayoutContextProviders() as $providerClass) {
$provider = \MintyPHP\App\Module\ModuleClassResolver::resolve($container, $providerClass);
if ($provider instanceof \MintyPHP\App\Module\Contracts\LayoutContextProvider) {
$providerData = $provider->provide($session, $container);
$layoutNav = appMergeLayoutNavProviderData($layoutNav, $providerData, $providerClass);
}
}
return $layoutNav;
2026-03-05 08:26:51 +01:00
}