v1.0.0.1
StocketBase
- <?php
-
- declare(strict_types=1);
-
- require_once __DIR__ . '/database.php';
- require_once __DIR__ . '/icons.php';
- require_once __DIR__ . '/social-icons.php';
- require_once __DIR__ . '/product-scheduler.php';
- require_once __DIR__ . '/languages.php';
-
- final class SiteFront
- {
- private static ?array $settings = null;
-
- public const AD_PLACEMENTS = [
- 'header' => 'Under the menu, on every page',
- 'homepage-top' => 'Home page, above featured products',
- 'catalog-top' => 'Between products in lists',
- 'product-page' => 'Product page, under the photos',
- 'checkout' => 'Checkout page',
- 'footer' => 'Just above the footer',
- ];
-
- public static function productUrl(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_product_urls'] ?? '0') === '1') {
- return $basePath . $prefix . '/' . rawurlencode($slug);
- }
-
- return $basePath . $prefix . '/product.php?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', 'StocketBase'),
- '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_product_image_enabled' => '0',
- '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',
- 'require_account_to_purchase' => '0',
- 'download_link_expiry_days' => '30',
- 'download_link_max_downloads' => '10',
- 'contact_enabled' => '0',
- 'contact_recipient_email' => '',
- 'contact_provider' => 'php_mail',
- 'contact_subject_mode' => 'free',
- 'contact_subjects' => '',
- 'contact_from_email' => '',
- 'contact_resend_api_key' => '',
- 'contact_postmark_token' => '',
- 'custom_css' => '',
- 'custom_js' => '',
- 'custom_head_html' => '',
- 'custom_head_html_index' => '0',
- 'custom_head_html_product' => '0',
- 'custom_head_html_category' => '0',
- 'custom_head_html_pages' => '0',
- 'custom_body_html' => '',
- 'custom_body_html_index' => '0',
- 'custom_body_html_product' => '0',
- 'custom_body_html_category' => '0',
- 'custom_body_html_pages' => '0',
- 'menu_position' => 'top',
- 'featured_banner_enabled' => '0',
- 'featured_banner_mode' => 'static',
- 'featured_banner_hide_duplicates' => '0',
- 'featured_banner_product_1' => '0',
- 'featured_banner_product_2' => '0',
- 'featured_banner_product_3' => '0',
- 'featured_banner_product_4' => '0',
- 'featured_banner_product_5' => '0',
- 'featured_banner_auto_window_value' => '24',
- 'featured_banner_auto_window_unit' => 'hours',
- 'featured_banner_auto_category_mode' => 'mixed',
- 'related_products_enabled' => '1',
- 'product_show_buyers' => '0',
- 'product_show_downloads' => '0',
- 'back_to_top_enabled' => '0',
- 'back_to_top_progress_enabled' => '0',
- 'breadcrumbs_enabled' => '0',
- 'tags_enabled' => '0',
- 'shop_icon_choice' => 'cart',
- 'shop_icon_custom_svg' => '',
- 'activity_log_enabled' => '0',
- 'seo_preview_enabled' => '0',
- 'indexnow_enabled' => '0',
- 'indexnow_key' => '',
- 'sitemap_rss_enabled' => '1',
- 'reviews_enabled' => '1',
- 'consent_manager_enabled' => '0',
- 'consent_footer_icon_enabled' => '0',
- 'heading_font' => 'Plus Jakarta Sans',
- 'body_font' => 'PT Serif',
- 'interface_font' => 'Plus Jakarta Sans',
- 'store_category' => 'general',
- 'pricing_model' => 'per_product',
- 'store_currency' => 'USD',
- 'payment_provider' => 'stripe',
- 'payment_webhook_secret' => '',
- 'payment_polar_webhook_secret' => '',
- 'payment_stripe_secret_key' => '',
- 'payment_stripe_publishable_key' => '',
- 'payment_polar_access_token' => '',
- 'payment_polar_organization_id' => '',
- 'subscription_interval' => 'month',
- 'mail_transport' => 'smtp',
- 'mail_smtp_host' => '',
- 'mail_smtp_port' => '587',
- 'mail_smtp_username' => '',
- 'mail_smtp_password' => '',
- 'mail_smtp_encryption' => 'tls',
- 'mail_resend_api_key' => '',
- 'mail_postmark_server_token' => '',
- 'mail_from_email' => '',
- 'mail_from_name' => '',
- 'mail_reply_to' => '',
- 'footer_columns' => '[]',
- 'footer_social_links' => '[]',
- 'product_loading_mode' => 'scroll',
- 'pagination_style' => 'numbered',
- 'products_per_page_home' => '12',
- 'products_per_page_category' => '12',
- 'search_enabled' => '1',
- 'search_match_title' => '1',
- 'search_match_excerpt' => '1',
- 'search_match_content' => '0',
- 'search_style' => 'icon',
- 'search_show_in_nav' => '1',
- '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);
- ProductScheduler::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' AND is_home = 0 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' => 'page.php?slug=' . urlencode($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 appendToCustomMenu(string $itemType, int $refId): void
- {
- if (!in_array($itemType, ['category', 'page'], true) || $refId <= 0) {
- return;
- }
-
- try {
- $db = Database::site();
- if ((int) $db->query('SELECT COUNT(*) FROM nav_items')->fetchColumn() === 0) {
- return;
- }
-
- $existing = $db->prepare('SELECT 1 FROM nav_items WHERE item_type = :type AND ref_id = :ref_id LIMIT 1');
- $existing->execute(['type' => $itemType, 'ref_id' => $refId]);
- if ($existing->fetchColumn()) {
- return;
- }
-
- $nextOrder = (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' => $nextOrder]);
- } catch (PDOException $exception) {
- error_log('StocketBase: could not add ' . $itemType . ' ' . $refId . ' to the menu: ' . $exception->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' AND is_home = 0 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' => 'page.php?slug=' . urlencode($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 AND is_home = 0 ORDER BY sort_order ASC, title ASC"
- )->fetchAll();
- }
-
- public static function homePage(): ?array
- {
- require_once __DIR__ . '/block-editor.php';
-
- $db = Database::site();
- $row = $db->query('SELECT * FROM pages WHERE is_home = 1 ORDER BY id ASC LIMIT 1')->fetch();
- if ($row) {
- return $row;
- }
-
- $settings = self::settings();
- $locked = false;
-
- try {
- $locked = (int) $db->query("SELECT GET_LOCK('stocketbase_home_page', 5)")->fetchColumn() === 1;
-
- $row = $db->query('SELECT * FROM pages WHERE is_home = 1 ORDER BY id ASC LIMIT 1')->fetch();
- if (!$row) {
- $slugCheck = $db->prepare('SELECT COUNT(*) FROM pages WHERE slug = :slug');
- $slug = '_home';
- for ($attempt = 2; $attempt < 100; $attempt++) {
- $slugCheck->execute(['slug' => $slug]);
- if ((int) $slugCheck->fetchColumn() === 0) {
- break;
- }
- $slug = '_home-' . $attempt;
- }
-
- $insert = $db->prepare(
- "INSERT INTO pages (author_id, title, slug, content_blocks, status, show_in_menu, sort_order, is_home) VALUES (NULL, :title, :slug, :content, 'published', 0, -1000, 1)"
- );
- $insert->execute([
- 'title' => 'Home page',
- 'slug' => $slug,
- 'content' => BlockEditor::defaultHomepageBlocks(trim((string) ($settings['site_description'] ?? '')) !== ''),
- ]);
-
- $row = $db->query('SELECT * FROM pages WHERE is_home = 1 ORDER BY id ASC LIMIT 1')->fetch();
- }
- } catch (PDOException $exception) {
- $row = false;
- } finally {
- if ($locked) {
- $db->query("SELECT RELEASE_LOCK('stocketbase_home_page')");
- }
- }
-
- return $row ?: null;
- }
-
- 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 $statement->fetchAll();
- }
-
- 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 = '';
- }
-
- 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 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-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 ($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): 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_product_image_enabled'] === '1') {
- $ogImage = $imagePath;
- } elseif ($settings['site_logo_url'] !== '') {
- $ogImage = $settings['site_logo_url'];
- }
-
- if ($ogImage !== null && $ogImage !== '') {
- $html .= '<meta property="og:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES) . '">';
- }
-
- return $html;
- }
-
- 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'] = $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) . '</script>';
- }
-
- private static function isCustomHtmlEnabledFor(string $slot, ?string $pageType): bool
- {
- if ($pageType === null || !in_array($pageType, ['index', 'product', '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'];
- }
- }
-