forked from fa/breadcrumb-the-shire
baseline
This commit is contained in:
103
lib/Support/Flash.php
Normal file
103
lib/Support/Flash.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
use MintyPHP\Session;
|
||||
|
||||
class Flash
|
||||
{
|
||||
private const SESSION_KEY = 'flash_messages';
|
||||
private const KEEP_KEY = 'flash_keep';
|
||||
|
||||
private static function ensureSession()
|
||||
{
|
||||
if (session_status() !== PHP_SESSION_ACTIVE) {
|
||||
Session::start();
|
||||
}
|
||||
if (!isset($_SESSION[self::SESSION_KEY])) {
|
||||
$_SESSION[self::SESSION_KEY] = [];
|
||||
}
|
||||
}
|
||||
|
||||
public static function add(string $type, string $message, ?string $scope = null, ?string $key = null): string
|
||||
{
|
||||
self::ensureSession();
|
||||
if ($key !== null) {
|
||||
$_SESSION[self::SESSION_KEY] = array_values(array_filter(
|
||||
$_SESSION[self::SESSION_KEY],
|
||||
function ($existing) use ($key, $scope) {
|
||||
$sameKey = ($existing['key'] ?? null) === $key;
|
||||
$sameScope = ($existing['scope'] ?? null) === $scope;
|
||||
return !($sameKey && $sameScope);
|
||||
}
|
||||
));
|
||||
}
|
||||
$id = bin2hex(random_bytes(8));
|
||||
$_SESSION[self::SESSION_KEY][] = [
|
||||
'id' => $id,
|
||||
'type' => $type,
|
||||
'message' => $message,
|
||||
'scope' => $scope,
|
||||
'key' => $key,
|
||||
];
|
||||
return $id;
|
||||
}
|
||||
|
||||
public static function success(string $message, ?string $scope = null, ?string $key = null): string
|
||||
{
|
||||
return self::add('success', $message, $scope, $key);
|
||||
}
|
||||
|
||||
public static function error(string $message, ?string $scope = null, ?string $key = null): string
|
||||
{
|
||||
return self::add('error', $message, $scope, $key);
|
||||
}
|
||||
|
||||
public static function info(string $message, ?string $scope = null, ?string $key = null): string
|
||||
{
|
||||
return self::add('info', $message, $scope, $key);
|
||||
}
|
||||
|
||||
public static function peek(?string $scope = null): array
|
||||
{
|
||||
self::ensureSession();
|
||||
$messages = $_SESSION[self::SESSION_KEY] ?? [];
|
||||
if ($scope === null) {
|
||||
return $messages;
|
||||
}
|
||||
|
||||
return array_values(array_filter($messages, function ($message) use ($scope) {
|
||||
$messageScope = $message['scope'] ?? null;
|
||||
return $messageScope === null || $messageScope === $scope;
|
||||
}));
|
||||
}
|
||||
|
||||
public static function has(): bool
|
||||
{
|
||||
self::ensureSession();
|
||||
return !empty($_SESSION[self::SESSION_KEY]);
|
||||
}
|
||||
|
||||
public static function dismiss(string $id): void
|
||||
{
|
||||
self::ensureSession();
|
||||
$messages = $_SESSION[self::SESSION_KEY] ?? [];
|
||||
$messages = array_values(array_filter($messages, function ($message) use ($id) {
|
||||
return ($message['id'] ?? '') !== $id;
|
||||
}));
|
||||
|
||||
if ($messages) {
|
||||
$_SESSION[self::SESSION_KEY] = $messages;
|
||||
} else {
|
||||
unset($_SESSION[self::SESSION_KEY]);
|
||||
}
|
||||
}
|
||||
|
||||
public static function keep(int $times = 1)
|
||||
{
|
||||
self::ensureSession();
|
||||
$times = max(1, $times);
|
||||
$current = (int) ($_SESSION[self::KEEP_KEY] ?? 0);
|
||||
$_SESSION[self::KEEP_KEY] = max($current, $times);
|
||||
}
|
||||
}
|
||||
92
lib/Support/Guard.php
Normal file
92
lib/Support/Guard.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
use MintyPHP\Router;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\TenantService;
|
||||
use MintyPHP\Service\AuthService;
|
||||
use MintyPHP\Http\Request;
|
||||
|
||||
class Guard
|
||||
{
|
||||
private const TENANT_REFRESH_INTERVAL = 60;
|
||||
|
||||
public static function requireLogin(string $redirect = 'login'): void
|
||||
{
|
||||
if (!isset($_SESSION['user'])) {
|
||||
Flash::error('Login required', 'login', 'login_required');
|
||||
Router::redirect($redirect);
|
||||
}
|
||||
self::refreshTenantContext();
|
||||
if (!empty($_SESSION['no_active_tenant'])) {
|
||||
AuthService::logout();
|
||||
Flash::error('No active tenant assigned', 'login', 'no_active_tenant');
|
||||
Router::redirect($redirect);
|
||||
}
|
||||
}
|
||||
|
||||
private static function validateCurrentTenant(): void
|
||||
{
|
||||
$currentTenant = $_SESSION['current_tenant'] ?? null;
|
||||
if (!$currentTenant || empty($currentTenant['id'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenantId = (int) $currentTenant['id'];
|
||||
$tenant = TenantService::findById($tenantId);
|
||||
if ($tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Current tenant was deleted, refresh session data
|
||||
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
||||
if ($userId > 0) {
|
||||
AuthService::loadTenantDataIntoSession($userId);
|
||||
} else {
|
||||
unset($_SESSION['current_tenant']);
|
||||
}
|
||||
}
|
||||
|
||||
private static function refreshTenantContext(): void
|
||||
{
|
||||
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
||||
if ($userId <= 0) {
|
||||
return;
|
||||
}
|
||||
$last = (int) ($_SESSION['tenant_context_refreshed_at'] ?? 0);
|
||||
$now = time();
|
||||
if ($last > 0 && ($now - $last) < self::TENANT_REFRESH_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
AuthService::loadTenantDataIntoSession($userId);
|
||||
$_SESSION['tenant_context_refreshed_at'] = $now;
|
||||
}
|
||||
|
||||
public static function requirePermission(string $permissionKey, string $redirect = 'admin'): void
|
||||
{
|
||||
self::requireLogin();
|
||||
self::validateCurrentTenant();
|
||||
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
||||
if (!$userId || !PermissionService::userHas($userId, $permissionKey)) {
|
||||
Flash::error('Permission denied', $redirect, 'permission_denied');
|
||||
Router::redirect($redirect);
|
||||
}
|
||||
}
|
||||
|
||||
public static function requirePermissionOrForbidden(string $permissionKey): void
|
||||
{
|
||||
self::requireLogin();
|
||||
self::validateCurrentTenant();
|
||||
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
||||
if (!$userId || !PermissionService::userHas($userId, $permissionKey)) {
|
||||
if (Request::wantsJson()) {
|
||||
http_response_code(403);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode(['error' => 'forbidden']);
|
||||
exit;
|
||||
}
|
||||
Router::redirect('error/forbidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
13
lib/Support/Hello.php
Normal file
13
lib/Support/Hello.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
class Hello
|
||||
{
|
||||
public static $name = 'MintyPHP';
|
||||
|
||||
public static function getGreeting(): string
|
||||
{
|
||||
return 'Hello ' . static::$name . '!';
|
||||
}
|
||||
}
|
||||
230
lib/Support/SearchConfig.php
Normal file
230
lib/Support/SearchConfig.php
Normal file
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\UserAvatarService;
|
||||
|
||||
class SearchConfig
|
||||
{
|
||||
public static function tenantScopeFilters(): array
|
||||
{
|
||||
return [
|
||||
'users' => 'and exists (select 1 from user_tenants ut where ut.user_id = users.id and ut.tenant_id in (???))',
|
||||
'address-book' => 'and exists (select 1 from user_tenants ut where ut.user_id = users.id and ut.tenant_id in (???))',
|
||||
'tenants' => 'and id in (???)',
|
||||
'departments' => 'and exists (select 1 from tenant_departments td where td.department_id = departments.id and td.tenant_id in (???))',
|
||||
];
|
||||
}
|
||||
|
||||
public static function resources(string $query, string $locale): array
|
||||
{
|
||||
$like = '%' . $query . '%';
|
||||
|
||||
return [
|
||||
[
|
||||
'key' => 'address-book',
|
||||
'label' => t('Address book'),
|
||||
'permission' => PermissionService::ADDRESS_BOOK_VIEW,
|
||||
'countSql' => 'select count(*) from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}}',
|
||||
'countParams' => [$like, $like, $like],
|
||||
'previewSql' => 'select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name limit ?',
|
||||
'previewParams' => [$like, $like, $like],
|
||||
'resultSql' => 'select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name',
|
||||
'resultParams' => [$like, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'users',
|
||||
'label' => t('Users'),
|
||||
'permission' => PermissionService::USERS_VIEW,
|
||||
'countSql' => 'select count(*) from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}}',
|
||||
'countParams' => [$like, $like, $like],
|
||||
'previewSql' => 'select uuid, first_name, last_name, email from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name limit ?',
|
||||
'previewParams' => [$like, $like, $like],
|
||||
'resultSql' => 'select uuid, first_name, last_name, email from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name',
|
||||
'resultParams' => [$like, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'tenants',
|
||||
'label' => t('Tenants'),
|
||||
'permission' => PermissionService::TENANTS_VIEW,
|
||||
'countSql' => 'select count(*) from tenants where description like ? {{tenantFilter}}',
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from tenants where description like ? {{tenantFilter}} order by description limit ?',
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from tenants where description like ? {{tenantFilter}} order by description',
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'departments',
|
||||
'label' => t('Departments'),
|
||||
'permission' => PermissionService::DEPARTMENTS_VIEW,
|
||||
'countSql' => 'select count(*) from departments where description like ? {{tenantFilter}}',
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from departments where description like ? {{tenantFilter}} order by description limit ?',
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from departments where description like ? {{tenantFilter}} order by description',
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'roles',
|
||||
'label' => t('Roles'),
|
||||
'permission' => PermissionService::ROLES_VIEW,
|
||||
'countSql' => 'select count(*) from roles where description like ?',
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from roles where description like ? order by description limit ?',
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from roles where description like ? order by description',
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'permissions',
|
||||
'label' => t('Permissions'),
|
||||
'permission' => PermissionService::PERMISSIONS_VIEW,
|
||||
'countSql' => 'select count(*) from permissions where `key` like ? or description like ?',
|
||||
'countParams' => [$like, $like],
|
||||
'previewSql' => 'select id, description, `key` from permissions where `key` like ? or description like ? order by `key` limit ?',
|
||||
'previewParams' => [$like, $like],
|
||||
'resultSql' => 'select id, description, `key` from permissions where `key` like ? or description like ? order by `key`',
|
||||
'resultParams' => [$like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'pages',
|
||||
'label' => t('Pages'),
|
||||
'permission' => '',
|
||||
'countSql' => 'select count(*) from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ?',
|
||||
'countParams' => [$locale, $like, $like],
|
||||
'previewSql' => 'select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ? order by p.slug limit ?',
|
||||
'previewParams' => [$locale, $like, $like],
|
||||
'resultSql' => 'select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ? order by p.slug',
|
||||
'resultParams' => [$locale, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'settings',
|
||||
'label' => t('Settings'),
|
||||
'permission' => PermissionService::SETTINGS_VIEW,
|
||||
'countSql' => 'select count(*) from settings where `key` like ? or value like ?',
|
||||
'countParams' => [$like, $like],
|
||||
'previewSql' => null,
|
||||
'previewParams' => [],
|
||||
'resultSql' => 'select `key`, value from settings where `key` like ? or value like ? order by `key`',
|
||||
'resultParams' => [$like, $like],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function iconForKey(string $key): string
|
||||
{
|
||||
return match ($key) {
|
||||
'address-book' => 'bi-people',
|
||||
'users' => 'bi-person-badge',
|
||||
'tenants' => 'bi-buildings',
|
||||
'departments' => 'bi-diagram-3',
|
||||
'roles' => 'bi-people',
|
||||
'permissions' => 'bi-shield-lock',
|
||||
'pages' => 'bi-file-text',
|
||||
'settings' => 'bi-gear',
|
||||
default => 'bi-search',
|
||||
};
|
||||
}
|
||||
|
||||
public static function listUrl(string $key, string $query): string
|
||||
{
|
||||
$encoded = urlencode($query);
|
||||
|
||||
return match ($key) {
|
||||
'address-book' => lurl('address-book') . '?search=' . $encoded,
|
||||
'users' => lurl('admin/users') . '?search=' . $encoded,
|
||||
'tenants' => lurl('admin/tenants') . '?search=' . $encoded,
|
||||
'departments' => lurl('admin/departments') . '?search=' . $encoded,
|
||||
'roles' => lurl('admin/roles') . '?search=' . $encoded,
|
||||
'permissions' => lurl('admin/permissions') . '?search=' . $encoded,
|
||||
'pages' => lurl(''),
|
||||
'settings' => lurl('admin/settings'),
|
||||
default => lurl(''),
|
||||
};
|
||||
}
|
||||
|
||||
public static function mapPreviewItem(string $key, array $data, string $query): ?array
|
||||
{
|
||||
if ($key === 'users') {
|
||||
$label = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
|
||||
$email = trim((string) ($data['email'] ?? ''));
|
||||
if ($email !== '') {
|
||||
$label = $label === '' ? $email : ($label . ' — ' . $email);
|
||||
}
|
||||
$url = lurl('admin/users/edit/' . ($data['uuid'] ?? '')) . '?search=' . urlencode($query);
|
||||
} elseif ($key === 'address-book') {
|
||||
$label = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
|
||||
$email = trim((string) ($data['email'] ?? ''));
|
||||
if ($email !== '') {
|
||||
$label = $label === '' ? $email : ($label . ' — ' . $email);
|
||||
}
|
||||
$url = lurl('address-book/view/' . ($data['uuid'] ?? '')) . '?search=' . urlencode($query);
|
||||
} elseif ($key === 'permissions') {
|
||||
$label = (string) ($data['description'] ?? '');
|
||||
$url = lurl('admin/permissions/edit/' . ($data['id'] ?? '')) . '?search=' . urlencode($query);
|
||||
} elseif ($key === 'pages') {
|
||||
$label = (string) ($data['slug'] ?? '');
|
||||
$url = lurl('page/' . $label) . '?search=' . urlencode($query);
|
||||
} else {
|
||||
$label = (string) ($data['description'] ?? '');
|
||||
$url = lurl('admin/' . $key . '/edit/' . ($data['uuid'] ?? '')) . '?search=' . urlencode($query);
|
||||
}
|
||||
|
||||
if ($label === '' || $url === '') {
|
||||
return null;
|
||||
}
|
||||
return ['label' => $label, 'url' => $url];
|
||||
}
|
||||
|
||||
public static function mapResultItem(string $key, string $label, array $data): ?array
|
||||
{
|
||||
$title = '';
|
||||
$description = '';
|
||||
$url = '';
|
||||
$image = '';
|
||||
if ($key === 'users') {
|
||||
$title = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
|
||||
$description = (string) ($data['email'] ?? '');
|
||||
$url = lurl('admin/users/edit/' . ($data['uuid'] ?? ''));
|
||||
} elseif ($key === 'address-book') {
|
||||
$title = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
|
||||
$description = (string) ($data['email'] ?? '');
|
||||
$uuid = (string) ($data['uuid'] ?? '');
|
||||
$url = lurl('address-book/view/' . $uuid);
|
||||
if ($uuid !== '' && UserAvatarService::hasAvatar($uuid)) {
|
||||
$image = lurl('admin/users/avatar-file') . '?uuid=' . urlencode($uuid) . '&size=64';
|
||||
}
|
||||
} elseif ($key === 'permissions') {
|
||||
$title = (string) ($data['key'] ?? '');
|
||||
$description = (string) ($data['description'] ?? '');
|
||||
$url = lurl('admin/permissions/edit/' . ($data['id'] ?? ''));
|
||||
} elseif ($key === 'pages') {
|
||||
$title = (string) ($data['slug'] ?? '');
|
||||
$description = t('Page');
|
||||
$url = lurl('page/' . $title);
|
||||
} elseif ($key === 'settings') {
|
||||
$title = (string) ($data['key'] ?? '');
|
||||
$description = (string) ($data['value'] ?? '');
|
||||
$url = lurl('admin/settings');
|
||||
} else {
|
||||
$title = (string) ($data['description'] ?? '');
|
||||
$description = $label;
|
||||
$url = lurl('admin/' . $key . '/edit/' . ($data['uuid'] ?? ''));
|
||||
}
|
||||
|
||||
if ($title === '' || $url === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => $label,
|
||||
'title' => $title,
|
||||
'description' => $description,
|
||||
'url' => $url,
|
||||
'image' => $image,
|
||||
'icon' => self::iconForKey($key),
|
||||
];
|
||||
}
|
||||
}
|
||||
28
lib/Support/Tile.php
Normal file
28
lib/Support/Tile.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
class Tile
|
||||
{
|
||||
public static function render(array $options = []): void
|
||||
{
|
||||
$defaults = [
|
||||
'href' => '#',
|
||||
'label' => '',
|
||||
'count' => null,
|
||||
'icon' => 'bi bi-grid-1x2',
|
||||
'iconBg' => null,
|
||||
'iconColor' => null,
|
||||
'class' => '',
|
||||
];
|
||||
|
||||
$data = array_merge($defaults, $options);
|
||||
$template = dirname(__DIR__, 2) . '/templates/partials/app-tile.phtml';
|
||||
if (!is_file($template)) {
|
||||
return;
|
||||
}
|
||||
|
||||
extract($data, EXTR_SKIP);
|
||||
require $template;
|
||||
}
|
||||
}
|
||||
6
lib/Support/helpers.php
Normal file
6
lib/Support/helpers.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/helpers/app.php';
|
||||
require __DIR__ . '/helpers/auth.php';
|
||||
require __DIR__ . '/helpers/i18n.php';
|
||||
require __DIR__ . '/helpers/ui.php';
|
||||
208
lib/Support/helpers/app.php
Normal file
208
lib/Support/helpers/app.php
Normal file
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
function e($string): void
|
||||
{
|
||||
echo htmlspecialchars((string) $string, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function asset(string $path): string
|
||||
{
|
||||
return \MintyPHP\Router::getBaseUrl() . ltrim($path, '/');
|
||||
}
|
||||
|
||||
function localeBase(): string
|
||||
{
|
||||
$locale = \MintyPHP\I18n::$locale ?? \MintyPHP\I18n::$defaultLocale;
|
||||
$prefix = $locale !== '' ? $locale . '/' : '';
|
||||
return \MintyPHP\Router::getBaseUrl() . $prefix;
|
||||
}
|
||||
|
||||
function lurl(string $path = ''): string
|
||||
{
|
||||
return localeBase() . ltrim($path, '/');
|
||||
}
|
||||
|
||||
function appTitle(): string
|
||||
{
|
||||
$default = defined('APP_NAME') ? APP_NAME : 'IMVS';
|
||||
$title = appSetting('app_title');
|
||||
if ($title !== null) {
|
||||
return $title;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
|
||||
function appUrl(string $path = ''): string
|
||||
{
|
||||
if ($path !== '' && preg_match('#^https?://#i', $path)) {
|
||||
return $path;
|
||||
}
|
||||
$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;
|
||||
}
|
||||
|
||||
function appLogoUrlAbsolute(int $size = 128): string
|
||||
{
|
||||
$url = appLogoUrl($size);
|
||||
return appUrl($url);
|
||||
}
|
||||
|
||||
function appSetting(string $key): ?string
|
||||
{
|
||||
$cacheFile = dirname(__DIR__, 3) . '/config/settings.php';
|
||||
if (!is_file($cacheFile)) {
|
||||
return null;
|
||||
}
|
||||
$settings = include $cacheFile;
|
||||
if (!is_array($settings)) {
|
||||
return null;
|
||||
}
|
||||
$value = $settings[$key] ?? null;
|
||||
$value = $value !== null ? trim((string) $value) : '';
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function appDefaultTheme(): string
|
||||
{
|
||||
$setting = appSetting('app_theme');
|
||||
if (in_array($setting, ['light', 'dark'], true)) {
|
||||
return $setting;
|
||||
}
|
||||
$envTheme = getenv('APP_THEME') ?: 'light';
|
||||
$envTheme = strtolower(trim((string) $envTheme));
|
||||
return in_array($envTheme, ['light', 'dark'], true) ? $envTheme : 'light';
|
||||
}
|
||||
|
||||
function allowUserTheme(): bool
|
||||
{
|
||||
$value = appSetting('app_theme_user');
|
||||
if ($value === null || $value === '') {
|
||||
return true;
|
||||
}
|
||||
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
function appPrimaryColor(): ?string
|
||||
{
|
||||
$tenantColor = $_SESSION['current_tenant']['primary_color'] ?? null;
|
||||
if ($tenantColor !== null) {
|
||||
$tenantColor = strtolower(trim((string) $tenantColor));
|
||||
if (preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $tenantColor)) {
|
||||
return $tenantColor;
|
||||
}
|
||||
}
|
||||
|
||||
$value = appSetting('app_primary_color');
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
$value = strtolower(trim($value));
|
||||
if (!preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
|
||||
return null;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function appPrimaryCssVars(): string
|
||||
{
|
||||
$hex = appPrimaryColor();
|
||||
if ($hex === null) {
|
||||
return '';
|
||||
}
|
||||
$hex = ltrim($hex, '#');
|
||||
if (strlen($hex) === 3) {
|
||||
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
|
||||
}
|
||||
$r = hexdec(substr($hex, 0, 2)) / 255;
|
||||
$g = hexdec(substr($hex, 2, 2)) / 255;
|
||||
$b = hexdec(substr($hex, 4, 2)) / 255;
|
||||
|
||||
$max = max($r, $g, $b);
|
||||
$min = min($r, $g, $b);
|
||||
$delta = $max - $min;
|
||||
|
||||
$h = 0.0;
|
||||
if ($delta !== 0.0) {
|
||||
if ($max === $r) {
|
||||
$h = 60 * fmod((($g - $b) / $delta), 6);
|
||||
} elseif ($max === $g) {
|
||||
$h = 60 * ((($b - $r) / $delta) + 2);
|
||||
} else {
|
||||
$h = 60 * ((($r - $g) / $delta) + 4);
|
||||
}
|
||||
}
|
||||
if ($h < 0) {
|
||||
$h += 360;
|
||||
}
|
||||
|
||||
$l = ($max + $min) / 2;
|
||||
$s = $delta === 0.0 ? 0.0 : $delta / (1 - abs(2 * $l - 1));
|
||||
|
||||
$h = round($h, 2);
|
||||
$s = round($s * 100, 2) . '%';
|
||||
$l = round($l * 100, 2) . '%';
|
||||
|
||||
return "--app-primary-h-base: {$h}; --app-primary-s-base: {$s}; --app-primary-l-base: {$l}; --app-primary-h-light: {$h}; --app-primary-s-light: {$s}; --app-primary-l-light: {$l};";
|
||||
}
|
||||
|
||||
function appLogoUrl(?int $size = null): string
|
||||
{
|
||||
if (class_exists('MintyPHP\\Service\\BrandingLogoService') && \MintyPHP\Service\BrandingLogoService::hasLogo()) {
|
||||
$query = $size ? '?size=' . (int) $size : '';
|
||||
return lurl('branding/logo' . $query);
|
||||
}
|
||||
return asset('brand/logo.svg');
|
||||
}
|
||||
|
||||
function appFaviconUrl(string $file): string
|
||||
{
|
||||
$tenantUuid = $_SESSION['current_tenant']['uuid'] ?? '';
|
||||
if ($tenantUuid !== '' && class_exists('MintyPHP\\Service\\TenantFaviconService')) {
|
||||
if (\MintyPHP\Service\TenantFaviconService::hasFavicon($tenantUuid)) {
|
||||
return asset('favicon/tenants/' . $tenantUuid . '/' . ltrim($file, '/'));
|
||||
}
|
||||
}
|
||||
return asset('favicon/' . ltrim($file, '/'));
|
||||
}
|
||||
|
||||
function d()
|
||||
{
|
||||
return call_user_func_array('MintyPHP\\Debugger::debug', func_get_args());
|
||||
}
|
||||
|
||||
function sortByDescription(array &$items): void
|
||||
{
|
||||
usort($items, static fn($a, $b) =>
|
||||
strcasecmp((string) ($a['description'] ?? ''), (string) ($b['description'] ?? ''))
|
||||
);
|
||||
}
|
||||
27
lib/Support/helpers/auth.php
Normal file
27
lib/Support/helpers/auth.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
function accountUrl(): string
|
||||
{
|
||||
$user = $_SESSION['user'] ?? [];
|
||||
$uuid = (string) ($user['uuid'] ?? '');
|
||||
return $uuid !== '' ? lurl('profile') : lurl('login');
|
||||
}
|
||||
|
||||
function can(string $permissionKey): bool
|
||||
{
|
||||
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
||||
if ($userId <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (!class_exists('MintyPHP\\Service\\PermissionService')) {
|
||||
return false;
|
||||
}
|
||||
$keys = \MintyPHP\Service\PermissionService::getCachedPermissions($userId);
|
||||
if (!$keys) {
|
||||
$keys = \MintyPHP\Service\PermissionService::getUserPermissions($userId);
|
||||
if (!$keys) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return in_array($permissionKey, $keys, true);
|
||||
}
|
||||
42
lib/Support/helpers/i18n.php
Normal file
42
lib/Support/helpers/i18n.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
function t()
|
||||
{
|
||||
$arguments = func_get_args();
|
||||
$arguments[0] = \MintyPHP\I18n::translate($arguments[0]);
|
||||
if (count($arguments) === 1) {
|
||||
return $arguments[0];
|
||||
}
|
||||
return call_user_func_array('sprintf', $arguments);
|
||||
}
|
||||
|
||||
function dt($value, ?string $format = null)
|
||||
{
|
||||
$displayTz = null;
|
||||
try {
|
||||
$displayTz = new \DateTimeZone(defined('APP_TIMEZONE') ? APP_TIMEZONE : date_default_timezone_get());
|
||||
} catch (\Exception $e) {
|
||||
$displayTz = new \DateTimeZone(date_default_timezone_get());
|
||||
}
|
||||
|
||||
if ($value instanceof \DateTimeInterface) {
|
||||
$date = (new \DateTimeImmutable('@' . $value->getTimestamp()))->setTimezone($displayTz);
|
||||
} elseif (is_string($value) && $value !== '') {
|
||||
try {
|
||||
// Treat DB timestamps as UTC and convert for display
|
||||
$date = new \DateTimeImmutable($value, new \DateTimeZone('UTC'));
|
||||
$date = $date->setTimezone($displayTz);
|
||||
} catch (\Exception $e) {
|
||||
return $value;
|
||||
}
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($format === null) {
|
||||
$locale = \MintyPHP\I18n::$locale ?? '';
|
||||
$format = (strpos((string) $locale, 'de') === 0) ? 'd.m.Y H:i' : 'Y-m-d H:i';
|
||||
}
|
||||
|
||||
return $date->format($format);
|
||||
}
|
||||
178
lib/Support/helpers/ui.php
Normal file
178
lib/Support/helpers/ui.php
Normal file
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
function gridLang(): array
|
||||
{
|
||||
return [
|
||||
'search' => [
|
||||
'placeholder' => t('Search...'),
|
||||
],
|
||||
'sort' => [
|
||||
'sortAsc' => t('Sort column ascending'),
|
||||
'sortDesc' => t('Sort column descending'),
|
||||
],
|
||||
'pagination' => [
|
||||
'previous' => t('Previous'),
|
||||
'next' => t('Next'),
|
||||
'navigate' => t('Page %d of %d'),
|
||||
'page' => t('Page %d'),
|
||||
'showing' => t('Showing'),
|
||||
'of' => t('of'),
|
||||
'to' => t('to'),
|
||||
'results' => t('results'),
|
||||
],
|
||||
'loading' => t('Loading...'),
|
||||
'noRecordsFound' => t('No records found'),
|
||||
'error' => t('An error happened while fetching the data'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a multi-select filter field with hidden input sync.
|
||||
*
|
||||
* @param string $id Base ID for the hidden input (select gets "-ui" suffix)
|
||||
* @param string $label Field label (will be translated)
|
||||
* @param string $placeholder Placeholder text (will be translated)
|
||||
* @param array $items Array of items with 'id' and 'description' keys
|
||||
* @param array $selected Array of selected item IDs
|
||||
*/
|
||||
function multiSelectFilter(
|
||||
string $id,
|
||||
string $label,
|
||||
string $placeholder,
|
||||
array $items,
|
||||
array $selected
|
||||
): void {
|
||||
?>
|
||||
<label class="app-field">
|
||||
<span><?php e(t($label)); ?></span>
|
||||
<input type="hidden" id="<?php e($id); ?>" value="<?php e(implode(',', $selected)); ?>">
|
||||
<select
|
||||
id="<?php e($id); ?>-ui"
|
||||
multiple
|
||||
data-multi-select
|
||||
data-sync-target="#<?php e($id); ?>"
|
||||
data-select-all="true"
|
||||
data-list-all="false"
|
||||
data-search="true"
|
||||
data-placeholder="<?php e(t($placeholder)); ?>"
|
||||
data-search-placeholder="<?php e(t('Search...')); ?>"
|
||||
data-select-all-label="<?php e(t('Select all')); ?>"
|
||||
data-selected-label="<?php e(t('%d selected')); ?>"
|
||||
>
|
||||
<?php foreach ($items as $item): ?>
|
||||
<?php $itemId = (string) ($item['id'] ?? ''); ?>
|
||||
<?php if ($itemId !== ''): ?>
|
||||
<option value="<?php e($itemId); ?>"<?php if (in_array($itemId, $selected, true)) { ?> selected<?php } ?>>
|
||||
<?php e($item['description'] ?? ''); ?>
|
||||
</option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a multi-select form field for data entry.
|
||||
*
|
||||
* @param string $id Element ID
|
||||
* @param string $name Form field name
|
||||
* @param string $label Field label (will be translated)
|
||||
* @param string $placeholder Placeholder text (will be translated)
|
||||
* @param array $items Array of items with 'id' and 'description' keys
|
||||
* @param array $selected Array of selected item IDs
|
||||
* @param bool $disabled Whether the field is disabled/readonly
|
||||
* @param string|array $labelKeys Key(s) to use for option label (tries in order)
|
||||
* @param string|null $formId Form ID for selects outside form element
|
||||
*/
|
||||
function multiSelectForm(
|
||||
string $id,
|
||||
string $name,
|
||||
string $label,
|
||||
string $placeholder,
|
||||
array $items,
|
||||
array $selected,
|
||||
bool $disabled = false,
|
||||
string|array $labelKeys = 'description',
|
||||
?string $formId = null
|
||||
): void {
|
||||
$labelKeyList = is_array($labelKeys) ? $labelKeys : [$labelKeys];
|
||||
?>
|
||||
<label>
|
||||
<span><?php e(t($label)); ?></span>
|
||||
</label>
|
||||
<select
|
||||
id="<?php e($id); ?>"
|
||||
name="<?php e($name); ?>"
|
||||
<?php if ($formId !== null): ?>form="<?php e($formId); ?>"<?php endif; ?>
|
||||
multiple
|
||||
data-multi-select="true"
|
||||
data-select-all="true"
|
||||
data-search="true"
|
||||
data-placeholder="<?php e(t($placeholder)); ?>"
|
||||
data-search-placeholder="<?php e(t('Search...')); ?>"
|
||||
data-select-all-label="<?php e(t('Select all')); ?>"
|
||||
<?php if ($disabled): ?>data-disabled="true" disabled<?php endif; ?>
|
||||
>
|
||||
<?php foreach ($items as $item): ?>
|
||||
<?php $itemId = (int) ($item['id'] ?? 0); ?>
|
||||
<?php if ($itemId > 0): ?>
|
||||
<?php
|
||||
$isSelected = in_array($itemId, $selected, true);
|
||||
$itemLabel = '';
|
||||
foreach ($labelKeyList as $key) {
|
||||
if (isset($item[$key]) && (string) $item[$key] !== '') {
|
||||
$itemLabel = (string) $item[$key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
?>
|
||||
<option value="<?php e((string) $itemId); ?>"<?php if ($isSelected) { ?> selected<?php } ?>>
|
||||
<?php e($itemLabel); ?>
|
||||
</option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php
|
||||
}
|
||||
|
||||
function navActive($path, bool $prefix = false): array
|
||||
{
|
||||
$current = \MintyPHP\Http\Request::path();
|
||||
$paths = is_array($path) ? $path : [$path];
|
||||
$isActive = false;
|
||||
foreach ($paths as $p) {
|
||||
$p = (string) $p;
|
||||
$match = $prefix ? strpos($current, $p) === 0 : $current === $p;
|
||||
if (!$match && ($current === '' || $current === '/')) {
|
||||
$match = $p === '' || $p === '/';
|
||||
}
|
||||
if ($match) {
|
||||
$isActive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'class' => $isActive ? 'active' : '',
|
||||
'aria' => $isActive ? 'aria-current="page"' : '',
|
||||
'isActive' => $isActive,
|
||||
];
|
||||
}
|
||||
|
||||
function navActivePublicPages(array $extraSlugs = []): array
|
||||
{
|
||||
$current = \MintyPHP\Http\Request::path();
|
||||
if ($current === '') {
|
||||
return ['class' => '', 'aria' => '', 'isActive' => false];
|
||||
}
|
||||
|
||||
$publicSlugs = array_merge(['imprint', 'privacy'], $extraSlugs);
|
||||
$isActive = strpos($current, 'page/') === 0 || in_array($current, $publicSlugs, true);
|
||||
|
||||
return [
|
||||
'class' => $isActive ? 'active' : '',
|
||||
'aria' => $isActive ? 'aria-current="page"' : '',
|
||||
'isActive' => $isActive,
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user