v1.0.0.8
Publisium
- <?php
-
- declare(strict_types=1);
-
- require_once __DIR__ . '/database.php';
- require_once __DIR__ . '/icons.php';
- require_once __DIR__ . '/social-icons.php';
- require_once __DIR__ . '/article-scheduler.php';
- require_once __DIR__ . '/languages.php';
- require_once __DIR__ . '/clean-urls.php';
-
- final class SiteFront
- {
- private static ?array $settings = null;
-
- public const AD_PLACEMENTS = [
- 'header' => 'Header, below the menu on every page',
- 'homepage-top' => 'Home page, near the top',
- 'homepage-bottom' => 'Home page, at the bottom',
- 'in-feed' => 'Between articles in lists (home page and categories)',
- 'category-top' => 'Category pages, above the articles',
- 'search-top' => 'Search page, above the results',
- 'article-top' => 'Articles, below the title',
- 'in-article' => 'Inside articles, between the cover image and the text',
- 'article-middle' => 'Articles, in the middle of the text',
- 'article-bottom' => 'Below the article text',
- 'page-top' => 'Pages, below the title',
- 'page-bottom' => 'Pages, below the content',
- 'footer' => 'Just above the footer',
- 'sticky-bottom' => 'Bar stuck to the bottom of the screen (visitors can close it)',
- ];
-
- public const AD_AUDIENCES = [
- 'all' => 'Everyone',
- 'guests' => 'Only visitors who aren’t logged in',
- 'members' => 'Only logged-in readers',
- 'paid' => 'Only paying subscribers',
- 'unpaid' => 'Only people who don’t pay (including visitors who aren’t logged in)',
- ];
-
- public const AD_CONSENTS = [
- 'none' => 'Show it right away, no cookie consent needed',
- 'marketing' => 'Only after the visitor allows marketing (usual for ad networks)',
- 'analytics' => 'Only after the visitor allows analytics',
- 'both' => 'Only after the visitor allows both analytics and marketing',
- ];
-
- public const ADBLOCK_MODES = [
- 'once' => 'User-Friendly: shows once, then never again in that browser',
- 'session' => 'Session: shows once per visit (until the tab is closed)',
- 'extended' => 'Extended: shows on every page, visitors can close it',
- 'lock' => 'ViewLocker: can’t be closed and the page can’t be scrolled',
- 'lock_max' => 'ViewLocker Max: can’t be closed and everything except the message is blurred out',
- ];
-
- public static function adblockMode(): string
- {
- $mode = (string) (self::settings()['adblock_notice_mode'] ?? 'session');
- $mode = ['gentle' => 'session', 'wall' => 'lock_max'][$mode] ?? $mode;
-
- return array_key_exists($mode, self::ADBLOCK_MODES) ? $mode : 'session';
- }
-
- private static array $adContext = ['type' => '', 'id' => 0];
-
- // Tells the ad system what is being shown, so ads can skip excluded articles and pages.
- public static function setAdContext(string $type, int $id = 0): void
- {
- self::$adContext = ['type' => $type, 'id' => $id];
- }
-
- public static function adExclusions(array $ad): array
- {
- $decoded = json_decode((string) ($ad['excluded_items'] ?? ''), true);
- $decoded = is_array($decoded) ? $decoded : [];
-
- return [
- 'home' => !empty($decoded['home']),
- 'articles' => array_values(array_unique(array_filter(array_map('intval', is_array($decoded['articles'] ?? null) ? $decoded['articles'] : [])))),
- 'pages' => array_values(array_unique(array_filter(array_map('intval', is_array($decoded['pages'] ?? null) ? $decoded['pages'] : [])))),
- ];
- }
-
- // A date in the site's language (for example "28 września 2026"), optionally with the time
- // in the 24-hour or 12-hour format picked in Layout. Without the intl extension it falls back to English.
- public static function formatDate(string|int $when, bool $withTime = false): string
- {
- $timestamp = is_int($when) ? $when : strtotime($when);
- if ($timestamp === false) {
- return '';
- }
-
- $date = false;
- if (class_exists('IntlDateFormatter')) {
- $formatter = new IntlDateFormatter(str_replace('-', '_', Languages::htmlLang()), IntlDateFormatter::LONG, IntlDateFormatter::NONE, date_default_timezone_get());
- $date = $formatter->format($timestamp);
- }
- if (!is_string($date) || $date === '') {
- $date = date('F j, Y', $timestamp);
- }
-
- if (!$withTime) {
- return $date;
- }
-
- return $date . ', ' . date(self::settings()['article_time_format'] === '12' ? 'g:i A' : 'H:i', $timestamp);
- }
-
- // The payment link, with the reader's email filled in on Polar and Stripe payment links.
- // The webhook links a payment to an account by email, so this keeps them matching.
- public static function subscriptionCheckoutUrl(?string $email = null): string
- {
- $url = trim((string) self::settings()['subscription_checkout_url']);
- $email = strtolower(trim((string) $email));
- if ($url === '' || $email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
- return $url;
- }
-
- $host = strtolower((string) parse_url($url, PHP_URL_HOST));
- $param = match (true) {
- $host === 'polar.sh' || str_ends_with($host, '.polar.sh') => 'customer_email',
- $host === 'buy.stripe.com' => 'prefilled_email',
- default => '',
- };
- if ($param === '' || preg_match('/[?&]' . $param . '=/', $url) === 1) {
- return $url;
- }
-
- [$base, $fragment] = array_pad(explode('#', $url, 2), 2, null);
-
- return $base . (str_contains($base, '?') ? '&' : '?') . $param . '=' . rawurlencode($email) . ($fragment !== null ? '#' . $fragment : '');
- }
-
- public static function renderAds(string $placement): string
- {
- $html = '';
- foreach (self::activeAds($placement) as $ad) {
- $html .= self::renderAd($ad);
- }
-
- return $html;
- }
-
- public static function articleUrl(string $slug, ?string $lang = null): string
- {
- $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
- $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
- if ((self::settings()['clean_article_urls'] ?? '0') === '1') {
- return $basePath . $prefix . '/' . rawurlencode(CleanUrls::slugFor('article', $slug) ?? $slug);
- }
-
- return $basePath . $prefix . '/article.php?slug=' . rawurlencode($slug);
- }
-
- // Link to the home page: "/" when the short home address is on, otherwise "/index.php".
- public static function homeUrl(?string $lang = null): string
- {
- $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
- $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
-
- return $basePath . $prefix . (self::cleanHomeUrl() ? '/' : '/index.php');
- }
-
- public static function cleanHomeUrl(): bool
- {
- return (self::settings()['clean_home_url'] ?? '0') === '1';
- }
-
- public static function pageUrl(string $slug, ?string $lang = null): string
- {
- return self::entityUrl('page', 'page.php', $slug, $lang);
- }
-
- public static function authorUrl(string $slug, ?string $lang = null): string
- {
- return self::entityUrl('author', 'artist.php', $slug, $lang);
- }
-
- private static function entityUrl(string $type, string $script, string $slug, ?string $lang): string
- {
- $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
- $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
- $cleanSlug = CleanUrls::slugFor($type, $slug);
- if ($cleanSlug !== null) {
- return $basePath . $prefix . '/' . rawurlencode($cleanSlug);
- }
-
- return $basePath . $prefix . '/' . $script . '?slug=' . rawurlencode($slug);
- }
-
- public static function resetSettings(): void
- {
- self::$settings = null;
- }
-
- public static function settings(): array
- {
- if (self::$settings !== null) {
- return self::$settings;
- }
-
- $defaults = [
- 'site_name' => Config::get('APP_NAME', 'Publisium'),
- 'site_description' => '',
- 'seo_title' => '',
- 'seo_description' => '',
- 'seo_keywords' => '',
- 'seo_author' => '',
- 'seo_reply_to' => '',
- 'seo_application_name' => '',
- 'seo_robots_index' => '1',
- 'seo_robots_follow' => '1',
- 'seo_og_article_image_enabled' => '0',
- 'seo_article_schema_enabled' => '0',
- 'seo_social_tags_enabled' => '0',
- 'seo_twitter_handle' => '',
- 'llms_txt_enabled' => '0',
- 'site_logo_url' => '',
- 'site_show_name_with_logo' => '0',
- 'site_short_name' => '',
- 'site_short_name_enabled' => '0',
- 'registration_enabled' => '1',
- 'login_enabled' => '1',
- 'custom_css' => '',
- 'custom_js' => '',
- 'custom_head_html' => '',
- 'custom_head_html_index' => '0',
- 'custom_head_html_article' => '0',
- 'custom_head_html_category' => '0',
- 'custom_head_html_pages' => '0',
- 'custom_body_html' => '',
- 'custom_body_html_index' => '0',
- 'custom_body_html_article' => '0',
- 'custom_body_html_category' => '0',
- 'custom_body_html_pages' => '0',
- 'menu_position' => 'top',
- 'banner_enabled' => '1',
- 'featured_banner_enabled' => '0',
- 'featured_banner_mode' => 'static',
- 'featured_banner_hide_duplicates' => '0',
- 'featured_banner_article_1' => '0',
- 'featured_banner_article_2' => '0',
- 'featured_banner_article_3' => '0',
- 'featured_banner_article_4' => '0',
- 'featured_banner_article_5' => '0',
- 'featured_banner_auto_window_value' => '24',
- 'featured_banner_auto_window_unit' => 'hours',
- 'featured_banner_auto_category_mode' => 'mixed',
- 'related_articles_enabled' => '1',
- 'article_reading_time_enabled' => '1',
- 'article_time_enabled' => '0',
- 'article_time_format' => '24',
- 'back_to_top_enabled' => '0',
- 'adblock_notice_enabled' => '0',
- 'adblock_notice_mode' => 'session',
- 'back_to_top_progress_enabled' => '0',
- 'toc_enabled' => '0',
- 'breadcrumbs_enabled' => '0',
- 'author_box_enabled' => '0',
- 'account_consents_enabled' => '1',
- 'author_pages_enabled' => '0',
- 'tags_enabled' => '0',
- 'activity_log_enabled' => '0',
- 'seo_preview_enabled' => '0',
- 'indexnow_enabled' => '0',
- 'indexnow_key' => '',
- 'sitemap_rss_enabled' => '1',
- 'rss_category_feeds_enabled' => '0',
- 'comments_enabled' => '0',
- 'comments_provider' => 'disqus',
- 'comments_shortname' => '',
- 'comments_server_url' => '',
- 'comments_site_id' => '',
- 'comments_repo' => '',
- 'comments_repo_id' => '',
- 'comments_category' => '',
- 'comments_category_id' => '',
- 'comments_mapping' => 'pathname',
- 'comments_custom_html' => '',
- 'comments_consent' => 'marketing',
- 'comments_load' => 'auto',
- 'comments_who' => 'users',
- 'comments_moderation' => 'all',
- 'comments_email' => 'off',
- 'consent_manager_enabled' => '0',
- 'consent_footer_icon_enabled' => '0',
- 'consent_show_analytics' => 'auto',
- 'consent_show_marketing' => 'auto',
- 'heading_font' => 'Plus Jakarta Sans',
- 'body_font' => 'PT Serif',
- 'interface_font' => 'Plus Jakarta Sans',
- 'subscription_name' => 'Full access',
- 'subscription_price_cents' => '0',
- 'subscription_interval' => 'month',
- 'subscription_currency' => 'USD',
- 'subscription_description' => '',
- 'subscription_checkout_url' => '',
- 'payment_provider' => 'stripe',
- 'payment_webhook_secret' => '',
- 'footer_columns' => '[]',
- 'footer_social_links' => '[]',
- 'article_loading_mode' => 'scroll',
- 'pagination_style' => 'numbered',
- 'articles_per_page_home' => '12',
- 'articles_per_page_category' => '12',
- 'search_enabled' => '0',
- 'search_match_title' => '1',
- 'search_match_excerpt' => '1',
- 'search_match_content' => '0',
- 'search_style' => 'icon',
- 'search_show_in_nav' => '0',
- 'search_show_in_footer' => '0',
- 'share_enabled' => '0',
- 'share_facebook' => '1',
- 'share_twitter' => '1',
- 'share_linkedin' => '1',
- 'share_whatsapp' => '1',
- 'share_telegram' => '0',
- 'share_email' => '1',
- 'share_copy_link' => '1',
- 'pwa_enabled' => '0',
- 'pwa_name' => '',
- 'pwa_short_name' => '',
- 'pwa_description' => '',
- 'pwa_icon_url' => '',
- 'pwa_theme_color' => '#ffffff',
- 'pwa_background_color' => '#ffffff',
- 'app_banner_enabled' => '0',
- 'app_android_url' => '',
- 'app_ios_url' => '',
- 'multilang_enabled' => '0',
- 'multilang_default_code' => 'en',
- 'multilang_default_name' => 'English',
- 'multilang_switcher' => '1',
- ];
-
- $rows = Database::site()->query('SELECT setting_key, setting_value FROM site_settings')->fetchAll();
- $values = [];
- foreach ($rows as $row) {
- $values[$row['setting_key']] = $row['setting_value'];
- }
-
- self::$settings = array_merge($defaults, $values);
- self::$settings = Languages::applySiteTexts(self::$settings);
- ArticleScheduler::publishDue();
-
- return self::$settings;
- }
-
- public static function navItems(): array
- {
- try {
- $rows = Database::site()->query(
- 'SELECT * FROM nav_items ORDER BY sort_order ASC, id ASC'
- )->fetchAll();
- } catch (PDOException $e) {
- return self::fallbackNavItems();
- }
-
- if (empty($rows)) {
- return self::fallbackNavItems();
- }
-
- $items = [];
- $navTitles = Languages::titles('nav', array_map('intval', array_column($rows, 'id')));
- foreach ($rows as $row) {
- if ($row['item_type'] === 'category') {
- $statement = Database::site()->prepare(
- 'SELECT id, name, slug FROM categories WHERE id = :id AND show_in_menu = 1 LIMIT 1'
- );
- $statement->execute(['id' => $row['ref_id']]);
- $category = $statement->fetch();
- if (!$category) {
- continue;
- }
- $category = Languages::categories([$category])[0];
- $items[] = [
- 'label' => $navTitles[(int) $row['id']] ?? ($row['label'] !== null && $row['label'] !== '' ? $row['label'] : $category['name']),
- 'url' => 'category.php?slug=' . urlencode($category['slug']),
- 'target' => '_self',
- 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
- ];
- continue;
- }
-
- if ($row['item_type'] === 'page') {
- $statement = Database::site()->prepare(
- "SELECT id, title, slug FROM pages WHERE id = :id AND show_in_menu = 1 AND status = 'published' LIMIT 1"
- );
- $statement->execute(['id' => $row['ref_id']]);
- $page = $statement->fetch();
- if (!$page) {
- continue;
- }
- $page = Languages::pages([$page])[0];
- $items[] = [
- 'label' => $navTitles[(int) $row['id']] ?? ($row['label'] !== null && $row['label'] !== '' ? $row['label'] : $page['title']),
- 'url' => self::pageUrl((string) $page['slug']),
- 'target' => '_self',
- 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
- ];
- continue;
- }
-
- if ($row['item_type'] === 'custom') {
- if (empty($row['label']) || empty($row['url'])) {
- continue;
- }
- $items[] = [
- 'label' => $navTitles[(int) $row['id']] ?? $row['label'],
- 'url' => $row['url'],
- 'target' => $row['target'] === '_blank' ? '_blank' : '_self',
- 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
- ];
- }
- }
-
- return $items;
- }
-
- public static function appendToCustomNav(string $itemType, int $refId): void
- {
- if ($refId <= 0 || !in_array($itemType, ['category', 'page'], true)) {
- return;
- }
-
- try {
- $db = Database::site();
- if ((int) $db->query('SELECT COUNT(*) FROM nav_items')->fetchColumn() === 0) {
- return;
- }
-
- $existing = $db->prepare('SELECT id FROM nav_items WHERE item_type = :type AND ref_id = :ref_id LIMIT 1');
- $existing->execute(['type' => $itemType, 'ref_id' => $refId]);
- if ($existing->fetch()) {
- return;
- }
-
- $next = (int) $db->query('SELECT COALESCE(MAX(sort_order), -1) + 1 FROM nav_items')->fetchColumn();
- $db->prepare('INSERT INTO nav_items (item_type, ref_id, sort_order) VALUES (:type, :ref_id, :sort_order)')
- ->execute(['type' => $itemType, 'ref_id' => $refId, 'sort_order' => $next]);
- } catch (PDOException $e) {
- error_log('Publisium: could not add ' . $itemType . ' #' . $refId . ' to the menu: ' . $e->getMessage());
- }
- }
-
- private static function navItemIconHtml(?string $iconKey, ?string $iconSvg): string
- {
- if ($iconKey === 'custom' && !empty($iconSvg)) {
- return '<span class="nav-item-icon" aria-hidden="true">' . $iconSvg . '</span>';
- }
-
- if (!empty($iconKey) && Icons::isNavIcon($iconKey)) {
- return Icons::icon($iconKey, 'icon icon-sm nav-item-icon');
- }
-
- return '';
- }
-
- private static function fallbackNavItems(): array
- {
- $items = [];
-
- $categories = Database::site()->query(
- 'SELECT id, name, slug FROM categories WHERE show_in_menu = 1 ORDER BY sort_order ASC, name ASC'
- )->fetchAll();
- $categories = Languages::categories($categories);
- foreach ($categories as $category) {
- $items[] = [
- 'label' => $category['name'],
- 'url' => 'category.php?slug=' . urlencode($category['slug']),
- 'target' => '_self',
- ];
- }
-
- try {
- $pages = Database::site()->query(
- "SELECT id, title, slug FROM pages WHERE show_in_menu = 1 AND status = 'published' ORDER BY sort_order ASC, title ASC"
- )->fetchAll();
- } catch (PDOException $e) {
- $pages = [];
- }
- $pages = Languages::pages($pages);
- foreach ($pages as $page) {
- $items[] = [
- 'label' => $page['title'],
- 'url' => self::pageUrl((string) $page['slug']),
- 'target' => '_self',
- ];
- }
-
- return $items;
- }
-
- public static function renderSearchControl(string $context): string
- {
- $settings = self::settings();
-
- if ($settings['search_enabled'] !== '1') {
- return '';
- }
-
- $placementKey = $context === 'footer' ? 'search_show_in_footer' : 'search_show_in_nav';
- if (($settings[$placementKey] ?? '0') !== '1') {
- return '';
- }
-
- $searchLabel = Language::get('nav_search', 'Search');
- $searchPlaceholder = Language::get('search_placeholder', 'Search');
- $magnifierSvg = '<svg class="icon icon-sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>';
-
- if ($settings['search_style'] === 'field') {
- return '<form action="search.php" method="get" class="site-search-form site-search-form-' . htmlspecialchars($context, ENT_QUOTES)
- . '" role="search">'
- . '<span class="site-search-form-icon">' . $magnifierSvg . '</span>'
- . '<input type="text" name="q" class="site-search-input" placeholder="' . htmlspecialchars($searchPlaceholder, ENT_QUOTES) . '" aria-label="' . htmlspecialchars($searchLabel, ENT_QUOTES) . '">'
- . '</form>';
- }
-
- return '<a href="search.php" class="site-search-icon-link" aria-label="' . htmlspecialchars($searchLabel, ENT_QUOTES) . '">' . $magnifierSvg . '</a>';
- }
-
- public static function renderShareControl(array $article): string
- {
- $settings = self::settings();
- if (($settings['share_enabled'] ?? '0') !== '1') {
- return '';
- }
-
- $url = self::currentUrl();
- $encodedUrl = urlencode($url);
- $encodedTitle = urlencode((string) ($article['title'] ?? ''));
-
- $platformDefs = [
- 'facebook' => [
- 'label' => Language::get('share_facebook', 'Facebook'),
- 'url' => 'https://www.facebook.com/sharer/sharer.php?u=' . $encodedUrl,
- 'svg' => SocialIcons::builtinSvg('facebook'),
- ],
- 'twitter' => [
- 'label' => Language::get('share_twitter', 'Twitter / X'),
- 'url' => 'https://twitter.com/intent/tweet?url=' . $encodedUrl . '&text=' . $encodedTitle,
- 'svg' => SocialIcons::builtinSvg('twitter'),
- ],
- 'linkedin' => [
- 'label' => Language::get('share_linkedin', 'LinkedIn'),
- 'url' => 'https://www.linkedin.com/sharing/share-offsite/?url=' . $encodedUrl,
- 'svg' => SocialIcons::builtinSvg('linkedin'),
- ],
- 'whatsapp' => [
- 'label' => Language::get('share_whatsapp', 'WhatsApp'),
- 'url' => 'https://wa.me/?text=' . $encodedTitle . '%20' . $encodedUrl,
- 'svg' => '<svg viewBox="0 0 24 24"><path d="M12.04 2c-5.52 0-10 4.48-10 10 0 1.77.46 3.5 1.34 5.02L2 22l5.13-1.35a9.96 9.96 0 0 0 4.91 1.29h.01c5.52 0 10-4.48 10-10S17.56 2 12.04 2zm5.87 14.24c-.25.7-1.45 1.34-2 1.42-.51.08-1.16.12-1.87-.12-.43-.14-.98-.32-1.69-.63-2.97-1.28-4.9-4.27-5.05-4.47-.15-.2-1.21-1.61-1.21-3.07s.76-2.18 1.03-2.48c.27-.3.59-.37.79-.37.2 0 .4 0 .57.01.18.01.43-.07.67.51.25.6.85 2.08.92 2.23.07.15.12.33.02.53-.1.2-.15.33-.3.5-.15.18-.31.4-.45.54-.15.15-.3.31-.13.61.17.3.77 1.27 1.65 2.06 1.13 1.01 2.09 1.32 2.39 1.47.3.15.48.13.65-.08.18-.2.75-.87.95-1.17.2-.3.4-.25.67-.15.27.1 1.73.82 2.03.97.3.15.5.22.57.35.08.13.08.73-.17 1.43z"/></svg>',
- ],
- 'telegram' => [
- 'label' => Language::get('share_telegram', 'Telegram'),
- 'url' => 'https://t.me/share/url?url=' . $encodedUrl . '&text=' . $encodedTitle,
- 'svg' => '<svg viewBox="0 0 24 24"><path d="M21.9 4.3 18.8 19.5c-.23 1.05-.85 1.3-1.72.81l-4.75-3.5-2.29 2.2c-.25.25-.47.47-.96.47l.34-4.85 8.8-7.95c.38-.34-.09-.53-.6-.19L6.9 12.6l-4.7-1.47c-1.02-.32-1.04-1.02.21-1.5L20.6 2.9c.85-.32 1.6.2 1.3 1.4z"/></svg>',
- ],
- 'email' => [
- 'label' => Language::get('share_email', 'Email'),
- 'url' => 'mailto:?subject=' . $encodedTitle . '&body=' . $encodedUrl,
- 'svg' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"></rect><path d="M3 7l9 6 9-6"></path></svg>',
- ],
- ];
-
- $platforms = [];
- foreach ($platformDefs as $key => $platform) {
- if (($settings['share_' . $key] ?? '0') === '1') {
- $platforms[$key] = $platform;
- }
- }
-
- $copyLinkEnabled = ($settings['share_copy_link'] ?? '0') === '1';
- if (empty($platforms) && !$copyLinkEnabled) {
- return '';
- }
-
- $shareLabel = Language::get('article_share', 'Share');
- $shareSvg = '<svg class="icon icon-sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.6" y1="10.6" x2="15.4" y2="6.4"></line><line x1="8.6" y1="13.4" x2="15.4" y2="17.6"></line></svg>';
-
- $html = '<div class="article-share">';
- $html .= '<button type="button" class="share-toggle-btn" id="share-toggle-btn" aria-expanded="false" aria-haspopup="true">' . $shareSvg . '<span>' . htmlspecialchars($shareLabel) . '</span></button>';
- $html .= '<div class="share-panel" id="share-panel">';
-
- foreach ($platforms as $key => $platform) {
- $html .= '<a href="' . htmlspecialchars($platform['url'], ENT_QUOTES) . '" class="share-panel-item" target="_blank" rel="noopener noreferrer">'
- . '<span class="share-panel-item-icon share-panel-item-icon-' . htmlspecialchars($key, ENT_QUOTES) . '" aria-hidden="true">' . $platform['svg'] . '</span>'
- . '<span>' . htmlspecialchars($platform['label']) . '</span>'
- . '</a>';
- }
-
- if ($copyLinkEnabled) {
- $linkSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.07 0l2.83-2.83a5 5 0 0 0-7.07-7.07l-1.42 1.41"></path><path d="M14 11a5 5 0 0 0-7.07 0L4.1 13.83a5 5 0 0 0 7.07 7.07l1.41-1.41"></path></svg>';
- $html .= '<button type="button" class="share-panel-item share-panel-item-copy" id="share-copy-btn" data-share-url="' . htmlspecialchars($url, ENT_QUOTES) . '" data-default-text="' . htmlspecialchars(Language::get('share_copy_link', 'Copy link'), ENT_QUOTES) . '" data-copied-text="' . htmlspecialchars(Language::get('share_link_copied', 'Link copied!'), ENT_QUOTES) . '">'
- . '<span class="share-panel-item-icon" aria-hidden="true">' . $linkSvg . '</span>'
- . '<span class="js-share-copy-label">' . htmlspecialchars(Language::get('share_copy_link', 'Copy link')) . '</span>'
- . '</button>';
- }
-
- $html .= '</div></div>';
-
- return $html;
- }
-
- public static function menuPages(): array
- {
- return Database::site()->query(
- "SELECT title, slug FROM pages WHERE status = 'published' AND show_in_menu = 1 ORDER BY sort_order ASC, title ASC"
- )->fetchAll();
- }
-
- public static function categories(): array
- {
- return Database::site()->query('SELECT id, name, slug FROM categories ORDER BY sort_order ASC, name ASC')->fetchAll();
- }
-
- public static function activeAds(string $placement): array
- {
- $statement = Database::site()->prepare(
- 'SELECT * FROM ads WHERE is_active = 1 AND placement = :placement ORDER BY created_at DESC'
- );
- $statement->execute(['placement' => $placement]);
-
- return array_values(array_filter($statement->fetchAll(), static fn(array $ad): bool => self::adFitsVisitor($ad)));
- }
-
- private static function adFitsVisitor(array $ad): bool
- {
- $audience = (string) ($ad['audience'] ?? 'all');
-
- // "Hide from paying subscribers" would contradict an ad meant only for subscribers, so it's ignored there.
- if ($audience !== 'paid' && (int) ($ad['hide_for_subscribers'] ?? 0) === 1 && self::visitorHasSubscription()) {
- return false;
- }
-
- if ($audience !== 'all') {
- $loggedIn = class_exists('UserAuth') && UserAuth::check();
- if (($audience === 'guests' && $loggedIn) || ($audience === 'members' && !$loggedIn)) {
- return false;
- }
- if (($audience === 'paid' && !self::visitorHasSubscription()) || ($audience === 'unpaid' && self::visitorHasSubscription())) {
- return false;
- }
- }
-
- $context = self::$adContext;
- if ($context['type'] === '') {
- return true;
- }
-
- $excluded = self::adExclusions($ad);
- if ($context['type'] === 'home') {
- return !$excluded['home'];
- }
- if ($context['type'] === 'article') {
- return !in_array($context['id'], $excluded['articles'], true);
- }
- if ($context['type'] === 'page') {
- return !in_array($context['id'], $excluded['pages'], true);
- }
-
- return true;
- }
-
- private static ?bool $visitorHasSubscription = null;
-
- public static function visitorHasSubscription(): bool
- {
- if (self::$visitorHasSubscription !== null) {
- return self::$visitorHasSubscription;
- }
-
- self::$visitorHasSubscription = false;
- if (!class_exists('UserAuth') || !UserAuth::check()) {
- return false;
- }
-
- try {
- $reader = UserAuth::user();
- self::$visitorHasSubscription = $reader !== null && UserAuth::hasActiveSubscription((int) $reader['id']);
- } catch (PDOException $e) {
- error_log('Publisium: could not check the reader subscription for ads: ' . $e->getMessage());
- }
-
- return self::$visitorHasSubscription;
- }
-
- public static function renderAd(array $ad): string
- {
- switch ($ad['type']) {
- case 'static_text':
- $html = '<div class="ad-slot ad-text">' . nl2br(htmlspecialchars($ad['content'])) . '</div>';
- break;
- case 'static_image':
- $img = '<img src="' . htmlspecialchars($ad['content']) . '" alt="' . htmlspecialchars($ad['name']) . '">';
- $html = '<div class="ad-slot ad-image">' . ($ad['link_url'] ? '<a href="' . htmlspecialchars($ad['link_url']) . '" rel="sponsored noopener" target="_blank">' . $img . '</a>' : $img) . '</div>';
- break;
- case 'script':
- $html = '<div class="ad-slot ad-script" data-requires-consent="0">' . $ad['content'] . '</div>';
- break;
- default:
- $html = '';
- }
-
- // With consent required, the ad waits in an inert <template> inside its slot until site.js gets consent.
- $consent = (string) ($ad['consent_category'] ?? 'none');
- if ($html !== '' && $consent !== 'none' && array_key_exists($consent, self::AD_CONSENTS) && self::settings()['consent_manager_enabled'] === '1') {
- $open = strpos($html, '>') + 1;
- $close = strrpos($html, '</div>');
- $inner = str_ireplace('</template', '<\/template', substr($html, $open, $close - $open));
- $html = substr($html, 0, $open)
- . '<template class="consent-gated" data-consent-category="' . implode(' ', self::scriptConsentCategories($consent)) . '">' . $inner . '</template>'
- . '</div>';
- }
-
- return $html;
- }
-
- public static function activeAnalyticsScripts(string $placement): array
- {
- $statement = Database::site()->prepare(
- 'SELECT * FROM analytics_scripts WHERE is_active = 1 AND placement = :placement ORDER BY created_at ASC'
- );
- $statement->execute(['placement' => $placement]);
- return $statement->fetchAll();
- }
-
- public const CONSENT_CATEGORIES = ['analytics', 'marketing'];
-
- public const CONSENT_SHOW = [
- 'auto' => 'Show it when a script, an ad or the comments need it (recommended)',
- 'always' => 'Always show it',
- 'never' => 'Never show it (code that needs it won’t run)',
- ];
-
- // Optional consent categories that something active on the site waits for.
- public static function consentNeededCategories(): array
- {
- $needed = [];
- try {
- $rows = Database::site()->query('SELECT DISTINCT consent_category FROM analytics_scripts WHERE is_active = 1 AND requires_consent = 1')->fetchAll(PDO::FETCH_COLUMN);
- foreach ($rows as $category) {
- $needed = array_merge($needed, self::scriptConsentCategories((string) $category));
- }
- } catch (PDOException $exception) {
- }
-
- try {
- $rows = Database::site()->query("SELECT DISTINCT consent_category FROM ads WHERE is_active = 1 AND consent_category IN ('analytics', 'marketing', 'both')")->fetchAll(PDO::FETCH_COLUMN);
- foreach ($rows as $category) {
- $needed = array_merge($needed, self::scriptConsentCategories((string) $category));
- }
- } catch (PDOException $exception) {
- }
-
- $settings = self::settings();
- if ($settings['comments_enabled'] === '1' && $settings['comments_provider'] !== 'builtin' && in_array($settings['comments_consent'], self::CONSENT_CATEGORIES, true)) {
- require_once __DIR__ . '/comments.php';
- if (Comments::isConfigured($settings)) {
- $needed[] = $settings['comments_consent'];
- }
- }
-
- return array_values(array_intersect(self::CONSENT_CATEGORIES, $needed));
- }
-
- // The optional categories the cookie banner offers. Empty means the banner isn't shown at all.
- public static function consentCategories(): array
- {
- $settings = self::settings();
- if ($settings['consent_manager_enabled'] !== '1') {
- return [];
- }
-
- $needed = null;
- $visible = [];
- foreach (self::CONSENT_CATEGORIES as $category) {
- $mode = $settings['consent_show_' . $category] ?? 'auto';
- if ($mode === 'auto') {
- $needed ??= self::consentNeededCategories();
- $show = in_array($category, $needed, true);
- } else {
- $show = $mode === 'always';
- }
- if ($show) {
- $visible[] = $category;
- }
- }
-
- return $visible;
- }
-
- public static function scriptConsentCategories(string $category): array
- {
- return match ($category) {
- 'marketing' => ['marketing'],
- 'both' => ['analytics', 'marketing'],
- default => ['analytics'],
- };
- }
-
- public static function renderAnalyticsScripts(string $placement): string
- {
- $scripts = self::activeAnalyticsScripts($placement);
- $consentManagerEnabled = self::settings()['consent_manager_enabled'] === '1';
- $html = '';
-
- foreach ($scripts as $script) {
- $code = $script['script_code'];
-
- $looksLikeHtml = str_contains($code, '<script') || str_contains($code, '<style') || str_contains($code, '<link') || str_contains($code, '<noscript');
-
- if (!$looksLikeHtml) {
- $code = '<script>' . $code . '</script>';
- }
-
- if ($script['requires_consent'] && $consentManagerEnabled) {
- $safeCode = str_replace('</script>', '<\/script>', $code);
- $html .= '<script type="text/plain" class="consent-gated-script" data-consent-category="' . implode(' ', self::scriptConsentCategories((string) ($script['consent_category'] ?? 'analytics'))) . '" data-placement="' . htmlspecialchars($placement) . '">' . $safeCode . '</script>';
- } else {
- $html .= $code;
- }
- }
-
- return $html;
- }
-
- public static function renderFontFaces(): string
- {
- require_once __DIR__ . '/font-library.php';
-
- $settings = self::settings();
- $emitted = [];
- $css = '';
-
- foreach ([$settings['heading_font'], $settings['body_font'], $settings['interface_font']] as $fontName) {
- if ($fontName === '' || in_array($fontName, $emitted, true)) {
- continue;
- }
- $css .= FontLibrary::fontFaceCss($fontName, $fontName);
- $emitted[] = $fontName;
- }
-
- return $css;
- }
-
- public static function fontVariablesCss(): string
- {
- $settings = self::settings();
- $headingFamily = addslashes($settings['heading_font']);
- $bodyFamily = addslashes($settings['body_font']);
- $interfaceFamily = addslashes($settings['interface_font']);
-
- return ":root{"
- . "--font-heading:\"{$headingFamily}\", -apple-system, BlinkMacSystemFont, sans-serif;"
- . "--font-body:\"{$bodyFamily}\", Georgia, serif;"
- . "--font-ui:\"{$interfaceFamily}\", -apple-system, BlinkMacSystemFont, sans-serif;"
- . "}";
- }
-
- private const TRACKING_PARAMS = ['fbclid', 'gclid', 'msclkid', 'yclid', 'igshid', 'mc_cid', 'mc_eid', '_ga', 'ref_src'];
-
- private static function configuredUrl(): string
- {
- $url = trim((string) Config::get('APP_URL', ''));
- if ($url === '') {
- return '';
- }
-
- if (!preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
- $url = 'https://' . $url;
- }
-
- return rtrim($url, '/');
- }
-
- private static function normalizeHost(string $host, string $scheme = ''): string
- {
- $host = strtolower(rtrim(trim($host), '.'));
- if ($host === '') {
- return '';
- }
-
- $port = '';
- if (preg_match('/^(.*):(\d+)$/', $host, $matches) && !str_ends_with($matches[1], ']')) {
- $host = $matches[1];
- $port = $matches[2];
- } elseif (preg_match('/^(\[.*\]):(\d+)$/', $host, $matches)) {
- $host = $matches[1];
- $port = $matches[2];
- }
-
- $defaultPorts = ['80', '443'];
- if ($scheme === 'http') {
- $defaultPorts = ['80'];
- } elseif ($scheme === 'https') {
- $defaultPorts = ['443'];
- }
-
- return in_array($port, $defaultPorts, true) || $port === '' ? $host : $host . ':' . $port;
- }
-
- private static function requestHost(): string
- {
- $forwarded = trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_HOST'] ?? ''))[0]);
- $host = $forwarded !== '' ? $forwarded : (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '');
-
- return self::normalizeHost($host);
- }
-
- private static function requestScheme(): string
- {
- $forwarded = strtolower(trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''))[0]));
- if ($forwarded === 'https' || $forwarded === 'http') {
- return $forwarded;
- }
-
- $https = strtolower((string) ($_SERVER['HTTPS'] ?? ''));
- if (($https !== '' && $https !== 'off') || (string) ($_SERVER['SERVER_PORT'] ?? '') === '443') {
- return 'https';
- }
-
- return 'http';
- }
-
- public static function isConfiguredHost(): bool
- {
- $configured = self::configuredUrl();
- if ($configured === '') {
- return true;
- }
-
- $parts = parse_url($configured);
- $configuredHost = self::normalizeHost((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''), (string) ($parts['scheme'] ?? ''));
- $currentHost = self::requestHost();
-
- if ($configuredHost === '' || $currentHost === '') {
- return true;
- }
-
- return $configuredHost === $currentHost;
- }
-
- private static function cleanRequestUri(): string
- {
- $uri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
- $path = (string) parse_url($uri, PHP_URL_PATH);
- $query = (string) parse_url($uri, PHP_URL_QUERY);
-
- if ($path === '') {
- $path = '/';
- }
-
- if (self::cleanHomeUrl() && str_ends_with($path, '/index.php')) {
- $path = substr($path, 0, -strlen('index.php'));
- }
-
- if ($query === '') {
- return $path;
- }
-
- $kept = [];
- foreach (explode('&', $query) as $pair) {
- if ($pair === '') {
- continue;
- }
- $name = strtolower(urldecode(explode('=', $pair, 2)[0]));
- if (str_starts_with($name, 'utm_') || in_array($name, self::TRACKING_PARAMS, true)) {
- continue;
- }
- $kept[] = $pair;
- }
-
- return $kept === [] ? $path : $path . '?' . implode('&', $kept);
- }
-
- public static function currentUrl(): string
- {
- $baseUrl = self::configuredUrl();
- if ($baseUrl === '') {
- $host = self::requestHost();
- $baseUrl = $host === '' ? '' : self::requestScheme() . '://' . $host;
- }
-
- return $baseUrl . self::cleanRequestUri();
- }
-
- public static function renderSeoMeta(): string
- {
- $settings = self::settings();
- $html = '';
-
- if ($settings['seo_keywords'] !== '') {
- $html .= '<meta name="keywords" content="' . htmlspecialchars($settings['seo_keywords'], ENT_QUOTES) . '">' . "\n";
- }
-
- if ($settings['seo_author'] !== '') {
- $html .= '<meta name="author" content="' . htmlspecialchars($settings['seo_author'], ENT_QUOTES) . '">' . "\n";
- }
-
- if ($settings['seo_reply_to'] !== '') {
- $html .= '<meta name="reply-to" content="' . htmlspecialchars($settings['seo_reply_to'], ENT_QUOTES) . '">' . "\n";
- }
-
- if ($settings['seo_application_name'] !== '') {
- $html .= '<meta name="application-name" content="' . htmlspecialchars($settings['seo_application_name'], ENT_QUOTES) . '">' . "\n";
- }
-
- $robotsIndex = $settings['seo_robots_index'] === '1' && self::isConfiguredHost() ? 'index' : 'noindex';
- $robotsFollow = $settings['seo_robots_follow'] === '1' ? 'follow' : 'nofollow';
- $html .= '<meta name="robots" content="' . $robotsIndex . ',' . $robotsFollow . '">' . "\n";
-
- $html .= '<link rel="canonical" href="' . htmlspecialchars(self::currentUrl(), ENT_QUOTES) . '">';
-
- return $html;
- }
-
- public static function renderOpenGraph(string $title, string $description, string $type = 'website', ?string $imagePath = null, ?array $articleMeta = null): string
- {
- $settings = self::settings();
-
- $html = '<meta property="og:title" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
- $html .= '<meta property="og:type" content="' . htmlspecialchars($type, ENT_QUOTES) . '">' . "\n";
- $html .= '<meta property="og:url" content="' . htmlspecialchars(self::currentUrl(), ENT_QUOTES) . '">' . "\n";
- $html .= '<meta property="og:site_name" content="' . htmlspecialchars($settings['site_name'], ENT_QUOTES) . '">' . "\n";
-
- if ($description !== '') {
- $html .= '<meta property="og:description" content="' . htmlspecialchars($description, ENT_QUOTES) . '">' . "\n";
- }
-
- $ogImage = null;
- if ($imagePath !== null && $settings['seo_og_article_image_enabled'] === '1') {
- $ogImage = $imagePath;
- } elseif ($settings['site_logo_url'] !== '') {
- $ogImage = $settings['site_logo_url'];
- }
- $ogImage = $ogImage !== null ? self::absoluteUrl($ogImage) : '';
-
- if ($ogImage !== '') {
- $html .= '<meta property="og:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES) . '">' . "\n";
- }
-
- if ($settings['seo_social_tags_enabled'] === '1') {
- $html .= '<meta property="og:locale" content="' . htmlspecialchars(str_replace('-', '_', Languages::htmlLang()), ENT_QUOTES) . '">' . "\n";
-
- if ($ogImage !== '') {
- $html .= '<meta property="og:image:alt" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
- }
-
- $published = self::isoDate($articleMeta['published'] ?? null);
- $modified = self::isoDate($articleMeta['modified'] ?? null);
- if ($published !== null) {
- $html .= '<meta property="article:published_time" content="' . $published . '">' . "\n";
- }
- if ($modified !== null) {
- $html .= '<meta property="article:modified_time" content="' . $modified . '">' . "\n";
- }
- if (!empty($articleMeta['author'])) {
- $html .= '<meta property="article:author" content="' . htmlspecialchars((string) $articleMeta['author'], ENT_QUOTES) . '">' . "\n";
- }
- if (!empty($articleMeta['section'])) {
- $html .= '<meta property="article:section" content="' . htmlspecialchars((string) $articleMeta['section'], ENT_QUOTES) . '">' . "\n";
- }
-
- $html .= '<meta name="twitter:card" content="' . ($ogImage !== '' ? 'summary_large_image' : 'summary') . '">' . "\n";
- $html .= '<meta name="twitter:title" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
- if ($description !== '') {
- $html .= '<meta name="twitter:description" content="' . htmlspecialchars($description, ENT_QUOTES) . '">' . "\n";
- }
- if ($ogImage !== '') {
- $html .= '<meta name="twitter:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES) . '">' . "\n";
- $html .= '<meta name="twitter:image:alt" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
- }
- if ($settings['seo_twitter_handle'] !== '') {
- $html .= '<meta name="twitter:site" content="' . htmlspecialchars($settings['seo_twitter_handle'], ENT_QUOTES) . '">' . "\n";
- }
- }
-
- return rtrim($html, "\n");
- }
-
- public static function renderArticleSchema(array $article, string $authorType, ?string $authorUrl): string
- {
- $settings = self::settings();
- $homeUrl = self::absoluteUrl(self::homeUrl());
-
- $schema = [
- '@context' => 'https://schema.org',
- '@type' => 'NewsArticle',
- 'mainEntityOfPage' => ['@type' => 'WebPage', '@id' => self::currentUrl()],
- 'headline' => (string) $article['title'],
- ];
-
- $description = (string) (($article['seo_description'] ?? '') ?: ($article['excerpt'] ?? ''));
- if ($description !== '') {
- $schema['description'] = $description;
- }
-
- $image = !empty($article['cover_image_path']) ? (string) $article['cover_image_path'] : $settings['site_logo_url'];
- if ($image !== '') {
- $schema['image'] = [self::absoluteUrl($image)];
- }
-
- $published = self::isoDate($article['published_at'] ?? null);
- $modified = self::isoDate($article['updated_at'] ?? null);
- if ($published !== null) {
- $schema['datePublished'] = $published;
- $schema['dateModified'] = $modified !== null && $modified > $published ? $modified : $published;
- }
-
- $authorName = trim((string) ($article['author_name'] ?? ''));
- if ($authorName !== '') {
- $author = ['@type' => $authorType === 'Organization' ? 'Organization' : 'Person', 'name' => $authorName];
- if ($authorUrl !== null && $authorUrl !== '') {
- $author['url'] = self::absoluteUrl($authorUrl);
- }
- } else {
- $author = ['@type' => 'Organization', 'name' => $settings['site_name'], 'url' => $homeUrl];
- }
- $schema['author'] = [$author];
-
- $publisher = ['@type' => 'Organization', 'name' => $settings['site_name'], 'url' => $homeUrl];
- if ($settings['site_logo_url'] !== '') {
- $publisher['logo'] = ['@type' => 'ImageObject', 'url' => self::absoluteUrl($settings['site_logo_url'])];
- }
- $schema['publisher'] = $publisher;
-
- if (($article['access_type'] ?? 'free') === 'paid') {
- $schema['isAccessibleForFree'] = false;
- }
-
- return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) . '</script>';
- }
-
- public static function absoluteUrl(string $url): string
- {
- $url = trim($url);
- if ($url === '' || preg_match('#^https?://#i', $url) === 1) {
- return $url;
- }
-
- if (str_starts_with($url, '//')) {
- return self::requestScheme() . ':' . $url;
- }
-
- $origin = self::configuredUrl();
- if ($origin === '') {
- $host = self::requestHost();
- $origin = $host === '' ? '' : self::requestScheme() . '://' . $host;
- }
-
- if (str_starts_with($url, '/')) {
- return $origin . $url;
- }
-
- return $origin . rtrim((string) Config::get('APP_BASE_PATH', ''), '/') . '/' . $url;
- }
-
- private static function isoDate(?string $value): ?string
- {
- if ($value === null || $value === '') {
- return null;
- }
-
- $timestamp = strtotime($value);
-
- return $timestamp === false ? null : date(DATE_ATOM, $timestamp);
- }
-
- public static function renderOrganizationSchema(): string
- {
- $settings = self::settings();
-
- $schema = [
- '@context' => 'https://schema.org',
- '@graph' => [
- [
- '@type' => 'Organization',
- 'name' => $settings['site_name'],
- 'url' => rtrim(Config::get('APP_URL', ''), '/') . '/',
- ],
- [
- '@type' => 'WebSite',
- 'name' => $settings['site_name'],
- 'url' => rtrim(Config::get('APP_URL', ''), '/') . '/',
- ],
- ],
- ];
-
- if ($settings['site_logo_url'] !== '') {
- $schema['@graph'][0]['logo'] = self::absoluteUrl($settings['site_logo_url']);
- }
-
- if ($settings['site_description'] !== '') {
- $schema['@graph'][1]['description'] = $settings['site_description'];
- }
-
- return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) . '</script>';
- }
-
- private static function isCustomHtmlEnabledFor(string $slot, ?string $pageType): bool
- {
- if ($pageType === null || !in_array($pageType, ['index', 'article', 'category', 'pages'], true)) {
- return false;
- }
-
- $settings = self::settings();
- $key = 'custom_' . $slot . '_html_' . $pageType;
-
- return ($settings[$key] ?? '0') === '1';
- }
-
- public static function renderCustomHeadHtml(?string $pageType): string
- {
- if (!self::isCustomHtmlEnabledFor('head', $pageType)) {
- return '';
- }
-
- return self::settings()['custom_head_html'];
- }
-
- public static function renderCustomBodyHtml(?string $pageType): string
- {
- if (!self::isCustomHtmlEnabledFor('body', $pageType)) {
- return '';
- }
-
- return self::settings()['custom_body_html'];
- }
- }
-