WebOrbiton
v2.0.0.0

Publisium

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