WebOrbiton
v1.0.0.6

Publisium

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