WebOrbiton
v3.1.0.0

FlatlyPage

895 lines · 29.6 KB
  1. <?php
  2. define('BASE_DIR', __DIR__);
  3. ​
  4. function flatly_detect_base_url(): string
  5. {
  6. $override = __DIR__ . '/data/base-url.txt';
  7. if (is_file($override)) {
  8. $base = trim((string) @file_get_contents($override));
  9. } else {
  10. $root = str_replace('\\', '/', (string) realpath(__DIR__));
  11. $scriptFile = str_replace('\\', '/', (string) realpath($_SERVER['SCRIPT_FILENAME'] ?? ''));
  12. $scriptName = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
  13. $base = null;
  14. ​
  15. if ($root !== '' && $scriptFile !== '' && stripos($scriptFile, $root . '/') === 0) {
  16. $relative = substr($scriptFile, strlen($root));
  17. $length = strlen($relative);
  18. if (strlen($scriptName) >= $length && strcasecmp(substr($scriptName, -$length), $relative) === 0) {
  19. $base = substr($scriptName, 0, strlen($scriptName) - $length);
  20. }
  21. }
  22. ​
  23. if ($base === null) {
  24. $docRoot = str_replace('\\', '/', (string) realpath($_SERVER['DOCUMENT_ROOT'] ?? ''));
  25. $base = ($docRoot !== '' && stripos($root, $docRoot) === 0) ? substr($root, strlen($docRoot)) : '';
  26. }
  27. }
  28. ​
  29. $base = '/' . trim((string) $base, '/');
  30. if ($base === '/' || !preg_match('#^(/[A-Za-z0-9._~\-]+)+$#', $base)) {
  31. return '';
  32. }
  33. return $base;
  34. }
  35. ​
  36. define('BASE_URL', flatly_detect_base_url());
  37. ​
  38. function flatly_rewrite_urls(string $html): string
  39. {
  40. if (BASE_URL === '' || $html === '') {
  41. return $html;
  42. }
  43. ​
  44. $base = BASE_URL;
  45. $prefix = static function (string $path) use ($base): string {
  46. if ($path === '' || $path[0] !== '/' || (isset($path[1]) && $path[1] === '/')) {
  47. return $path;
  48. }
  49. if ($path === $base) {
  50. return $path;
  51. }
  52. foreach (['/', '?', '#'] as $next) {
  53. if (strpos($path, $base . $next) === 0) {
  54. return $path;
  55. }
  56. }
  57. return $base . $path;
  58. };
  59. ​
  60. $html = preg_replace_callback(
  61. '/(\s(?:href|src|action|poster|formaction|data-src)\s*=\s*)(["\'])(\/(?!\/)[^"\']*)\2/i',
  62. static fn(array $m): string => $m[1] . $m[2] . $prefix($m[3]) . $m[2],
  63. $html
  64. ) ?? $html;
  65. ​
  66. $html = preg_replace_callback(
  67. '/(\ssrcset\s*=\s*)(["\'])([^"\']*)\2/i',
  68. static function (array $m) use ($prefix): string {
  69. $parts = array_map(static function (string $candidate) use ($prefix): string {
  70. $candidate = trim($candidate);
  71. $pieces = preg_split('/\s+/', $candidate, 2);
  72. $pieces[0] = $prefix($pieces[0]);
  73. return implode(' ', $pieces);
  74. }, explode(',', $m[3]));
  75. return $m[1] . $m[2] . implode(', ', $parts) . $m[2];
  76. },
  77. $html
  78. ) ?? $html;
  79. ​
  80. $html = preg_replace_callback(
  81. '/url\(\s*(["\']?)(\/(?!\/)[^)"\']*)\1\s*\)/i',
  82. static fn(array $m): string => 'url(' . $m[1] . $prefix($m[2]) . $m[1] . ')',
  83. $html
  84. ) ?? $html;
  85. ​
  86. $script = '<script>window.FLATLY_BASE=' . json_encode($base, JSON_UNESCAPED_SLASHES) . ';</script>';
  87. $injected = preg_replace('/<head(\s[^>]*)?>/i', '$0' . $script, $html, 1);
  88. return $injected ?? $html;
  89. }
  90. ​
  91. if (session_status() === PHP_SESSION_NONE) {
  92. if (BASE_URL !== '') {
  93. session_name('FLATLY' . substr(md5(BASE_DIR), 0, 10));
  94. session_set_cookie_params(['path' => BASE_URL . '/', 'httponly' => true, 'samesite' => 'Lax']);
  95. }
  96. session_start();
  97. }
  98. ​
  99. if (BASE_URL !== '' && PHP_SAPI !== 'cli') {
  100. ob_start(static function (string $buffer): string {
  101. foreach (headers_list() as $header) {
  102. if (stripos($header, 'content-type:') === 0 && stripos($header, 'html') === false) {
  103. return $buffer;
  104. }
  105. }
  106. return flatly_rewrite_urls($buffer);
  107. });
  108. }
  109. ​
  110. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://';
  111. $host = $_SERVER['HTTP_HOST'];
  112. ​
  113. function flatly_configured_site_url(): ?string
  114. {
  115. $file = __DIR__ . '/data/sitemap-config.php';
  116. $config = is_file($file) ? include $file : null;
  117. $value = is_array($config) ? trim((string) ($config['website_domain'] ?? '')) : '';
  118. if ($value === '') {
  119. return null;
  120. }
  121. if (!preg_match('#^https?://#i', $value)) {
  122. $value = 'https://' . $value;
  123. }
  124. $parts = parse_url($value);
  125. if (empty($parts['host'])) {
  126. return null;
  127. }
  128. $url = strtolower($parts['scheme']) . '://' . strtolower($parts['host']) . (isset($parts['port']) ? ':' . $parts['port'] : '');
  129. $path = rtrim($parts['path'] ?? '', '/');
  130. return $url . ($path !== '' ? $path : BASE_URL);
  131. }
  132. ​
  133. $configured_site_url = flatly_configured_site_url();
  134. ​
  135. define('SITE_NAME', 'FlatlyPage');
  136. define('SITE_URL', $configured_site_url ?? $protocol . $host . BASE_URL);
  137. define('DATA_DIR', __DIR__ . '/data/');
  138. ​
  139. if ($configured_site_url !== null && !headers_sent()
  140. && strcasecmp((string) preg_replace('/:\d+$/', '', $host), (string) parse_url($configured_site_url, PHP_URL_HOST)) !== 0) {
  141. header('X-Robots-Tag: noindex, nofollow');
  142. }
  143. define('ADMIN_DIR', __DIR__ . '/admin/');
  144. ​
  145. require_once __DIR__ . '/languages.php';
  146. ​
  147. define('CSRF_TOKEN_NAME', 'csrf_token');
  148. ​
  149. if (!is_dir(DATA_DIR)) {
  150. mkdir(DATA_DIR, 0755, true);
  151. }
  152. ​
  153. function generate_csrf_token(): string
  154. {
  155. if (empty($_SESSION[CSRF_TOKEN_NAME])) {
  156. $_SESSION[CSRF_TOKEN_NAME] = bin2hex(random_bytes(32));
  157. }
  158. return $_SESSION[CSRF_TOKEN_NAME];
  159. }
  160. ​
  161. function verify_csrf_token(string $token): bool
  162. {
  163. return isset($_SESSION[CSRF_TOKEN_NAME]) && hash_equals($_SESSION[CSRF_TOKEN_NAME], $token);
  164. }
  165. ​
  166. function is_logged_in(): bool
  167. {
  168. return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
  169. }
  170. ​
  171. function require_login(): void
  172. {
  173. if (!is_logged_in()) {
  174. header('Location: ' . BASE_URL . '/admin');
  175. exit;
  176. }
  177. if (!headers_sent()) {
  178. header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  179. header('Pragma: no-cache');
  180. }
  181. check_ip_ban();
  182. }
  183. ​
  184. function check_ip_ban(): void
  185. {
  186. static $tracker = null;
  187. ​
  188. if ($tracker === null) {
  189. require_once __DIR__ . '/admin/login_tracking.php';
  190. $tracker = new LoginTracker();
  191. }
  192. ​
  193. $clientIP = $tracker->getClientIP();
  194. ​
  195. if ($tracker->isIPBanned($clientIP)) {
  196. session_unset();
  197. session_destroy();
  198. ​
  199. if (isset($_COOKIE[session_name()])) {
  200. setcookie(session_name(), '', time() - 3600, session_get_cookie_params()['path']);
  201. }
  202. ​
  203. http_response_code(403);
  204. exit('Access forbidden.');
  205. }
  206. }
  207. ​
  208. function e(string $string): string
  209. {
  210. return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
  211. }
  212. ​
  213. function slugify(string $text): string
  214. {
  215. $text = preg_replace('~[^\pL\d]+~u', '-', $text);
  216. $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  217. $text = preg_replace('~[^-\w]+~', '', $text);
  218. $text = trim($text, '-');
  219. $text = preg_replace('~-+~', '-', $text);
  220. $text = strtolower($text);
  221. return empty($text) ? 'n-a' : $text;
  222. }
  223. ​
  224. function media_types(): array
  225. {
  226. return [
  227. 'image' => [
  228. 'jpg' => ['image/jpeg'],
  229. 'jpeg' => ['image/jpeg'],
  230. 'png' => ['image/png'],
  231. 'gif' => ['image/gif'],
  232. 'webp' => ['image/webp'],
  233. 'avif' => ['image/avif'],
  234. 'ico' => ['image/x-icon', 'image/vnd.microsoft.icon'],
  235. ],
  236. 'video' => [
  237. 'mp4' => ['video/mp4'],
  238. 'm4v' => ['video/mp4', 'video/x-m4v'],
  239. 'webm' => ['video/webm'],
  240. 'ogv' => ['video/ogg', 'application/ogg'],
  241. 'mov' => ['video/quicktime', 'video/mp4'],
  242. ],
  243. 'audio' => [
  244. 'mp3' => ['audio/mpeg', 'audio/mp3'],
  245. 'ogg' => ['audio/ogg', 'application/ogg'],
  246. 'oga' => ['audio/ogg', 'application/ogg'],
  247. 'opus' => ['audio/ogg', 'audio/opus', 'application/ogg'],
  248. 'wav' => ['audio/wav', 'audio/x-wav', 'audio/vnd.wave'],
  249. 'm4a' => ['audio/mp4', 'audio/x-m4a', 'video/mp4'],
  250. 'aac' => ['audio/aac', 'audio/x-hx-aac-adts'],
  251. 'flac' => ['audio/flac', 'audio/x-flac'],
  252. 'weba' => ['audio/webm', 'video/webm'],
  253. ],
  254. 'document' => [
  255. 'pdf' => ['application/pdf', 'application/x-pdf'],
  256. 'txt' => ['text/plain'],
  257. 'csv' => ['text/csv', 'text/plain', 'application/csv', 'text/x-csv'],
  258. 'rtf' => ['text/rtf', 'application/rtf'],
  259. 'doc' => ['application/msword', 'application/vnd.ms-office', 'application/CDFV2', 'application/x-ole-storage'],
  260. 'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'],
  261. 'xls' => ['application/vnd.ms-excel', 'application/vnd.ms-office', 'application/CDFV2', 'application/x-ole-storage'],
  262. 'xlsx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'],
  263. 'ppt' => ['application/vnd.ms-powerpoint', 'application/vnd.ms-office', 'application/CDFV2', 'application/x-ole-storage'],
  264. 'pptx' => ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/zip'],
  265. 'odt' => ['application/vnd.oasis.opendocument.text', 'application/zip'],
  266. 'ods' => ['application/vnd.oasis.opendocument.spreadsheet', 'application/zip'],
  267. 'odp' => ['application/vnd.oasis.opendocument.presentation', 'application/zip'],
  268. 'epub' => ['application/epub+zip', 'application/zip'],
  269. 'zip' => ['application/zip', 'application/x-zip-compressed', 'application/x-zip'],
  270. '7z' => ['application/x-7z-compressed'],
  271. 'rar' => ['application/vnd.rar', 'application/x-rar-compressed', 'application/x-rar'],
  272. ],
  273. ];
  274. }
  275. ​
  276. function media_kind_for_extension(string $ext): ?string
  277. {
  278. $ext = strtolower($ext);
  279. foreach (media_types() as $kind => $exts) {
  280. if (isset($exts[$ext])) {
  281. return $kind;
  282. }
  283. }
  284. return null;
  285. }
  286. ​
  287. function media_mime_for_url(string $url, string $fallback): string
  288. {
  289. $path = parse_url($url, PHP_URL_PATH) ?: $url;
  290. $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
  291. $map = [
  292. 'mp4' => 'video/mp4', 'm4v' => 'video/mp4', 'webm' => 'video/webm', 'ogv' => 'video/ogg', 'mov' => 'video/mp4',
  293. 'mp3' => 'audio/mpeg', 'ogg' => 'audio/ogg', 'oga' => 'audio/ogg', 'opus' => 'audio/ogg', 'wav' => 'audio/wav',
  294. 'm4a' => 'audio/mp4', 'aac' => 'audio/aac', 'flac' => 'audio/flac', 'weba' => 'audio/webm',
  295. ];
  296. return $map[$ext] ?? $fallback;
  297. }
  298. ​
  299. function invalidate_php_cache(string $filepath): void
  300. {
  301. clearstatcache(true, $filepath);
  302. if (function_exists('opcache_invalidate')) {
  303. @opcache_invalidate($filepath, true);
  304. }
  305. }
  306. ​
  307. function load_page(string $filename): ?array
  308. {
  309. foreach ([$filename . '.php', 'default-' . $filename . '.php'] as $candidate) {
  310. $filepath = DATA_DIR . $candidate;
  311. if (file_exists($filepath)) {
  312. return include $filepath;
  313. }
  314. }
  315. return null;
  316. }
  317. ​
  318. function save_page(string $filename, array $data): bool
  319. {
  320. unset($GLOBALS['_products_cache']);
  321. $filepath = DATA_DIR . $filename . '.php';
  322. $content = "<?php\nreturn " . var_export($data, true) . ";\n";
  323. $written = file_put_contents($filepath, $content) !== false;
  324. invalidate_php_cache($filepath);
  325. return $written;
  326. }
  327. ​
  328. function get_site_settings(?string $lang = null): array
  329. {
  330. $lang ??= flatly_current_lang();
  331. $settings = load_page('settings') ?? get_default_site_settings();
  332. if ($lang !== null) {
  333. $translation = load_page_lang('settings', $lang);
  334. if (is_array($translation)) {
  335. $settings = flatly_merge_translation($settings, $translation);
  336. }
  337. $settings['site_language'] = $lang;
  338. }
  339. return $settings;
  340. }
  341. ​
  342. function get_default_site_settings(): array
  343. {
  344. return [
  345. 'site_name' => SITE_NAME,
  346. 'site_description' => 'Build amazing websites with ease',
  347. 'logo_text' => SITE_NAME,
  348. 'site_language' => 'en',
  349. 'logo_image' => '',
  350. 'favicon' => '',
  351. 'primary_color' => '#ffffff',
  352. 'nav_links' => [
  353. ['label' => 'Features', 'url' => '#features'],
  354. ['label' => 'Testimonials', 'url' => '#testimonials'],
  355. ['label' => 'Pricing', 'url' => '#pricing'],
  356. ],
  357. 'nav_buttons' => [
  358. ['label' => 'Log in', 'url' => '#', 'style' => 'ghost'],
  359. ['label' => 'Get Started', 'url' => '#', 'style' => 'primary'],
  360. ],
  361. 'footer' => [
  362. 'brand_description' => 'A lightweight, self-hosted CMS that lets you create and manage websites with ease.',
  363. 'columns' => [
  364. [
  365. 'title' => 'Product',
  366. 'links' => [
  367. ['label' => 'Features', 'url' => '#features'],
  368. ['label' => 'Pricing', 'url' => '#pricing'],
  369. ['label' => 'Integrations', 'url' => '#'],
  370. ]
  371. ],
  372. [
  373. 'title' => 'Company',
  374. 'links' => [
  375. ['label' => 'About', 'url' => '#'],
  376. ['label' => 'Blog', 'url' => '#'],
  377. ['label' => 'Careers', 'url' => '#'],
  378. ]
  379. ],
  380. [
  381. 'title' => 'Resources',
  382. 'links' => [
  383. ['label' => 'Documentation', 'url' => '#'],
  384. ['label' => 'Guides', 'url' => '#'],
  385. ['label' => 'Support', 'url' => '#'],
  386. ]
  387. ],
  388. [
  389. 'title' => 'Legal',
  390. 'links' => [
  391. ['label' => 'Privacy', 'url' => '#'],
  392. ['label' => 'Terms', 'url' => '#'],
  393. ]
  394. ],
  395. ],
  396. 'social_links' => [
  397. ['platform' => 'twitter', 'url' => '#'],
  398. ['platform' => 'github', 'url' => '#'],
  399. ['platform' => 'linkedin', 'url' => '#'],
  400. ],
  401. 'copyright' => '© ' . date('Y') . ' ' . SITE_NAME . '. All rights reserved.',
  402. 'bottom_links' => [
  403. ['label' => 'Privacy Policy', 'url' => '#'],
  404. ['label' => 'Terms of Service', 'url' => '#'],
  405. ],
  406. ],
  407. ];
  408. }
  409. ​
  410. function get_available_fonts(): array
  411. {
  412. static $fonts = null;
  413. if ($fonts !== null) {
  414. return $fonts;
  415. }
  416. $fonts = [];
  417. foreach (glob(BASE_DIR . '/fonts/*.ttf') ?: [] as $file) {
  418. $base = pathinfo($file, PATHINFO_FILENAME);
  419. $label = trim(str_replace('_', ' ', $base));
  420. if ($label !== '' && preg_match('/^[\p{L}\p{N} \-.]+$/u', $label)) {
  421. $fonts[$label] = basename($file);
  422. }
  423. }
  424. ksort($fonts, SORT_NATURAL | SORT_FLAG_CASE);
  425. return $fonts;
  426. }
  427. ​
  428. function resolve_font(?string $name, string $default): string
  429. {
  430. $fonts = get_available_fonts();
  431. if ($name !== null && isset($fonts[$name])) {
  432. return $name;
  433. }
  434. if (isset($fonts[$default])) {
  435. return $default;
  436. }
  437. return (string) (array_key_first($fonts) ?? '');
  438. }
  439. ​
  440. function font_head_html(array $names, array $preload = []): string
  441. {
  442. $fonts = get_available_fonts();
  443. $css = '';
  444. $links = '';
  445. foreach (array_unique($names) as $name) {
  446. if (!isset($fonts[$name])) {
  447. continue;
  448. }
  449. $file = $fonts[$name];
  450. $url = '/fonts/' . rawurlencode($file) . '?v=' . (int) @filemtime(BASE_DIR . '/fonts/' . $file);
  451. $css .= "@font-face{font-family:'" . $name . "';font-style:normal;font-weight:100 900;font-display:swap;src:url('" . $url . "') format('truetype');}";
  452. if (in_array($name, $preload, true)) {
  453. $links .= '<link rel="preload" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" as="font" type="font/ttf" crossorigin>' . "\n ";
  454. }
  455. }
  456. return $css === '' ? '' : $links . '<style>' . $css . '</style>';
  457. }
  458. ​
  459. function get_system_settings(): array
  460. {
  461. static $settings = null;
  462. if ($settings !== null) {
  463. return $settings;
  464. }
  465. $stored = load_page('system');
  466. $settings = array_merge([
  467. 'translator_enabled' => true,
  468. 'translator_provider' => 'mymemory',
  469. 'translator_api_key' => '',
  470. 'dashboard_font' => 'Space Grotesk',
  471. 'ai_enabled' => false,
  472. 'ai_provider' => 'gemini',
  473. 'ai_model' => '',
  474. 'ai_api_key' => '',
  475. 'custom_js' => '',
  476. 'custom_html' => [],
  477. 'analytics' => [],
  478. ], is_array($stored) ? $stored : []);
  479. if (is_array($stored) && !isset($stored['dashboard_font']) && isset($stored['interface_font'])) {
  480. $settings['dashboard_font'] = $stored['interface_font'];
  481. }
  482. return $settings;
  483. }
  484. ​
  485. const CUSTOM_CODE_MAX_LENGTH = 100000;
  486. ​
  487. function flatly_posted_code(string $field): mixed
  488. {
  489. $decode = static function (mixed $value): string {
  490. $decoded = is_string($value) ? base64_decode($value, true) : false;
  491. ​
  492. return $decoded !== false && mb_check_encoding($decoded, 'UTF-8') ? $decoded : '';
  493. };
  494. if (isset($_POST[$field . '_b64'])) {
  495. $encoded = $_POST[$field . '_b64'];
  496. ​
  497. return is_array($encoded) ? array_map($decode, $encoded) : $decode($encoded);
  498. }
  499. ​
  500. return $_POST[$field] ?? null;
  501. }
  502. ​
  503. function flatly_clean_custom_code(mixed $raw): string
  504. {
  505. $code = str_replace(["\r\n", "\r"], "\n", is_string($raw) ? $raw : '');
  506. $code = (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $code);
  507. ​
  508. return mb_substr(trim($code), 0, CUSTOM_CODE_MAX_LENGTH);
  509. }
  510. ​
  511. function flatly_custom_js(): string
  512. {
  513. $code = (string) (get_system_settings()['custom_js'] ?? '');
  514. if (trim($code) === '') {
  515. return '';
  516. }
  517. if (stripos($code, '<script') !== false) {
  518. return "\n" . $code . "\n";
  519. }
  520. ​
  521. return "\n<script>\n" . str_ireplace('</script', '<\/script', $code) . "\n</script>\n";
  522. }
  523. ​
  524. const CUSTOM_HTML_LOCATIONS = [
  525. 'head' => 'Head (before </head>)',
  526. 'nav' => 'Navigation (inside the top bar, after the buttons)',
  527. 'body_start' => 'Body start (right after <body>)',
  528. 'body_end' => 'Body end (before </body>)',
  529. ];
  530. const CUSTOM_HTML_MAX_SNIPPETS = 20;
  531. ​
  532. function flatly_clean_custom_html(mixed $locations, mixed $codes): array
  533. {
  534. $locations = is_array($locations) ? array_values($locations) : [];
  535. $codes = is_array($codes) ? array_values($codes) : [];
  536. $snippets = [];
  537. foreach ($codes as $index => $code) {
  538. $location = is_string($locations[$index] ?? null) ? $locations[$index] : '';
  539. $code = flatly_clean_custom_code($code);
  540. if ($code === '' || !isset(CUSTOM_HTML_LOCATIONS[$location])) {
  541. continue;
  542. }
  543. $snippets[] = ['location' => $location, 'code' => $code];
  544. if (count($snippets) >= CUSTOM_HTML_MAX_SNIPPETS) {
  545. break;
  546. }
  547. }
  548. ​
  549. return $snippets;
  550. }
  551. ​
  552. function flatly_custom_html(string $location): string
  553. {
  554. $out = flatly_analytics_html($location);
  555. foreach ((array) (get_system_settings()['custom_html'] ?? []) as $snippet) {
  556. if (is_array($snippet) && ($snippet['location'] ?? '') === $location && is_string($snippet['code'] ?? null) && trim($snippet['code']) !== '') {
  557. $out .= "\n" . $snippet['code'] . "\n";
  558. }
  559. }
  560. ​
  561. return $out;
  562. }
  563. ​
  564. const ANALYTICS_PLACEMENTS = [
  565. 'head' => '<head>',
  566. 'body_start' => '<body> start',
  567. 'body_end' => '<body> end',
  568. ];
  569. const ANALYTICS_MAX_SCRIPTS = 30;
  570. ​
  571. function flatly_analytics_defaults(): array
  572. {
  573. return [
  574. 'consent_enabled' => false,
  575. 'cookie_icon' => false,
  576. 'banner_text' => 'We use cookies to analyse traffic and improve your experience. You can accept or reject optional cookies.',
  577. 'accept_label' => 'Accept',
  578. 'reject_label' => 'Reject',
  579. 'privacy_url' => '',
  580. 'scripts' => [],
  581. ];
  582. }
  583. ​
  584. function flatly_analytics_settings(): array
  585. {
  586. $stored = get_system_settings()['analytics'] ?? [];
  587. ​
  588. return array_merge(flatly_analytics_defaults(), is_array($stored) ? $stored : []);
  589. }
  590. ​
  591. function flatly_clean_analytics(array $raw): array
  592. {
  593. $defaults = flatly_analytics_defaults();
  594. $text = static function (mixed $value, int $limit, string $fallback): string {
  595. $value = is_string($value) ? trim((string) preg_replace('/[\x00-\x1F\x7F]/u', ' ', $value)) : '';
  596. ​
  597. return $value === '' ? $fallback : mb_substr($value, 0, $limit);
  598. };
  599. ​
  600. $privacy = is_string($raw['privacy_url'] ?? null) ? trim($raw['privacy_url']) : '';
  601. if ($privacy !== '' && preg_match('#^(https?://|/)[^\s<>"\']*$#i', $privacy) !== 1) {
  602. $privacy = '';
  603. }
  604. ​
  605. $scripts = [];
  606. foreach (array_slice(is_array($raw['scripts'] ?? null) ? array_values($raw['scripts']) : [], 0, ANALYTICS_MAX_SCRIPTS) as $script) {
  607. if (!is_array($script)) {
  608. continue;
  609. }
  610. $code = flatly_clean_custom_code($script['code'] ?? '');
  611. $name = $text($script['name'] ?? '', 100, '');
  612. if ($code === '' || $name === '') {
  613. continue;
  614. }
  615. $id = is_string($script['id'] ?? null) && preg_match('/^[a-z0-9]{6,32}$/', $script['id']) === 1 ? $script['id'] : bin2hex(random_bytes(6));
  616. $scripts[] = [
  617. 'id' => $id,
  618. 'name' => $name,
  619. 'code' => $code,
  620. 'placement' => is_string($script['placement'] ?? null) && isset(ANALYTICS_PLACEMENTS[$script['placement']]) ? $script['placement'] : 'head',
  621. 'consent' => !empty($script['consent']),
  622. 'active' => !empty($script['active']),
  623. ];
  624. }
  625. ​
  626. return [
  627. 'consent_enabled' => !empty($raw['consent_enabled']),
  628. 'cookie_icon' => !empty($raw['cookie_icon']),
  629. 'banner_text' => $text($raw['banner_text'] ?? '', 600, $defaults['banner_text']),
  630. 'accept_label' => $text($raw['accept_label'] ?? '', 40, $defaults['accept_label']),
  631. 'reject_label' => $text($raw['reject_label'] ?? '', 40, $defaults['reject_label']),
  632. 'privacy_url' => $privacy,
  633. 'scripts' => $scripts,
  634. ];
  635. }
  636. ​
  637. function flatly_analytics_html(string $location): string
  638. {
  639. $analytics = flatly_analytics_settings();
  640. $gate = !empty($analytics['consent_enabled']);
  641. $out = '';
  642. ​
  643. foreach ((array) $analytics['scripts'] as $script) {
  644. if (!is_array($script) || empty($script['active']) || ($script['placement'] ?? '') !== $location || !is_string($script['code'] ?? null)) {
  645. continue;
  646. }
  647. $out .= $gate && !empty($script['consent'])
  648. ? "\n<template data-flatly-consent>\n" . $script['code'] . "\n</template>\n"
  649. : "\n" . $script['code'] . "\n";
  650. }
  651. ​
  652. if ($gate && $location === 'body_end') {
  653. $config = [
  654. 'text' => (string) $analytics['banner_text'],
  655. 'accept' => (string) $analytics['accept_label'],
  656. 'reject' => (string) $analytics['reject_label'],
  657. 'privacy' => (string) $analytics['privacy_url'],
  658. 'icon' => !empty($analytics['cookie_icon']),
  659. ];
  660. $version = @filemtime(BASE_DIR . '/assets/js/consent.js') ?: 1;
  661. $out .= "\n<script>window.FLATLY_CONSENT = " . json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP) . ";</script>\n"
  662. . '<script src="/assets/js/consent.js?v=' . $version . '"></script>' . "\n";
  663. }
  664. ​
  665. return $out;
  666. }
  667. ​
  668. function get_dashboard_font(): string
  669. {
  670. return resolve_font(get_system_settings()['dashboard_font'] ?? null, 'Space Grotesk');
  671. }
  672. ​
  673. function get_optional_font(array $site_settings, string $key): string
  674. {
  675. $name = $site_settings[$key] ?? '';
  676. return $name !== '' && isset(get_available_fonts()[$name]) ? $name : '';
  677. }
  678. ​
  679. function site_font_selectors(): array
  680. {
  681. return [
  682. 'headings_font' => 'h1,h2,h3,h4,h5,h6',
  683. 'logo_font' => '.logo',
  684. 'price_font' => '.pricing-card .price',
  685. ];
  686. }
  687. ​
  688. function site_extra_fonts(array $site_settings): array
  689. {
  690. $names = [];
  691. foreach (array_keys(site_font_selectors()) as $key) {
  692. $name = get_optional_font($site_settings, $key);
  693. if ($name !== '') {
  694. $names[] = $name;
  695. }
  696. }
  697. return array_values(array_unique($names));
  698. }
  699. ​
  700. function get_site_interface_font(array $site_settings): string
  701. {
  702. return resolve_font($site_settings['interface_font'] ?? null, 'Space Grotesk');
  703. }
  704. ​
  705. function site_all_fonts(array $site_settings): array
  706. {
  707. $names = array_merge([get_text_font($site_settings), get_site_interface_font($site_settings)], site_extra_fonts($site_settings));
  708. return array_values(array_unique(array_filter($names, fn($name) => $name !== '')));
  709. }
  710. ​
  711. function site_fonts_css(array $site_settings): string
  712. {
  713. $text = get_text_font($site_settings);
  714. $interface = get_site_interface_font($site_settings);
  715. $css = '';
  716. if ($interface !== '') {
  717. $stack = font_family_css($interface);
  718. $css .= 'body{font-family:' . $stack . ';}';
  719. $css .= 'main .btn,main button,main input,main select,main textarea{font-family:' . $stack . ';}';
  720. }
  721. if ($text !== '') {
  722. $css .= 'main{font-family:' . font_family_css($text) . ';}';
  723. }
  724. foreach (site_font_selectors() as $key => $selector) {
  725. $name = get_optional_font($site_settings, $key);
  726. if ($name !== '') {
  727. $css .= $selector . '{font-family:' . font_family_css($name) . ';}';
  728. }
  729. }
  730. return $css;
  731. }
  732. ​
  733. function get_headings_font(array $site_settings): string
  734. {
  735. $name = $site_settings['headings_font'] ?? '';
  736. return $name !== '' && isset(get_available_fonts()[$name]) ? $name : '';
  737. }
  738. ​
  739. function headings_font_css(string $name): string
  740. {
  741. return $name === '' ? '' : "h1,h2,h3,h4,h5,h6{font-family:" . font_family_css($name) . ";}";
  742. }
  743. ​
  744. function get_text_font(array $site_settings): string
  745. {
  746. return resolve_font($site_settings['website_font'] ?? null, 'EB Garamond');
  747. }
  748. ​
  749. function font_family_css(string $name, string $fallback = '-apple-system, BlinkMacSystemFont, sans-serif'): string
  750. {
  751. return $name === '' ? $fallback : "'" . $name . "', " . $fallback;
  752. }
  753. ​
  754. function admin_font_head(): string
  755. {
  756. $font = get_dashboard_font();
  757. $html = font_head_html([$font], [$font]);
  758. if ($font !== '') {
  759. $html .= '<style>:root{--font-interface:' . font_family_css($font, 'sans-serif') . ';}</style>';
  760. }
  761. return $html;
  762. }
  763. ​
  764. function nav_icon_html($icon): string
  765. {
  766. if (!is_string($icon) || !preg_match('/^icon-[a-z0-9-]+$/', $icon)) {
  767. return '';
  768. }
  769. return '<svg class="nav-icon" aria-hidden="true"><use href="/assets/icons.svg#' . $icon . '"></use></svg>';
  770. }
  771. ​
  772. function get_icon_ids(): array
  773. {
  774. static $ids = null;
  775. if ($ids !== null) {
  776. return $ids;
  777. }
  778. $ids = [];
  779. $file = BASE_DIR . '/assets/icons.svg';
  780. if (is_file($file) && preg_match_all('/<symbol[^>]*\bid="(icon-[a-z0-9-]+)"/', (string) file_get_contents($file), $m)) {
  781. $ids = array_values(array_unique($m[1]));
  782. }
  783. return $ids;
  784. }
  785. ​
  786. function theme_file_active(): bool
  787. {
  788. $path = BASE_DIR . '/css/theme.css';
  789. if (!is_file($path) || filesize($path) === 0) {
  790. return false;
  791. }
  792. $handle = fopen($path, 'r');
  793. $header = fread($handle, 25);
  794. fclose($handle);
  795. return trim($header) !== '/* No theme active */';
  796. }
  797. ​
  798. function theme_link_html(): string
  799. {
  800. if (!theme_file_active()) {
  801. return '';
  802. }
  803. return '<link rel="stylesheet" href="/css/theme.css?v=' . (int) filemtime(BASE_DIR . '/css/theme.css') . '">';
  804. }
  805. ​
  806. function get_all_products(?string $lang = null): array
  807. {
  808. $lang ??= flatly_current_lang();
  809. $cache_key = $lang ?? '';
  810. if (isset($GLOBALS['_products_cache'][$cache_key])) {
  811. return $GLOBALS['_products_cache'][$cache_key];
  812. }
  813. ​
  814. $products = [];
  815. $files = glob(DATA_DIR . ($lang !== null && flatly_lang_code_valid($lang) ? $lang . '-lang-' : '') . 'product-*.php') ?: [];
  816. foreach ($files as $file) {
  817. $data = include $file;
  818. if (is_array($data)) {
  819. $products[] = $data;
  820. }
  821. }
  822. ​
  823. usort($products, function ($a, $b) {
  824. return strtotime($b['created_at'] ?? '0') - strtotime($a['created_at'] ?? '0');
  825. });
  826. return $GLOBALS['_products_cache'][$cache_key] = $products;
  827. }
  828. ​
  829. function find_product_by_slug(string $slug, ?string $lang = null): ?array
  830. {
  831. $products = get_all_products($lang);
  832. foreach ($products as $product) {
  833. if (isset($product['slug']) && $product['slug'] === $slug) {
  834. return $product;
  835. }
  836. }
  837. return null;
  838. }
  839. ​
  840. function get_all_pages(?string $lang = null): array
  841. {
  842. $pages = [
  843. ['label' => 'Homepage', 'url' => flatly_lang_url($lang, '/')],
  844. ];
  845. ​
  846. $products = get_all_products($lang);
  847. foreach ($products as $product) {
  848. $pages[] = [
  849. 'label' => $product['title'] ?? 'Product',
  850. 'url' => flatly_lang_url($lang, '/' . ($product['slug'] ?? '')),
  851. ];
  852. }
  853. ​
  854. return $pages;
  855. }
  856. ​
  857. function getPages(): array
  858. {
  859. return get_all_products();
  860. }
  861. ​
  862. function getSiteSettings(): array
  863. {
  864. return get_site_settings();
  865. }
  866. ​
  867. function getNavigation(): array
  868. {
  869. $settings = get_site_settings();
  870. return [
  871. 'items' => $settings['nav_links'] ?? [],
  872. ];
  873. }
  874. ​
  875. function getFooterSettings(): array
  876. {
  877. $settings = get_site_settings();
  878. $footer = $settings['footer'] ?? [];
  879. ​
  880. return [
  881. 'description' => $footer['brand_description'] ?? 'A lightweight, self-hosted CMS that lets you create and manage websites with ease..',
  882. 'social_links' => $footer['social_links'] ?? [],
  883. 'columns' => $footer['columns'] ?? [],
  884. 'copyright' => $footer['copyright'] ?? '© ' . date('Y') . ' ' . SITE_NAME . '. All rights reserved.',
  885. 'bottom_links' => $footer['bottom_links'] ?? [],
  886. ];
  887. }
  888. ​
  889. function sanitize(string $input): string
  890. {
  891. return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
  892. }
  893. ​
  894. require_once BASE_DIR . '/engine/renderion.php';
  895. ​