WebOrbiton
v1.0.0.9

Publisium

1,232 lines · 50.7 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/database.php';
  6. require_once __DIR__ . '/icons.php';
  7. require_once __DIR__ . '/social-icons.php';
  8. require_once __DIR__ . '/article-scheduler.php';
  9. require_once __DIR__ . '/languages.php';
  10. require_once __DIR__ . '/clean-urls.php';
  11. ​
  12. final class SiteFront
  13. {
  14. private static ?array $settings = null;
  15. ​
  16. public const AD_PLACEMENTS = [
  17. 'header' => 'Header, below the menu on every page',
  18. 'homepage-top' => 'Home page, near the top',
  19. 'homepage-bottom' => 'Home page, at the bottom',
  20. 'in-feed' => 'Between articles in lists (home page and categories)',
  21. 'category-top' => 'Category pages, above the articles',
  22. 'search-top' => 'Search page, above the results',
  23. 'article-top' => 'Articles, below the title',
  24. 'in-article' => 'Inside articles, between the cover image and the text',
  25. 'article-middle' => 'Articles, in the middle of the text',
  26. 'article-bottom' => 'Below the article text',
  27. 'page-top' => 'Pages, below the title',
  28. 'page-bottom' => 'Pages, below the content',
  29. 'footer' => 'Just above the footer',
  30. 'sticky-bottom' => 'Bar stuck to the bottom of the screen (visitors can close it)',
  31. ];
  32. ​
  33. public const AD_AUDIENCES = [
  34. 'all' => 'Everyone',
  35. 'guests' => 'Only visitors who aren’t logged in',
  36. 'members' => 'Only logged-in readers',
  37. 'paid' => 'Only paying subscribers',
  38. 'unpaid' => 'Only people who don’t pay (including visitors who aren’t logged in)',
  39. ];
  40. ​
  41. public const AD_CONSENTS = [
  42. 'none' => 'Show it right away, no cookie consent needed',
  43. 'marketing' => 'Only after the visitor allows marketing (usual for ad networks)',
  44. 'analytics' => 'Only after the visitor allows analytics',
  45. 'both' => 'Only after the visitor allows both analytics and marketing',
  46. ];
  47. ​
  48. public const ADBLOCK_MODES = [
  49. 'once' => 'User-Friendly: shows once, then never again in that browser',
  50. 'session' => 'Session: shows once per visit (until the tab is closed)',
  51. 'extended' => 'Extended: shows on every page, visitors can close it',
  52. 'lock' => 'ViewLocker: can’t be closed and the page can’t be scrolled',
  53. 'lock_max' => 'ViewLocker Max: can’t be closed and everything except the message is blurred out',
  54. ];
  55. ​
  56. public static function adblockMode(): string
  57. {
  58. $mode = (string) (self::settings()['adblock_notice_mode'] ?? 'session');
  59. $mode = ['gentle' => 'session', 'wall' => 'lock_max'][$mode] ?? $mode;
  60. ​
  61. return array_key_exists($mode, self::ADBLOCK_MODES) ? $mode : 'session';
  62. }
  63. ​
  64. private static array $adContext = ['type' => '', 'id' => 0];
  65. ​
  66. // Tells the ad system what is being shown, so ads can skip excluded articles and pages.
  67. public static function setAdContext(string $type, int $id = 0): void
  68. {
  69. self::$adContext = ['type' => $type, 'id' => $id];
  70. }
  71. ​
  72. public static function adExclusions(array $ad): array
  73. {
  74. $decoded = json_decode((string) ($ad['excluded_items'] ?? ''), true);
  75. $decoded = is_array($decoded) ? $decoded : [];
  76. ​
  77. return [
  78. 'home' => !empty($decoded['home']),
  79. 'articles' => array_values(array_unique(array_filter(array_map('intval', is_array($decoded['articles'] ?? null) ? $decoded['articles'] : [])))),
  80. 'pages' => array_values(array_unique(array_filter(array_map('intval', is_array($decoded['pages'] ?? null) ? $decoded['pages'] : [])))),
  81. ];
  82. }
  83. ​
  84. // A date in the site's language (for example "28 września 2026"), optionally with the time
  85. // in the 24-hour or 12-hour format picked in Layout. Without the intl extension it falls back to English.
  86. public static function formatDate(string|int $when, bool $withTime = false): string
  87. {
  88. $timestamp = is_int($when) ? $when : strtotime($when);
  89. if ($timestamp === false) {
  90. return '';
  91. }
  92. ​
  93. $date = false;
  94. if (class_exists('IntlDateFormatter')) {
  95. $formatter = new IntlDateFormatter(str_replace('-', '_', Languages::htmlLang()), IntlDateFormatter::LONG, IntlDateFormatter::NONE, date_default_timezone_get());
  96. $date = $formatter->format($timestamp);
  97. }
  98. if (!is_string($date) || $date === '') {
  99. $date = date('F j, Y', $timestamp);
  100. }
  101. ​
  102. if (!$withTime) {
  103. return $date;
  104. }
  105. ​
  106. return $date . ', ' . date(self::settings()['article_time_format'] === '12' ? 'g:i A' : 'H:i', $timestamp);
  107. }
  108. ​
  109. // The payment link, with the reader's email filled in on Polar and Stripe payment links.
  110. // The webhook links a payment to an account by email, so this keeps them matching.
  111. public static function subscriptionCheckoutUrl(?string $email = null): string
  112. {
  113. $url = trim((string) self::settings()['subscription_checkout_url']);
  114. $email = strtolower(trim((string) $email));
  115. if ($url === '' || $email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  116. return $url;
  117. }
  118. ​
  119. $host = strtolower((string) parse_url($url, PHP_URL_HOST));
  120. $param = match (true) {
  121. $host === 'polar.sh' || str_ends_with($host, '.polar.sh') => 'customer_email',
  122. $host === 'buy.stripe.com' => 'prefilled_email',
  123. default => '',
  124. };
  125. if ($param === '' || preg_match('/[?&]' . $param . '=/', $url) === 1) {
  126. return $url;
  127. }
  128. ​
  129. [$base, $fragment] = array_pad(explode('#', $url, 2), 2, null);
  130. ​
  131. return $base . (str_contains($base, '?') ? '&' : '?') . $param . '=' . rawurlencode($email) . ($fragment !== null ? '#' . $fragment : '');
  132. }
  133. ​
  134. public static function renderAds(string $placement): string
  135. {
  136. $html = '';
  137. foreach (self::activeAds($placement) as $ad) {
  138. $html .= self::renderAd($ad);
  139. }
  140. ​
  141. return $html;
  142. }
  143. ​
  144. public static function articleUrl(string $slug, ?string $lang = null): string
  145. {
  146. $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
  147. $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
  148. if ((self::settings()['clean_article_urls'] ?? '0') === '1') {
  149. return $basePath . $prefix . '/' . rawurlencode(CleanUrls::slugFor('article', $slug) ?? $slug);
  150. }
  151. ​
  152. return $basePath . $prefix . '/article.php?slug=' . rawurlencode($slug);
  153. }
  154. ​
  155. // Link to the home page: "/" when the short home address is on, otherwise "/index.php".
  156. public static function homeUrl(?string $lang = null): string
  157. {
  158. $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
  159. $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
  160. ​
  161. return $basePath . $prefix . (self::cleanHomeUrl() ? '/' : '/index.php');
  162. }
  163. ​
  164. public static function cleanHomeUrl(): bool
  165. {
  166. return (self::settings()['clean_home_url'] ?? '0') === '1';
  167. }
  168. ​
  169. public static function pageUrl(string $slug, ?string $lang = null): string
  170. {
  171. return self::entityUrl('page', 'page.php', $slug, $lang);
  172. }
  173. ​
  174. public static function authorUrl(string $slug, ?string $lang = null): string
  175. {
  176. return self::entityUrl('author', 'artist.php', $slug, $lang);
  177. }
  178. ​
  179. private static function entityUrl(string $type, string $script, string $slug, ?string $lang): string
  180. {
  181. $basePath = rtrim((string) Config::get('APP_BASE_PATH', ''), '/');
  182. $prefix = $lang === null ? Languages::prefix() : ($lang === '' ? '' : '/' . $lang);
  183. $cleanSlug = CleanUrls::slugFor($type, $slug);
  184. if ($cleanSlug !== null) {
  185. return $basePath . $prefix . '/' . rawurlencode($cleanSlug);
  186. }
  187. ​
  188. return $basePath . $prefix . '/' . $script . '?slug=' . rawurlencode($slug);
  189. }
  190. ​
  191. public static function resetSettings(): void
  192. {
  193. self::$settings = null;
  194. }
  195. ​
  196. public static function settings(): array
  197. {
  198. if (self::$settings !== null) {
  199. return self::$settings;
  200. }
  201. ​
  202. $defaults = [
  203. 'site_name' => Config::get('APP_NAME', 'Publisium'),
  204. 'site_description' => '',
  205. 'seo_title' => '',
  206. 'seo_description' => '',
  207. 'seo_keywords' => '',
  208. 'seo_author' => '',
  209. 'seo_reply_to' => '',
  210. 'seo_application_name' => '',
  211. 'seo_robots_index' => '1',
  212. 'seo_robots_follow' => '1',
  213. 'seo_og_article_image_enabled' => '0',
  214. 'seo_article_schema_enabled' => '0',
  215. 'seo_social_tags_enabled' => '0',
  216. 'seo_twitter_handle' => '',
  217. 'llms_txt_enabled' => '0',
  218. 'site_logo_url' => '',
  219. 'site_show_name_with_logo' => '0',
  220. 'site_short_name' => '',
  221. 'site_short_name_enabled' => '0',
  222. 'registration_enabled' => '1',
  223. 'login_enabled' => '1',
  224. 'custom_css' => '',
  225. 'custom_js' => '',
  226. 'custom_head_html' => '',
  227. 'custom_head_html_index' => '0',
  228. 'custom_head_html_article' => '0',
  229. 'custom_head_html_category' => '0',
  230. 'custom_head_html_pages' => '0',
  231. 'custom_body_html' => '',
  232. 'custom_body_html_index' => '0',
  233. 'custom_body_html_article' => '0',
  234. 'custom_body_html_category' => '0',
  235. 'custom_body_html_pages' => '0',
  236. 'menu_position' => 'top',
  237. 'banner_enabled' => '1',
  238. 'featured_banner_enabled' => '0',
  239. 'featured_banner_mode' => 'static',
  240. 'featured_banner_hide_duplicates' => '0',
  241. 'featured_banner_article_1' => '0',
  242. 'featured_banner_article_2' => '0',
  243. 'featured_banner_article_3' => '0',
  244. 'featured_banner_article_4' => '0',
  245. 'featured_banner_article_5' => '0',
  246. 'featured_banner_auto_window_value' => '24',
  247. 'featured_banner_auto_window_unit' => 'hours',
  248. 'featured_banner_auto_category_mode' => 'mixed',
  249. 'related_articles_enabled' => '1',
  250. 'article_reading_time_enabled' => '1',
  251. 'article_time_enabled' => '0',
  252. 'article_time_format' => '24',
  253. 'back_to_top_enabled' => '0',
  254. 'adblock_notice_enabled' => '0',
  255. 'adblock_notice_mode' => 'session',
  256. 'back_to_top_progress_enabled' => '0',
  257. 'toc_enabled' => '0',
  258. 'breadcrumbs_enabled' => '0',
  259. 'author_box_enabled' => '0',
  260. 'account_consents_enabled' => '1',
  261. 'author_pages_enabled' => '0',
  262. 'tags_enabled' => '0',
  263. 'activity_log_enabled' => '0',
  264. 'seo_preview_enabled' => '0',
  265. 'indexnow_enabled' => '0',
  266. 'indexnow_key' => '',
  267. 'sitemap_rss_enabled' => '1',
  268. 'rss_category_feeds_enabled' => '0',
  269. 'comments_enabled' => '0',
  270. 'comments_provider' => 'disqus',
  271. 'comments_shortname' => '',
  272. 'comments_server_url' => '',
  273. 'comments_site_id' => '',
  274. 'comments_repo' => '',
  275. 'comments_repo_id' => '',
  276. 'comments_category' => '',
  277. 'comments_category_id' => '',
  278. 'comments_mapping' => 'pathname',
  279. 'comments_custom_html' => '',
  280. 'comments_consent' => 'marketing',
  281. 'comments_load' => 'auto',
  282. 'comments_who' => 'users',
  283. 'comments_moderation' => 'all',
  284. 'comments_email' => 'off',
  285. 'consent_manager_enabled' => '0',
  286. 'consent_footer_icon_enabled' => '0',
  287. 'consent_show_analytics' => 'auto',
  288. 'consent_show_marketing' => 'auto',
  289. 'heading_font' => 'Plus Jakarta Sans',
  290. 'body_font' => 'PT Serif',
  291. 'interface_font' => 'Plus Jakarta Sans',
  292. 'subscription_name' => 'Full access',
  293. 'subscription_price_cents' => '0',
  294. 'subscription_interval' => 'month',
  295. 'subscription_currency' => 'USD',
  296. 'subscription_description' => '',
  297. 'subscription_checkout_url' => '',
  298. 'payment_provider' => 'stripe',
  299. 'payment_webhook_secret' => '',
  300. 'footer_columns' => '[]',
  301. 'footer_social_links' => '[]',
  302. 'article_loading_mode' => 'scroll',
  303. 'pagination_style' => 'numbered',
  304. 'articles_per_page_home' => '12',
  305. 'articles_per_page_category' => '12',
  306. 'search_enabled' => '0',
  307. 'search_match_title' => '1',
  308. 'search_match_excerpt' => '1',
  309. 'search_match_content' => '0',
  310. 'search_style' => 'icon',
  311. 'search_show_in_nav' => '0',
  312. 'search_show_in_footer' => '0',
  313. 'share_enabled' => '0',
  314. 'share_facebook' => '1',
  315. 'share_twitter' => '1',
  316. 'share_linkedin' => '1',
  317. 'share_whatsapp' => '1',
  318. 'share_telegram' => '0',
  319. 'share_email' => '1',
  320. 'share_copy_link' => '1',
  321. 'pwa_enabled' => '0',
  322. 'pwa_name' => '',
  323. 'pwa_short_name' => '',
  324. 'pwa_description' => '',
  325. 'pwa_icon_url' => '',
  326. 'pwa_theme_color' => '#ffffff',
  327. 'pwa_background_color' => '#ffffff',
  328. 'app_banner_enabled' => '0',
  329. 'app_android_url' => '',
  330. 'app_ios_url' => '',
  331. 'multilang_enabled' => '0',
  332. 'multilang_default_code' => 'en',
  333. 'multilang_default_name' => 'English',
  334. 'multilang_switcher' => '1',
  335. ];
  336. ​
  337. $rows = Database::site()->query('SELECT setting_key, setting_value FROM site_settings')->fetchAll();
  338. $values = [];
  339. foreach ($rows as $row) {
  340. $values[$row['setting_key']] = $row['setting_value'];
  341. }
  342. ​
  343. self::$settings = array_merge($defaults, $values);
  344. self::$settings = Languages::applySiteTexts(self::$settings);
  345. ArticleScheduler::publishDue();
  346. ​
  347. return self::$settings;
  348. }
  349. ​
  350. public static function navItems(): array
  351. {
  352. try {
  353. $rows = Database::site()->query(
  354. 'SELECT * FROM nav_items ORDER BY sort_order ASC, id ASC'
  355. )->fetchAll();
  356. } catch (PDOException $e) {
  357. return self::fallbackNavItems();
  358. }
  359. ​
  360. if (empty($rows)) {
  361. return self::fallbackNavItems();
  362. }
  363. ​
  364. $items = [];
  365. $navTitles = Languages::titles('nav', array_map('intval', array_column($rows, 'id')));
  366. foreach ($rows as $row) {
  367. if ($row['item_type'] === 'category') {
  368. $statement = Database::site()->prepare(
  369. 'SELECT id, name, slug FROM categories WHERE id = :id AND show_in_menu = 1 LIMIT 1'
  370. );
  371. $statement->execute(['id' => $row['ref_id']]);
  372. $category = $statement->fetch();
  373. if (!$category) {
  374. continue;
  375. }
  376. $category = Languages::categories([$category])[0];
  377. $items[] = [
  378. 'label' => $navTitles[(int) $row['id']] ?? ($row['label'] !== null && $row['label'] !== '' ? $row['label'] : $category['name']),
  379. 'url' => 'category.php?slug=' . urlencode($category['slug']),
  380. 'target' => '_self',
  381. 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
  382. ];
  383. continue;
  384. }
  385. ​
  386. if ($row['item_type'] === 'page') {
  387. $statement = Database::site()->prepare(
  388. "SELECT id, title, slug FROM pages WHERE id = :id AND show_in_menu = 1 AND status = 'published' LIMIT 1"
  389. );
  390. $statement->execute(['id' => $row['ref_id']]);
  391. $page = $statement->fetch();
  392. if (!$page) {
  393. continue;
  394. }
  395. $page = Languages::pages([$page])[0];
  396. $items[] = [
  397. 'label' => $navTitles[(int) $row['id']] ?? ($row['label'] !== null && $row['label'] !== '' ? $row['label'] : $page['title']),
  398. 'url' => self::pageUrl((string) $page['slug']),
  399. 'target' => '_self',
  400. 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
  401. ];
  402. continue;
  403. }
  404. ​
  405. if ($row['item_type'] === 'custom') {
  406. if (empty($row['label']) || empty($row['url'])) {
  407. continue;
  408. }
  409. $items[] = [
  410. 'label' => $navTitles[(int) $row['id']] ?? $row['label'],
  411. 'url' => $row['url'],
  412. 'target' => $row['target'] === '_blank' ? '_blank' : '_self',
  413. 'icon_html' => self::navItemIconHtml($row['icon_key'] ?? null, $row['icon_svg'] ?? null),
  414. ];
  415. }
  416. }
  417. ​
  418. return $items;
  419. }
  420. ​
  421. public static function appendToCustomNav(string $itemType, int $refId): void
  422. {
  423. if ($refId <= 0 || !in_array($itemType, ['category', 'page'], true)) {
  424. return;
  425. }
  426. ​
  427. try {
  428. $db = Database::site();
  429. if ((int) $db->query('SELECT COUNT(*) FROM nav_items')->fetchColumn() === 0) {
  430. return;
  431. }
  432. ​
  433. $existing = $db->prepare('SELECT id FROM nav_items WHERE item_type = :type AND ref_id = :ref_id LIMIT 1');
  434. $existing->execute(['type' => $itemType, 'ref_id' => $refId]);
  435. if ($existing->fetch()) {
  436. return;
  437. }
  438. ​
  439. $next = (int) $db->query('SELECT COALESCE(MAX(sort_order), -1) + 1 FROM nav_items')->fetchColumn();
  440. $db->prepare('INSERT INTO nav_items (item_type, ref_id, sort_order) VALUES (:type, :ref_id, :sort_order)')
  441. ->execute(['type' => $itemType, 'ref_id' => $refId, 'sort_order' => $next]);
  442. } catch (PDOException $e) {
  443. error_log('Publisium: could not add ' . $itemType . ' #' . $refId . ' to the menu: ' . $e->getMessage());
  444. }
  445. }
  446. ​
  447. private static function navItemIconHtml(?string $iconKey, ?string $iconSvg): string
  448. {
  449. if ($iconKey === 'custom' && !empty($iconSvg)) {
  450. return '<span class="nav-item-icon" aria-hidden="true">' . $iconSvg . '</span>';
  451. }
  452. ​
  453. if (!empty($iconKey) && Icons::isNavIcon($iconKey)) {
  454. return Icons::icon($iconKey, 'icon icon-sm nav-item-icon');
  455. }
  456. ​
  457. return '';
  458. }
  459. ​
  460. private static function fallbackNavItems(): array
  461. {
  462. $items = [];
  463. ​
  464. $categories = Database::site()->query(
  465. 'SELECT id, name, slug FROM categories WHERE show_in_menu = 1 ORDER BY sort_order ASC, name ASC'
  466. )->fetchAll();
  467. $categories = Languages::categories($categories);
  468. foreach ($categories as $category) {
  469. $items[] = [
  470. 'label' => $category['name'],
  471. 'url' => 'category.php?slug=' . urlencode($category['slug']),
  472. 'target' => '_self',
  473. ];
  474. }
  475. ​
  476. try {
  477. $pages = Database::site()->query(
  478. "SELECT id, title, slug FROM pages WHERE show_in_menu = 1 AND status = 'published' ORDER BY sort_order ASC, title ASC"
  479. )->fetchAll();
  480. } catch (PDOException $e) {
  481. $pages = [];
  482. }
  483. $pages = Languages::pages($pages);
  484. foreach ($pages as $page) {
  485. $items[] = [
  486. 'label' => $page['title'],
  487. 'url' => self::pageUrl((string) $page['slug']),
  488. 'target' => '_self',
  489. ];
  490. }
  491. ​
  492. return $items;
  493. }
  494. ​
  495. public static function renderSearchControl(string $context): string
  496. {
  497. $settings = self::settings();
  498. ​
  499. if ($settings['search_enabled'] !== '1') {
  500. return '';
  501. }
  502. ​
  503. $placementKey = $context === 'footer' ? 'search_show_in_footer' : 'search_show_in_nav';
  504. if (($settings[$placementKey] ?? '0') !== '1') {
  505. return '';
  506. }
  507. ​
  508. $searchLabel = Language::get('nav_search', 'Search');
  509. $searchPlaceholder = Language::get('search_placeholder', 'Search');
  510. $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>';
  511. ​
  512. if ($settings['search_style'] === 'field') {
  513. return '<form action="search.php" method="get" class="site-search-form site-search-form-' . htmlspecialchars($context, ENT_QUOTES)
  514. . '" role="search">'
  515. . '<span class="site-search-form-icon">' . $magnifierSvg . '</span>'
  516. . '<input type="text" name="q" class="site-search-input" placeholder="' . htmlspecialchars($searchPlaceholder, ENT_QUOTES) . '" aria-label="' . htmlspecialchars($searchLabel, ENT_QUOTES) . '">'
  517. . '</form>';
  518. }
  519. ​
  520. return '<a href="search.php" class="site-search-icon-link" aria-label="' . htmlspecialchars($searchLabel, ENT_QUOTES) . '">' . $magnifierSvg . '</a>';
  521. }
  522. ​
  523. public static function renderShareControl(array $article): string
  524. {
  525. $settings = self::settings();
  526. if (($settings['share_enabled'] ?? '0') !== '1') {
  527. return '';
  528. }
  529. ​
  530. $url = self::currentUrl();
  531. $encodedUrl = urlencode($url);
  532. $encodedTitle = urlencode((string) ($article['title'] ?? ''));
  533. ​
  534. $platformDefs = [
  535. 'facebook' => [
  536. 'label' => Language::get('share_facebook', 'Facebook'),
  537. 'url' => 'https://www.facebook.com/sharer/sharer.php?u=' . $encodedUrl,
  538. 'svg' => SocialIcons::builtinSvg('facebook'),
  539. ],
  540. 'twitter' => [
  541. 'label' => Language::get('share_twitter', 'Twitter / X'),
  542. 'url' => 'https://twitter.com/intent/tweet?url=' . $encodedUrl . '&text=' . $encodedTitle,
  543. 'svg' => SocialIcons::builtinSvg('twitter'),
  544. ],
  545. 'linkedin' => [
  546. 'label' => Language::get('share_linkedin', 'LinkedIn'),
  547. 'url' => 'https://www.linkedin.com/sharing/share-offsite/?url=' . $encodedUrl,
  548. 'svg' => SocialIcons::builtinSvg('linkedin'),
  549. ],
  550. 'whatsapp' => [
  551. 'label' => Language::get('share_whatsapp', 'WhatsApp'),
  552. 'url' => 'https://wa.me/?text=' . $encodedTitle . '%20' . $encodedUrl,
  553. '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>',
  554. ],
  555. 'telegram' => [
  556. 'label' => Language::get('share_telegram', 'Telegram'),
  557. 'url' => 'https://t.me/share/url?url=' . $encodedUrl . '&text=' . $encodedTitle,
  558. '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>',
  559. ],
  560. 'email' => [
  561. 'label' => Language::get('share_email', 'Email'),
  562. 'url' => 'mailto:?subject=' . $encodedTitle . '&body=' . $encodedUrl,
  563. '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>',
  564. ],
  565. ];
  566. ​
  567. $platforms = [];
  568. foreach ($platformDefs as $key => $platform) {
  569. if (($settings['share_' . $key] ?? '0') === '1') {
  570. $platforms[$key] = $platform;
  571. }
  572. }
  573. ​
  574. $copyLinkEnabled = ($settings['share_copy_link'] ?? '0') === '1';
  575. if (empty($platforms) && !$copyLinkEnabled) {
  576. return '';
  577. }
  578. ​
  579. $shareLabel = Language::get('article_share', 'Share');
  580. $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>';
  581. ​
  582. $html = '<div class="article-share">';
  583. $html .= '<button type="button" class="share-toggle-btn" id="share-toggle-btn" aria-expanded="false" aria-haspopup="true">' . $shareSvg . '<span>' . htmlspecialchars($shareLabel) . '</span></button>';
  584. $html .= '<div class="share-panel" id="share-panel">';
  585. ​
  586. foreach ($platforms as $key => $platform) {
  587. $html .= '<a href="' . htmlspecialchars($platform['url'], ENT_QUOTES) . '" class="share-panel-item" target="_blank" rel="noopener noreferrer">'
  588. . '<span class="share-panel-item-icon share-panel-item-icon-' . htmlspecialchars($key, ENT_QUOTES) . '" aria-hidden="true">' . $platform['svg'] . '</span>'
  589. . '<span>' . htmlspecialchars($platform['label']) . '</span>'
  590. . '</a>';
  591. }
  592. ​
  593. if ($copyLinkEnabled) {
  594. $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>';
  595. $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) . '">'
  596. . '<span class="share-panel-item-icon" aria-hidden="true">' . $linkSvg . '</span>'
  597. . '<span class="js-share-copy-label">' . htmlspecialchars(Language::get('share_copy_link', 'Copy link')) . '</span>'
  598. . '</button>';
  599. }
  600. ​
  601. $html .= '</div></div>';
  602. ​
  603. return $html;
  604. }
  605. ​
  606. public static function menuPages(): array
  607. {
  608. return Database::site()->query(
  609. "SELECT title, slug FROM pages WHERE status = 'published' AND show_in_menu = 1 ORDER BY sort_order ASC, title ASC"
  610. )->fetchAll();
  611. }
  612. ​
  613. public static function categories(): array
  614. {
  615. return Database::site()->query('SELECT id, name, slug FROM categories ORDER BY sort_order ASC, name ASC')->fetchAll();
  616. }
  617. ​
  618. public static function activeAds(string $placement): array
  619. {
  620. $statement = Database::site()->prepare(
  621. 'SELECT * FROM ads WHERE is_active = 1 AND placement = :placement ORDER BY created_at DESC'
  622. );
  623. $statement->execute(['placement' => $placement]);
  624. ​
  625. return array_values(array_filter($statement->fetchAll(), static fn(array $ad): bool => self::adFitsVisitor($ad)));
  626. }
  627. ​
  628. private static function adFitsVisitor(array $ad): bool
  629. {
  630. $audience = (string) ($ad['audience'] ?? 'all');
  631. ​
  632. // "Hide from paying subscribers" would contradict an ad meant only for subscribers, so it's ignored there.
  633. if ($audience !== 'paid' && (int) ($ad['hide_for_subscribers'] ?? 0) === 1 && self::visitorHasSubscription()) {
  634. return false;
  635. }
  636. ​
  637. if ($audience !== 'all') {
  638. $loggedIn = class_exists('UserAuth') && UserAuth::check();
  639. if (($audience === 'guests' && $loggedIn) || ($audience === 'members' && !$loggedIn)) {
  640. return false;
  641. }
  642. if (($audience === 'paid' && !self::visitorHasSubscription()) || ($audience === 'unpaid' && self::visitorHasSubscription())) {
  643. return false;
  644. }
  645. }
  646. ​
  647. $context = self::$adContext;
  648. if ($context['type'] === '') {
  649. return true;
  650. }
  651. ​
  652. $excluded = self::adExclusions($ad);
  653. if ($context['type'] === 'home') {
  654. return !$excluded['home'];
  655. }
  656. if ($context['type'] === 'article') {
  657. return !in_array($context['id'], $excluded['articles'], true);
  658. }
  659. if ($context['type'] === 'page') {
  660. return !in_array($context['id'], $excluded['pages'], true);
  661. }
  662. ​
  663. return true;
  664. }
  665. ​
  666. private static ?bool $visitorHasSubscription = null;
  667. ​
  668. public static function visitorHasSubscription(): bool
  669. {
  670. if (self::$visitorHasSubscription !== null) {
  671. return self::$visitorHasSubscription;
  672. }
  673. ​
  674. self::$visitorHasSubscription = false;
  675. if (!class_exists('UserAuth') || !UserAuth::check()) {
  676. return false;
  677. }
  678. ​
  679. try {
  680. $reader = UserAuth::user();
  681. self::$visitorHasSubscription = $reader !== null && UserAuth::hasActiveSubscription((int) $reader['id']);
  682. } catch (PDOException $e) {
  683. error_log('Publisium: could not check the reader subscription for ads: ' . $e->getMessage());
  684. }
  685. ​
  686. return self::$visitorHasSubscription;
  687. }
  688. ​
  689. public static function renderAd(array $ad): string
  690. {
  691. switch ($ad['type']) {
  692. case 'static_text':
  693. $html = '<div class="ad-slot ad-text">' . nl2br(htmlspecialchars($ad['content'])) . '</div>';
  694. break;
  695. case 'static_image':
  696. $img = '<img src="' . htmlspecialchars($ad['content']) . '" alt="' . htmlspecialchars($ad['name']) . '">';
  697. $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>';
  698. break;
  699. case 'script':
  700. $html = '<div class="ad-slot ad-script" data-requires-consent="0">' . $ad['content'] . '</div>';
  701. break;
  702. default:
  703. $html = '';
  704. }
  705. ​
  706. // With consent required, the ad waits in an inert <template> inside its slot until site.js gets consent.
  707. $consent = (string) ($ad['consent_category'] ?? 'none');
  708. if ($html !== '' && $consent !== 'none' && array_key_exists($consent, self::AD_CONSENTS) && self::settings()['consent_manager_enabled'] === '1') {
  709. $open = strpos($html, '>') + 1;
  710. $close = strrpos($html, '</div>');
  711. $inner = str_ireplace('</template', '<\/template', substr($html, $open, $close - $open));
  712. $html = substr($html, 0, $open)
  713. . '<template class="consent-gated" data-consent-category="' . implode(' ', self::scriptConsentCategories($consent)) . '">' . $inner . '</template>'
  714. . '</div>';
  715. }
  716. ​
  717. return $html;
  718. }
  719. ​
  720. public static function activeAnalyticsScripts(string $placement): array
  721. {
  722. $statement = Database::site()->prepare(
  723. 'SELECT * FROM analytics_scripts WHERE is_active = 1 AND placement = :placement ORDER BY created_at ASC'
  724. );
  725. $statement->execute(['placement' => $placement]);
  726. return $statement->fetchAll();
  727. }
  728. ​
  729. public const CONSENT_CATEGORIES = ['analytics', 'marketing'];
  730. ​
  731. public const CONSENT_SHOW = [
  732. 'auto' => 'Show it when a script, an ad or the comments need it (recommended)',
  733. 'always' => 'Always show it',
  734. 'never' => 'Never show it (code that needs it won’t run)',
  735. ];
  736. ​
  737. // Optional consent categories that something active on the site waits for.
  738. public static function consentNeededCategories(): array
  739. {
  740. $needed = [];
  741. try {
  742. $rows = Database::site()->query('SELECT DISTINCT consent_category FROM analytics_scripts WHERE is_active = 1 AND requires_consent = 1')->fetchAll(PDO::FETCH_COLUMN);
  743. foreach ($rows as $category) {
  744. $needed = array_merge($needed, self::scriptConsentCategories((string) $category));
  745. }
  746. } catch (PDOException $exception) {
  747. }
  748. ​
  749. try {
  750. $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);
  751. foreach ($rows as $category) {
  752. $needed = array_merge($needed, self::scriptConsentCategories((string) $category));
  753. }
  754. } catch (PDOException $exception) {
  755. }
  756. ​
  757. $settings = self::settings();
  758. if ($settings['comments_enabled'] === '1' && $settings['comments_provider'] !== 'builtin' && in_array($settings['comments_consent'], self::CONSENT_CATEGORIES, true)) {
  759. require_once __DIR__ . '/comments.php';
  760. if (Comments::isConfigured($settings)) {
  761. $needed[] = $settings['comments_consent'];
  762. }
  763. }
  764. ​
  765. return array_values(array_intersect(self::CONSENT_CATEGORIES, $needed));
  766. }
  767. ​
  768. // The optional categories the cookie banner offers. Empty means the banner isn't shown at all.
  769. public static function consentCategories(): array
  770. {
  771. $settings = self::settings();
  772. if ($settings['consent_manager_enabled'] !== '1') {
  773. return [];
  774. }
  775. ​
  776. $needed = null;
  777. $visible = [];
  778. foreach (self::CONSENT_CATEGORIES as $category) {
  779. $mode = $settings['consent_show_' . $category] ?? 'auto';
  780. if ($mode === 'auto') {
  781. $needed ??= self::consentNeededCategories();
  782. $show = in_array($category, $needed, true);
  783. } else {
  784. $show = $mode === 'always';
  785. }
  786. if ($show) {
  787. $visible[] = $category;
  788. }
  789. }
  790. ​
  791. return $visible;
  792. }
  793. ​
  794. public static function scriptConsentCategories(string $category): array
  795. {
  796. return match ($category) {
  797. 'marketing' => ['marketing'],
  798. 'both' => ['analytics', 'marketing'],
  799. default => ['analytics'],
  800. };
  801. }
  802. ​
  803. public static function renderAnalyticsScripts(string $placement): string
  804. {
  805. $scripts = self::activeAnalyticsScripts($placement);
  806. $consentManagerEnabled = self::settings()['consent_manager_enabled'] === '1';
  807. $html = '';
  808. ​
  809. foreach ($scripts as $script) {
  810. $code = $script['script_code'];
  811. ​
  812. $looksLikeHtml = str_contains($code, '<script') || str_contains($code, '<style') || str_contains($code, '<link') || str_contains($code, '<noscript');
  813. ​
  814. if (!$looksLikeHtml) {
  815. $code = '<script>' . $code . '</script>';
  816. }
  817. ​
  818. if ($script['requires_consent'] && $consentManagerEnabled) {
  819. $safeCode = str_replace('</script>', '<\/script>', $code);
  820. $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>';
  821. } else {
  822. $html .= $code;
  823. }
  824. }
  825. ​
  826. return $html;
  827. }
  828. ​
  829. public static function renderFontFaces(): string
  830. {
  831. require_once __DIR__ . '/font-library.php';
  832. ​
  833. $settings = self::settings();
  834. $emitted = [];
  835. $css = '';
  836. ​
  837. foreach ([$settings['heading_font'], $settings['body_font'], $settings['interface_font']] as $fontName) {
  838. if ($fontName === '' || in_array($fontName, $emitted, true)) {
  839. continue;
  840. }
  841. $css .= FontLibrary::fontFaceCss($fontName, $fontName);
  842. $emitted[] = $fontName;
  843. }
  844. ​
  845. return $css;
  846. }
  847. ​
  848. public static function fontVariablesCss(): string
  849. {
  850. $settings = self::settings();
  851. $headingFamily = addslashes($settings['heading_font']);
  852. $bodyFamily = addslashes($settings['body_font']);
  853. $interfaceFamily = addslashes($settings['interface_font']);
  854. ​
  855. return ":root{"
  856. . "--font-heading:\"{$headingFamily}\", -apple-system, BlinkMacSystemFont, sans-serif;"
  857. . "--font-body:\"{$bodyFamily}\", Georgia, serif;"
  858. . "--font-ui:\"{$interfaceFamily}\", -apple-system, BlinkMacSystemFont, sans-serif;"
  859. . "}";
  860. }
  861. ​
  862. private const TRACKING_PARAMS = ['fbclid', 'gclid', 'msclkid', 'yclid', 'igshid', 'mc_cid', 'mc_eid', '_ga', 'ref_src'];
  863. ​
  864. private static function configuredUrl(): string
  865. {
  866. $url = trim((string) Config::get('APP_URL', ''));
  867. if ($url === '') {
  868. return '';
  869. }
  870. ​
  871. if (!preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
  872. $url = 'https://' . $url;
  873. }
  874. ​
  875. return rtrim($url, '/');
  876. }
  877. ​
  878. private static function normalizeHost(string $host, string $scheme = ''): string
  879. {
  880. $host = strtolower(rtrim(trim($host), '.'));
  881. if ($host === '') {
  882. return '';
  883. }
  884. ​
  885. $port = '';
  886. if (preg_match('/^(.*):(\d+)$/', $host, $matches) && !str_ends_with($matches[1], ']')) {
  887. $host = $matches[1];
  888. $port = $matches[2];
  889. } elseif (preg_match('/^(\[.*\]):(\d+)$/', $host, $matches)) {
  890. $host = $matches[1];
  891. $port = $matches[2];
  892. }
  893. ​
  894. $defaultPorts = ['80', '443'];
  895. if ($scheme === 'http') {
  896. $defaultPorts = ['80'];
  897. } elseif ($scheme === 'https') {
  898. $defaultPorts = ['443'];
  899. }
  900. ​
  901. return in_array($port, $defaultPorts, true) || $port === '' ? $host : $host . ':' . $port;
  902. }
  903. ​
  904. private static function requestHost(): string
  905. {
  906. $forwarded = trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_HOST'] ?? ''))[0]);
  907. $host = $forwarded !== '' ? $forwarded : (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '');
  908. ​
  909. return self::normalizeHost($host);
  910. }
  911. ​
  912. private static function requestScheme(): string
  913. {
  914. $forwarded = strtolower(trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''))[0]));
  915. if ($forwarded === 'https' || $forwarded === 'http') {
  916. return $forwarded;
  917. }
  918. ​
  919. $https = strtolower((string) ($_SERVER['HTTPS'] ?? ''));
  920. if (($https !== '' && $https !== 'off') || (string) ($_SERVER['SERVER_PORT'] ?? '') === '443') {
  921. return 'https';
  922. }
  923. ​
  924. return 'http';
  925. }
  926. ​
  927. public static function isConfiguredHost(): bool
  928. {
  929. $configured = self::configuredUrl();
  930. if ($configured === '') {
  931. return true;
  932. }
  933. ​
  934. $parts = parse_url($configured);
  935. $configuredHost = self::normalizeHost((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''), (string) ($parts['scheme'] ?? ''));
  936. $currentHost = self::requestHost();
  937. ​
  938. if ($configuredHost === '' || $currentHost === '') {
  939. return true;
  940. }
  941. ​
  942. return $configuredHost === $currentHost;
  943. }
  944. ​
  945. private static function cleanRequestUri(): string
  946. {
  947. $uri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
  948. $path = (string) parse_url($uri, PHP_URL_PATH);
  949. $query = (string) parse_url($uri, PHP_URL_QUERY);
  950. ​
  951. if ($path === '') {
  952. $path = '/';
  953. }
  954. ​
  955. if (self::cleanHomeUrl() && str_ends_with($path, '/index.php')) {
  956. $path = substr($path, 0, -strlen('index.php'));
  957. }
  958. ​
  959. if ($query === '') {
  960. return $path;
  961. }
  962. ​
  963. $kept = [];
  964. foreach (explode('&', $query) as $pair) {
  965. if ($pair === '') {
  966. continue;
  967. }
  968. $name = strtolower(urldecode(explode('=', $pair, 2)[0]));
  969. if (str_starts_with($name, 'utm_') || in_array($name, self::TRACKING_PARAMS, true)) {
  970. continue;
  971. }
  972. $kept[] = $pair;
  973. }
  974. ​
  975. return $kept === [] ? $path : $path . '?' . implode('&', $kept);
  976. }
  977. ​
  978. public static function currentUrl(): string
  979. {
  980. $baseUrl = self::configuredUrl();
  981. if ($baseUrl === '') {
  982. $host = self::requestHost();
  983. $baseUrl = $host === '' ? '' : self::requestScheme() . '://' . $host;
  984. }
  985. ​
  986. return $baseUrl . self::cleanRequestUri();
  987. }
  988. ​
  989. public static function renderSeoMeta(): string
  990. {
  991. $settings = self::settings();
  992. $html = '';
  993. ​
  994. if ($settings['seo_keywords'] !== '') {
  995. $html .= '<meta name="keywords" content="' . htmlspecialchars($settings['seo_keywords'], ENT_QUOTES) . '">' . "\n";
  996. }
  997. ​
  998. if ($settings['seo_author'] !== '') {
  999. $html .= '<meta name="author" content="' . htmlspecialchars($settings['seo_author'], ENT_QUOTES) . '">' . "\n";
  1000. }
  1001. ​
  1002. if ($settings['seo_reply_to'] !== '') {
  1003. $html .= '<meta name="reply-to" content="' . htmlspecialchars($settings['seo_reply_to'], ENT_QUOTES) . '">' . "\n";
  1004. }
  1005. ​
  1006. if ($settings['seo_application_name'] !== '') {
  1007. $html .= '<meta name="application-name" content="' . htmlspecialchars($settings['seo_application_name'], ENT_QUOTES) . '">' . "\n";
  1008. }
  1009. ​
  1010. $robotsIndex = $settings['seo_robots_index'] === '1' && self::isConfiguredHost() ? 'index' : 'noindex';
  1011. $robotsFollow = $settings['seo_robots_follow'] === '1' ? 'follow' : 'nofollow';
  1012. $html .= '<meta name="robots" content="' . $robotsIndex . ',' . $robotsFollow . '">' . "\n";
  1013. ​
  1014. $html .= '<link rel="canonical" href="' . htmlspecialchars(self::currentUrl(), ENT_QUOTES) . '">';
  1015. ​
  1016. return $html;
  1017. }
  1018. ​
  1019. public static function renderOpenGraph(string $title, string $description, string $type = 'website', ?string $imagePath = null, ?array $articleMeta = null): string
  1020. {
  1021. $settings = self::settings();
  1022. ​
  1023. $html = '<meta property="og:title" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
  1024. $html .= '<meta property="og:type" content="' . htmlspecialchars($type, ENT_QUOTES) . '">' . "\n";
  1025. $html .= '<meta property="og:url" content="' . htmlspecialchars(self::currentUrl(), ENT_QUOTES) . '">' . "\n";
  1026. $html .= '<meta property="og:site_name" content="' . htmlspecialchars($settings['site_name'], ENT_QUOTES) . '">' . "\n";
  1027. ​
  1028. if ($description !== '') {
  1029. $html .= '<meta property="og:description" content="' . htmlspecialchars($description, ENT_QUOTES) . '">' . "\n";
  1030. }
  1031. ​
  1032. $ogImage = null;
  1033. if ($imagePath !== null && $settings['seo_og_article_image_enabled'] === '1') {
  1034. $ogImage = $imagePath;
  1035. } elseif ($settings['site_logo_url'] !== '') {
  1036. $ogImage = $settings['site_logo_url'];
  1037. }
  1038. $ogImage = $ogImage !== null ? self::absoluteUrl($ogImage) : '';
  1039. ​
  1040. if ($ogImage !== '') {
  1041. $html .= '<meta property="og:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES) . '">' . "\n";
  1042. }
  1043. ​
  1044. if ($settings['seo_social_tags_enabled'] === '1') {
  1045. $html .= '<meta property="og:locale" content="' . htmlspecialchars(str_replace('-', '_', Languages::htmlLang()), ENT_QUOTES) . '">' . "\n";
  1046. ​
  1047. if ($ogImage !== '') {
  1048. $html .= '<meta property="og:image:alt" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
  1049. }
  1050. ​
  1051. $published = self::isoDate($articleMeta['published'] ?? null);
  1052. $modified = self::isoDate($articleMeta['modified'] ?? null);
  1053. if ($published !== null) {
  1054. $html .= '<meta property="article:published_time" content="' . $published . '">' . "\n";
  1055. }
  1056. if ($modified !== null) {
  1057. $html .= '<meta property="article:modified_time" content="' . $modified . '">' . "\n";
  1058. }
  1059. if (!empty($articleMeta['author'])) {
  1060. $html .= '<meta property="article:author" content="' . htmlspecialchars((string) $articleMeta['author'], ENT_QUOTES) . '">' . "\n";
  1061. }
  1062. if (!empty($articleMeta['section'])) {
  1063. $html .= '<meta property="article:section" content="' . htmlspecialchars((string) $articleMeta['section'], ENT_QUOTES) . '">' . "\n";
  1064. }
  1065. ​
  1066. $html .= '<meta name="twitter:card" content="' . ($ogImage !== '' ? 'summary_large_image' : 'summary') . '">' . "\n";
  1067. $html .= '<meta name="twitter:title" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
  1068. if ($description !== '') {
  1069. $html .= '<meta name="twitter:description" content="' . htmlspecialchars($description, ENT_QUOTES) . '">' . "\n";
  1070. }
  1071. if ($ogImage !== '') {
  1072. $html .= '<meta name="twitter:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES) . '">' . "\n";
  1073. $html .= '<meta name="twitter:image:alt" content="' . htmlspecialchars($title, ENT_QUOTES) . '">' . "\n";
  1074. }
  1075. if ($settings['seo_twitter_handle'] !== '') {
  1076. $html .= '<meta name="twitter:site" content="' . htmlspecialchars($settings['seo_twitter_handle'], ENT_QUOTES) . '">' . "\n";
  1077. }
  1078. }
  1079. ​
  1080. return rtrim($html, "\n");
  1081. }
  1082. ​
  1083. public static function renderArticleSchema(array $article, string $authorType, ?string $authorUrl): string
  1084. {
  1085. $settings = self::settings();
  1086. $homeUrl = self::absoluteUrl(self::homeUrl());
  1087. ​
  1088. $schema = [
  1089. '@context' => 'https://schema.org',
  1090. '@type' => 'NewsArticle',
  1091. 'mainEntityOfPage' => ['@type' => 'WebPage', '@id' => self::currentUrl()],
  1092. 'headline' => (string) $article['title'],
  1093. ];
  1094. ​
  1095. $description = (string) (($article['seo_description'] ?? '') ?: ($article['excerpt'] ?? ''));
  1096. if ($description !== '') {
  1097. $schema['description'] = $description;
  1098. }
  1099. ​
  1100. $image = !empty($article['cover_image_path']) ? (string) $article['cover_image_path'] : $settings['site_logo_url'];
  1101. if ($image !== '') {
  1102. $schema['image'] = [self::absoluteUrl($image)];
  1103. }
  1104. ​
  1105. $published = self::isoDate($article['published_at'] ?? null);
  1106. $modified = self::isoDate($article['updated_at'] ?? null);
  1107. if ($published !== null) {
  1108. $schema['datePublished'] = $published;
  1109. $schema['dateModified'] = $modified !== null && $modified > $published ? $modified : $published;
  1110. }
  1111. ​
  1112. $authorName = trim((string) ($article['author_name'] ?? ''));
  1113. if ($authorName !== '') {
  1114. $author = ['@type' => $authorType === 'Organization' ? 'Organization' : 'Person', 'name' => $authorName];
  1115. if ($authorUrl !== null && $authorUrl !== '') {
  1116. $author['url'] = self::absoluteUrl($authorUrl);
  1117. }
  1118. } else {
  1119. $author = ['@type' => 'Organization', 'name' => $settings['site_name'], 'url' => $homeUrl];
  1120. }
  1121. $schema['author'] = [$author];
  1122. ​
  1123. $publisher = ['@type' => 'Organization', 'name' => $settings['site_name'], 'url' => $homeUrl];
  1124. if ($settings['site_logo_url'] !== '') {
  1125. $publisher['logo'] = ['@type' => 'ImageObject', 'url' => self::absoluteUrl($settings['site_logo_url'])];
  1126. }
  1127. $schema['publisher'] = $publisher;
  1128. ​
  1129. if (($article['access_type'] ?? 'free') === 'paid') {
  1130. $schema['isAccessibleForFree'] = false;
  1131. }
  1132. ​
  1133. return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) . '</script>';
  1134. }
  1135. ​
  1136. public static function absoluteUrl(string $url): string
  1137. {
  1138. $url = trim($url);
  1139. if ($url === '' || preg_match('#^https?://#i', $url) === 1) {
  1140. return $url;
  1141. }
  1142. ​
  1143. if (str_starts_with($url, '//')) {
  1144. return self::requestScheme() . ':' . $url;
  1145. }
  1146. ​
  1147. $origin = self::configuredUrl();
  1148. if ($origin === '') {
  1149. $host = self::requestHost();
  1150. $origin = $host === '' ? '' : self::requestScheme() . '://' . $host;
  1151. }
  1152. ​
  1153. if (str_starts_with($url, '/')) {
  1154. return $origin . $url;
  1155. }
  1156. ​
  1157. return $origin . rtrim((string) Config::get('APP_BASE_PATH', ''), '/') . '/' . $url;
  1158. }
  1159. ​
  1160. private static function isoDate(?string $value): ?string
  1161. {
  1162. if ($value === null || $value === '') {
  1163. return null;
  1164. }
  1165. ​
  1166. $timestamp = strtotime($value);
  1167. ​
  1168. return $timestamp === false ? null : date(DATE_ATOM, $timestamp);
  1169. }
  1170. ​
  1171. public static function renderOrganizationSchema(): string
  1172. {
  1173. $settings = self::settings();
  1174. ​
  1175. $schema = [
  1176. '@context' => 'https://schema.org',
  1177. '@graph' => [
  1178. [
  1179. '@type' => 'Organization',
  1180. 'name' => $settings['site_name'],
  1181. 'url' => rtrim(Config::get('APP_URL', ''), '/') . '/',
  1182. ],
  1183. [
  1184. '@type' => 'WebSite',
  1185. 'name' => $settings['site_name'],
  1186. 'url' => rtrim(Config::get('APP_URL', ''), '/') . '/',
  1187. ],
  1188. ],
  1189. ];
  1190. ​
  1191. if ($settings['site_logo_url'] !== '') {
  1192. $schema['@graph'][0]['logo'] = self::absoluteUrl($settings['site_logo_url']);
  1193. }
  1194. ​
  1195. if ($settings['site_description'] !== '') {
  1196. $schema['@graph'][1]['description'] = $settings['site_description'];
  1197. }
  1198. ​
  1199. return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) . '</script>';
  1200. }
  1201. ​
  1202. private static function isCustomHtmlEnabledFor(string $slot, ?string $pageType): bool
  1203. {
  1204. if ($pageType === null || !in_array($pageType, ['index', 'article', 'category', 'pages'], true)) {
  1205. return false;
  1206. }
  1207. ​
  1208. $settings = self::settings();
  1209. $key = 'custom_' . $slot . '_html_' . $pageType;
  1210. ​
  1211. return ($settings[$key] ?? '0') === '1';
  1212. }
  1213. ​
  1214. public static function renderCustomHeadHtml(?string $pageType): string
  1215. {
  1216. if (!self::isCustomHtmlEnabledFor('head', $pageType)) {
  1217. return '';
  1218. }
  1219. ​
  1220. return self::settings()['custom_head_html'];
  1221. }
  1222. ​
  1223. public static function renderCustomBodyHtml(?string $pageType): string
  1224. {
  1225. if (!self::isCustomHtmlEnabledFor('body', $pageType)) {
  1226. return '';
  1227. }
  1228. ​
  1229. return self::settings()['custom_body_html'];
  1230. }
  1231. }
  1232. ​