'"Merriweather", Georgia, Times, "Times New Roman", serif', 'mono' => '"Iosevka", ui-monospace, "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace', default => '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', }; } function font_stack_url(string $fontStack): ?string { return null; } /** * Resolve the TrueType font path for dynamic OG image generation with hook override support. * * @param array $context */ function get_og_image_font_path(string $fontStack, array $context = []): ?string { $defaultFile = match ($fontStack) { 'mono' => PUREBLOG_BASE_PATH . '/assets/fonts/iosevka/Iosevka-Bold.ttf', 'serif' => PUREBLOG_BASE_PATH . '/assets/fonts/merriweather/Merriweather-Bold.ttf', default => PUREBLOG_BASE_PATH . '/assets/fonts/inter/Inter-Bold.ttf', }; $resolved = apply_filter('on_og_image_font', $defaultFile, $context); if (is_string($resolved) && is_file($resolved) && is_readable($resolved)) { return $resolved; } return is_file($defaultFile) && is_readable($defaultFile) ? $defaultFile : null; } /** * Get the dynamic Open Graph banner image URL for a post, page, or homepage. * * @param array|null $post * @param array|null $page */ function get_dynamic_og_image_url(?array $post = null, ?array $page = null): string { if (is_array($post) && !empty($post['slug'])) { return get_base_url() . '/og-image.php?type=post&slug=' . urlencode((string) $post['slug']); } if (is_array($page) && !empty($page['slug'])) { return get_base_url() . '/og-image.php?type=page&slug=' . urlencode((string) $page['slug']); } return get_base_url() . '/og-image.php?type=home'; } /** * Validate that a resolved path is within the allowed base directory. */ function validate_image_path(string $baseDir, string $targetPath): bool { $resolvedBase = realpath($baseDir); $resolvedTarget = realpath($targetPath); if ($resolvedBase === false || $resolvedTarget === false) { return false; } return str_starts_with($resolvedTarget, $resolvedBase . DIRECTORY_SEPARATOR); } /** * Validate that a slug is safe for use as an image folder name. */ function is_safe_image_slug(string $slug): bool { return $slug !== '' && preg_match('/^[\p{L}\p{N}\-_]+$/u', $slug) === 1; } function strip_image_metadata(string $path, string $mimeType): void { $ext = pathinfo($path, PATHINFO_EXTENSION); $tmpPath = $path . '.tmp' . ($ext !== '' ? '.' . $ext : ''); if (class_exists('Imagick')) { try { $img = new Imagick($path); $img->stripImage(); if ($img->writeImage($tmpPath) && is_file($tmpPath) && filesize($tmpPath) > 0) { @rename($tmpPath, $path); } else { @unlink($tmpPath); } $img->destroy(); } catch (Throwable $e) { @unlink($tmpPath); // silently fail — upload still succeeds } return; } // GD fallback: re-encoding drops all metadata [$loader, $saver] = match($mimeType) { 'image/jpeg' => ['imagecreatefromjpeg', fn($i, $dest) => imagejpeg($i, $dest, 90)], 'image/png' => ['imagecreatefrompng', fn($i, $dest) => imagepng($i, $dest)], 'image/webp' => ['imagecreatefromwebp', fn($i, $dest) => imagewebp($i, $dest)], default => [null, null], }; if ($loader === null || !function_exists($loader)) { return; } try { $img = @$loader($path); if ($img === false) { return; } if ($mimeType === 'image/png' || $mimeType === 'image/webp') { imagealphablending($img, false); imagesavealpha($img, true); } if (@$saver($img, $tmpPath) && is_file($tmpPath) && filesize($tmpPath) > 0) { @rename($tmpPath, $path); } else { @unlink($tmpPath); } } catch (Throwable $e) { @unlink($tmpPath); } } /** * Generate a resized thumbnail for an admin image preview. */ function generate_image_thumbnail(string $sourcePath, string $thumbPath, int $maxSize = 300): bool { if (!is_file($sourcePath) || $maxSize < 1) { return false; } if (!class_exists('Imagick') && !extension_loaded('gd')) { return false; } $thumbDir = dirname($thumbPath); if (!is_dir($thumbDir) && !@mkdir($thumbDir, 0755, true)) { return false; } $ext = pathinfo($thumbPath, PATHINFO_EXTENSION); $tmpPath = $thumbPath . '.tmp' . ($ext !== '' ? '.' . $ext : ''); if (class_exists('Imagick')) { try { $img = new Imagick($sourcePath); if ($img->getNumberImages() > 1) { $img = $img->coalesceImages(); $img->setIteratorIndex(0); $single = $img->getImage(); $img->destroy(); $img = $single; } $w = $img->getImageWidth(); $h = $img->getImageHeight(); if ($w <= 0 || $h <= 0) { $img->destroy(); return false; } if ($w <= $maxSize && $h <= $maxSize) { $img->destroy(); return @copy($sourcePath, $thumbPath); } $img->thumbnailImage($maxSize, $maxSize, true); $ok = $img->writeImage($tmpPath) && is_file($tmpPath) && filesize($tmpPath) > 0; $img->destroy(); if ($ok) { return @rename($tmpPath, $thumbPath); } @unlink($tmpPath); } catch (Throwable $e) { @unlink($tmpPath); } return false; } $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->file($sourcePath) ?: ''; [$loader, $saver] = match($mimeType) { 'image/jpeg' => ['imagecreatefromjpeg', fn($i, $dest) => imagejpeg($i, $dest, 82)], 'image/png' => ['imagecreatefrompng', fn($i, $dest) => imagepng($i, $dest)], 'image/webp' => ['imagecreatefromwebp', fn($i, $dest) => imagewebp($i, $dest, 82)], 'image/gif' => ['imagecreatefromgif', fn($i, $dest) => imagegif($i, $dest)], 'image/avif' => ['imagecreatefromavif', fn($i, $dest) => function_exists('imageavif') ? imageavif($i, $dest, 82) : false], default => [null, null], }; if ($loader === null || !function_exists($loader)) { return false; } try { $srcImg = @$loader($sourcePath); if ($srcImg === false) { return false; } $w = imagesx($srcImg); $h = imagesy($srcImg); if ($w <= 0 || $h <= 0) { return false; } if ($w <= $maxSize && $h <= $maxSize) { return @copy($sourcePath, $thumbPath); } $ratio = min($maxSize / $w, $maxSize / $h); $newW = max(1, (int) round($w * $ratio)); $newH = max(1, (int) round($h * $ratio)); $dstImg = imagecreatetruecolor($newW, $newH); if ($dstImg === false) { return false; } if (in_array($mimeType, ['image/png', 'image/webp', 'image/gif', 'image/avif'], true)) { imagealphablending($dstImg, false); imagesavealpha($dstImg, true); $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127); if ($transparent !== false) { imagefilledrectangle($dstImg, 0, 0, $newW, $newH, $transparent); } } if (!imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h)) { return false; } if (@$saver($dstImg, $tmpPath) && is_file($tmpPath) && filesize($tmpPath) > 0) { return @rename($tmpPath, $thumbPath); } @unlink($tmpPath); } catch (Throwable $e) { @unlink($tmpPath); } return false; } /** * Get the thumbnail URL for an image in a slug folder, lazily generating it if missing. */ function get_image_thumb_url(string $slug, string $filename): string { $fullUrl = base_path() . '/content/images/' . $slug . '/' . $filename; $thumbUrl = base_path() . '/content/images/' . $slug . '/thumbs/' . $filename; $sourcePath = PUREBLOG_CONTENT_IMAGES_PATH . '/' . $slug . '/' . $filename; $thumbPath = PUREBLOG_CONTENT_IMAGES_PATH . '/' . $slug . '/thumbs/' . $filename; if (is_file($thumbPath) && filesize($thumbPath) > 0) { return $thumbUrl; } if (is_file($sourcePath) && generate_image_thumbnail($sourcePath, $thumbPath)) { return $thumbUrl; } return $fullUrl; } function slugify(string $value): string { $value = trim($value); if (function_exists('mb_strtolower')) { $value = mb_strtolower($value, 'UTF-8'); } else { $value = strtolower($value); } // Transliterate common diacritics to ASCII equivalents $value = strtr($value, [ 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ÿ' => 'y', ]); $value = preg_replace('/[^\p{L}\p{N}\s-]/u', '', $value) ?? ''; $value = preg_replace('/[\s-]+/u', '-', $value) ?? ''; return trim($value, '-'); } // --------------------------------------------------------------------------- // Date and timezone helpers // --------------------------------------------------------------------------- function normalize_date_value(string $value): ?string { if ($value === '') { return null; } $formats = [ 'Y-m-d H:i', 'Y-m-d H:i:s', 'Y-m-d\\TH:i:s.u\\Z', 'Y-m-d\\TH:i:s\\Z', 'Y-m-d\\TH:i:s.uP', 'Y-m-d\\TH:i:sP', ]; foreach ($formats as $format) { $dt = DateTime::createFromFormat($format, $value); if ($dt instanceof DateTime) { return $dt->format('Y-m-d H:i'); } } $timestamp = strtotime($value); if ($timestamp !== false) { return date('Y-m-d H:i', $timestamp); } return null; } function site_timezone_identifier(array $config): string { $timezone = trim((string) ($config['timezone'] ?? '')); if ($timezone === '') { return date_default_timezone_get(); } return in_array($timezone, DateTimeZone::listIdentifiers(), true) ? $timezone : date_default_timezone_get(); } function site_timezone_object(array $config): DateTimeZone { return new DateTimeZone(site_timezone_identifier($config)); } function site_date_format(array $config): string { $format = trim((string) ($config['date_format'] ?? '')); return $format !== '' ? $format : 'F j, Y'; } function current_site_datetime_for_storage(array $config): string { return (new DateTimeImmutable('now', site_timezone_object($config)))->format('Y-m-d H:i'); } function parse_post_datetime_with_timezone(?string $value, array $config): ?DateTimeImmutable { $raw = trim((string) $value); if ($raw === '') { return null; } $tz = site_timezone_object($config); $formats = [ 'Y-m-d H:i', 'Y-m-d H:i:s', 'Y-m-d\\TH:i:s.u\\Z', 'Y-m-d\\TH:i:s\\Z', 'Y-m-d\\TH:i:s.uP', 'Y-m-d\\TH:i:sP', ]; foreach ($formats as $format) { $dt = DateTimeImmutable::createFromFormat($format, $raw, $tz); if ($dt instanceof DateTimeImmutable) { return $dt->setTimezone($tz); } } $timestamp = strtotime($raw); if ($timestamp === false) { return null; } return (new DateTimeImmutable('@' . $timestamp))->setTimezone($tz); } function format_post_date_for_display(?string $value, array $config): string { return format_datetime_for_display($value, $config, null); } function format_datetime_for_display(?string $value, array $config, ?string $format = null): string { $dt = parse_post_datetime_with_timezone($value, $config); if (!$dt) { return ''; } $effectiveFormat = $format !== null && trim($format) !== '' ? $format : site_date_format($config); return _lang_translate_date($dt->format($effectiveFormat)); } function calculate_reading_time(string $content): string { $wordCount = str_word_count(strip_tags($content)); $minutes = max(1, (int) ceil($wordCount / 200)); return t('frontend.reading_time', ['n' => $minutes]); } function relative_time(int $timestamp): string { $diff = max(0, time() - $timestamp); if ($diff < 60) { return t('admin.dashboard.time_just_now'); } if ($diff < 3600) { $n = (int) floor($diff / 60); return t($n === 1 ? 'admin.dashboard.time_minute_ago' : 'admin.dashboard.time_minutes_ago', ['n' => $n]); } if ($diff < 86400) { $n = (int) floor($diff / 3600); return t($n === 1 ? 'admin.dashboard.time_hour_ago' : 'admin.dashboard.time_hours_ago', ['n' => $n]); } $n = (int) floor($diff / 86400); return t($n === 1 ? 'admin.dashboard.time_day_ago' : 'admin.dashboard.time_days_ago', ['n' => $n]); } function format_post_date_for_rss(?string $value, array $config): string { $dt = parse_post_datetime_with_timezone($value, $config); if (!$dt) { return (new DateTimeImmutable('now', site_timezone_object($config)))->format(DATE_RSS); } return $dt->format(DATE_RSS); } // --------------------------------------------------------------------------- // Post scheduler // --------------------------------------------------------------------------- function publish_scheduled_posts(): int { if (!is_dir(PUREBLOG_POSTS_PATH)) { return 0; } $files = glob(PUREBLOG_POSTS_PATH . '/*.md') ?: []; $config = load_config(); $now = new DateTimeImmutable('now', site_timezone_object($config)); $count = 0; foreach ($files as $file) { $front = parse_post_meta_only($file); if (($front['status'] ?? '') !== 'scheduled') { continue; } $dt = parse_post_datetime_with_timezone($front['date'] ?? '', $config); if ($dt === null || $dt > $now) { continue; } $parsed = parse_post_file($file); $fm = $parsed['front_matter']; $knownKeys = ['title', 'slug', 'date', 'status', 'tags', 'description', 'categories', 'layout']; $post = array_merge( array_diff_key($fm, array_flip($knownKeys)), [ 'title' => $fm['title'] ?? 'Untitled', 'slug' => $fm['slug'] ?? '', 'date' => $fm['date'] ?? '', 'status' => 'published', 'tags' => $fm['tags'] ?? [], 'description' => $fm['description'] ?? '', 'content' => $parsed['content'], 'layout' => $fm['layout'] ?? '', ] ); $saveError = ''; if (save_post($post, $post['slug'], $post['date'], 'scheduled', $saveError)) { $count++; } } return $count; } function maybe_publish_scheduled_posts(): void { if (!is_dir(PUREBLOG_POSTS_PATH)) { return; } $lockFile = PUREBLOG_POSTS_PATH . '/.scheduler.lock'; $interval = 300; // 5 minutes if (is_file($lockFile) && (time() - (int) filemtime($lockFile)) < $interval) { return; } @file_put_contents($lockFile, (string) time()); publish_scheduled_posts(); } // --------------------------------------------------------------------------- // Post and page I/O // --------------------------------------------------------------------------- function _build_front_matter_lines(array $frontMatter): array { $frontLines = ["---"]; foreach ($frontMatter as $key => $value) { if ($key === 'tags') { $value = '[' . implode(', ', $value) . ']'; $frontLines[] = $key . ': ' . $value; } elseif (is_string($value) && strpos($value, "\n") !== false) { $frontLines[] = $key . ': |'; $value = str_replace("\r", '', $value); $lines = explode("\n", $value); foreach ($lines as $line) { $frontLines[] = ' ' . $line; } } else { $frontLines[] = $key . ': ' . (string) $value; } } $frontLines[] = "---"; return $frontLines; } function _parse_front_matter_lines(array $lines): array { $frontMatter = []; $listKey = null; $blockKey = null; $blockLines = []; $blockIndent = 0; foreach ($lines as $line) { if ($blockKey !== null) { if ($line === '' || rtrim($line) === '') { $blockLines[] = ''; continue; } if (preg_match('/^(\s+)(.*)$/', $line, $matches)) { $indent = strlen($matches[1]); if ($blockIndent === 0) { $blockIndent = $indent; } if ($indent >= $blockIndent) { $blockLines[] = substr($line, $blockIndent); continue; } } $frontMatter[$blockKey] = implode("\n", $blockLines); $blockKey = null; $blockLines = []; $blockIndent = 0; } $trimmedLine = rtrim($line); if ($trimmedLine === '') { continue; } if ($listKey !== null) { if (preg_match('/^\s*-\s*(.+)$/', $trimmedLine, $matches)) { $item = trim($matches[1], " \t\"'"); if ($item !== '') { $frontMatter[$listKey][] = $item; } continue; } $listKey = null; } if (strpos($trimmedLine, ':') === false) { continue; } [$key, $value] = array_map('trim', explode(':', $trimmedLine, 2)); if ($key === '') { continue; } if ($value === '|') { $blockKey = $key; $blockLines = []; $blockIndent = 0; continue; } if ($value === '') { if (in_array($key, ['tags', 'categories'], true)) { $listKey = $key; $frontMatter[$key] = $frontMatter[$key] ?? []; continue; } $frontMatter[$key] = ''; continue; } if ($key === 'date') { $value = trim($value, "\"'"); $normalized = normalize_date_value($value); $frontMatter[$key] = $normalized ?? $value; } elseif ($key === 'tags' || $key === 'categories') { $value = trim($value, "[] "); $tags = $value === '' ? [] : array_map('trim', explode(',', $value)); $frontMatter[$key] = array_filter($tags, fn($tag) => $tag !== ''); } elseif ($key === 'description') { $frontMatter[$key] = $value; } elseif ($key === 'include_in_nav') { $frontMatter[$key] = in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true); } else { $frontMatter[$key] = $value; } } if ($blockKey !== null) { $frontMatter[$blockKey] = implode("\n", $blockLines); } if (!empty($frontMatter['categories'])) { $categoryTags = is_array($frontMatter['categories']) ? $frontMatter['categories'] : []; $existingTags = $frontMatter['tags'] ?? []; $frontMatter['tags'] = array_values(array_unique(array_merge($existingTags, $categoryTags))); } return $frontMatter; } function parse_post_file(string $filepath): array { $raw = file_get_contents($filepath); if ($raw === false) { return ['front_matter' => [], 'content' => '']; } $raw = str_replace("\r\n", "\n", $raw); $frontMatter = []; $content = $raw; if (str_starts_with($raw, "---\n")) { $parts = explode("\n---\n", $raw, 2); if (count($parts) === 2) { $frontMatter = _parse_front_matter_lines(explode("\n", trim($parts[0], "-\n"))); $content = $parts[1]; } } return [ 'front_matter' => $frontMatter, 'content' => ltrim($content), ]; } function parse_post_meta_only(string $filepath): array { $fh = @fopen($filepath, 'r'); if ($fh === false) { return []; } $firstLine = fgets($fh); if ($firstLine === false || rtrim($firstLine) !== '---') { fclose($fh); return []; } $lines = []; while (($line = fgets($fh)) !== false) { $trimmed = rtrim($line); if ($trimmed === '---') { break; } $lines[] = $trimmed; } fclose($fh); return _parse_front_matter_lines($lines); } function get_all_posts_meta(bool $includeDrafts = false, bool $bustCache = false): array { static $all = null; static $published = null; if ($bustCache) { $all = null; $published = null; } if ($all === null) { if (!is_dir(PUREBLOG_POSTS_PATH)) { $all = []; $published = []; } else { $files = glob(PUREBLOG_POSTS_PATH . '/*.md') ?: []; $posts = []; $config = load_config(); foreach ($files as $file) { $front = parse_post_meta_only($file); $status = $front['status'] ?? 'draft'; $dateString = $front['date'] ?? ''; $dt = parse_post_datetime_with_timezone($dateString, $config); $timestamp = $dt ? $dt->getTimestamp() : 0; $knownFrontKeys = ['title', 'slug', 'date', 'status', 'tags', 'description', 'categories']; $extraFront = array_diff_key($front, array_flip($knownFrontKeys)); $posts[] = array_merge($extraFront, [ 'title' => $front['title'] ?? 'Untitled', 'slug' => $front['slug'] ?? '', 'date' => $dateString, 'timestamp' => $timestamp, 'status' => $status, 'tags' => $front['tags'] ?? [], 'description' => $front['description'] ?? '', 'path' => $file, ]); } usort($posts, fn($a, $b) => ($b['timestamp'] <=> $a['timestamp'])); $all = $posts; $published = array_values(array_filter($all, fn($p) => ($p['status'] ?? 'draft') === 'published')); } } return $includeDrafts ? $all : $published; } function get_all_posts(bool $includeDrafts = false, bool $bustCache = false): array { static $all = null; static $published = null; if ($bustCache) { $all = null; $published = null; } if ($all === null) { if (!is_dir(PUREBLOG_POSTS_PATH)) { $all = []; $published = []; } else { $files = glob(PUREBLOG_POSTS_PATH . '/*.md') ?: []; $posts = []; $config = load_config(); foreach ($files as $file) { $parsed = parse_post_file($file); $front = $parsed['front_matter']; $status = $front['status'] ?? 'draft'; $dateString = $front['date'] ?? ''; $dt = parse_post_datetime_with_timezone($dateString, $config); $timestamp = $dt ? $dt->getTimestamp() : 0; $knownFrontKeys = ['title', 'slug', 'date', 'status', 'tags', 'description', 'categories']; $extraFront = array_diff_key($front, array_flip($knownFrontKeys)); $posts[] = array_merge($extraFront, [ 'title' => $front['title'] ?? 'Untitled', 'slug' => $front['slug'] ?? '', 'date' => $dateString, 'timestamp' => $timestamp, 'status' => $status, 'tags' => $front['tags'] ?? [], 'description' => $front['description'] ?? '', 'content' => $parsed['content'], 'path' => $file, ]); } usort($posts, fn($a, $b) => ($b['timestamp'] <=> $a['timestamp'])); $all = $posts; $published = array_values(array_filter($all, fn($p) => ($p['status'] ?? 'draft') === 'published')); } } return $includeDrafts ? $all : $published; } function get_post_by_slug(string $slug, bool $includeDrafts = false): ?array { $posts = get_all_posts($includeDrafts); foreach ($posts as $post) { if ($post['slug'] === $slug) { return $post; } } return null; } function get_adjacent_posts_by_slug(string $slug, bool $includeDrafts = false): array { $posts = get_all_posts($includeDrafts); $count = count($posts); for ($i = 0; $i < $count; $i++) { if (($posts[$i]['slug'] ?? '') !== $slug) { continue; } return [ 'previous' => $posts[$i + 1] ?? null, 'next' => $posts[$i - 1] ?? null, ]; } return [ 'previous' => null, 'next' => null, ]; } function get_all_pages(bool $includeDrafts = false, bool $bustCache = false): array { static $all = null; static $published = null; if ($bustCache) { $all = null; $published = null; } if ($all === null) { if (!is_dir(PUREBLOG_PAGES_PATH)) { $all = []; $published = []; } else { $files = glob(PUREBLOG_PAGES_PATH . '/*.md') ?: []; $pages = []; foreach ($files as $file) { $parsed = parse_post_file($file); $front = $parsed['front_matter']; $status = $front['status'] ?? 'draft'; $knownPageKeys = ['title', 'slug', 'status', 'description', 'include_in_nav', 'categories']; $extraFront = array_diff_key($front, array_flip($knownPageKeys)); $pages[] = array_merge($extraFront, [ 'title' => $front['title'] ?? 'Untitled', 'slug' => $front['slug'] ?? '', 'status' => $status, 'description' => $front['description'] ?? '', 'include_in_nav' => $front['include_in_nav'] ?? true, 'content' => $parsed['content'], 'path' => $file, ]); } usort($pages, fn($a, $b) => ($a['title'] <=> $b['title'])); $all = $pages; $published = array_values(array_filter($all, fn($p) => ($p['status'] ?? 'draft') === 'published')); } } return $includeDrafts ? $all : $published; } function get_page_by_slug(string $slug, bool $includeDrafts = false): ?array { $pages = get_all_pages($includeDrafts); foreach ($pages as $page) { if ($page['slug'] === $slug) { return $page; } } return null; } function save_page(array &$page, ?string $originalSlug = null, ?string $originalStatus = null, ?string &$error = null): bool { $error = null; $title = trim($page['title'] ?? ''); $slug = trim($page['slug'] ?? ''); $status = trim($page['status'] ?? 'draft'); $description = trim($page['description'] ?? ''); $includeInNav = (bool) ($page['include_in_nav'] ?? true); $content = str_replace("\r", '', $page['content'] ?? ''); $slug = slugify($slug === '' ? $title : $slug); if ($slug !== '') { $baseSlug = $slug; $suffix = 2; while (slug_in_use($slug, 'page', $originalSlug)) { $slug = $baseSlug . '-' . $suffix; $suffix++; } } $page['slug'] = $slug; if ($originalSlug !== null && $originalSlug !== '' && $originalSlug !== $slug) { $oldImageFolder = PUREBLOG_BASE_PATH . '/content/images/' . $originalSlug; $newImageFolder = PUREBLOG_BASE_PATH . '/content/images/' . $slug; if (is_dir($oldImageFolder)) { @rename($oldImageFolder, $newImageFolder); } if (isset($page['content'])) { $page['content'] = str_replace( '/content/images/' . $originalSlug . '/', '/content/images/' . $slug . '/', $page['content'] ); $content = str_replace("\r", '', $page['content']); } if (isset($page['feature_image']) && $page['feature_image'] !== '') { $page['feature_image'] = str_replace( '/content/images/' . $originalSlug . '/', '/content/images/' . $slug . '/', $page['feature_image'] ); } } $filename = $slug . '.md'; $path = PUREBLOG_PAGES_PATH . '/' . $filename; $featureImage = trim($page['feature_image'] ?? ''); $frontMatter = [ 'title' => $title, 'slug' => $slug, 'status' => $status, 'description' => $description, 'include_in_nav' => $includeInNav ? 'true' : 'false', ]; if ($featureImage !== '') { $frontMatter['feature_image'] = $featureImage; } $frontLines = _build_front_matter_lines($frontMatter); $body = implode("\n", $frontLines) . "\n\n" . ltrim($content) . "\n"; if (!is_dir(PUREBLOG_PAGES_PATH)) { mkdir(PUREBLOG_PAGES_PATH, 0755, true); } $existingPath = null; if ($originalSlug !== null && $originalSlug !== $slug) { $existingPath = PUREBLOG_PAGES_PATH . '/' . $originalSlug . '.md'; if (!is_file($existingPath)) { $existingPath = null; } } if (file_put_contents($path, $body) === false) { $error = 'Unable to write page file.'; return false; } if ($existingPath && $existingPath !== $path) { if (!unlink($existingPath)) { $error = 'Page saved, but could not remove the old file. Check permissions.'; return false; } } $wasPublished = ($originalStatus === 'published'); $isPublished = ($status === 'published'); if ($isPublished) { call_hook('on_page_updated', [$slug]); if (!$wasPublished) { call_hook('on_page_published', [$slug]); } if ($wasPublished && $originalSlug !== null && $originalSlug !== '' && $originalSlug !== $slug) { // Old URL can remain cached when a published page slug changes. call_hook('on_page_deleted', [$originalSlug]); } } elseif ($wasPublished) { // Page was removed from public output (unpublished). call_hook('on_page_deleted', [$slug]); } get_all_pages(true, true); build_search_index(); cache_clear(); return true; } function delete_page_by_slug(string $slug): bool { $path = PUREBLOG_PAGES_PATH . '/' . $slug . '.md'; if (!is_file($path)) { return false; } $deleted = unlink($path); if (!$deleted) { return false; } $imageDir = PUREBLOG_CONTENT_IMAGES_PATH . '/' . $slug; if (is_dir($imageDir)) { $thumbDir = $imageDir . '/thumbs'; if (is_dir($thumbDir)) { foreach (glob($thumbDir . '/*') ?: [] as $thumbFile) { if (is_file($thumbFile)) { @unlink($thumbFile); } } @rmdir($thumbDir); } $files = glob($imageDir . '/*') ?: []; foreach ($files as $file) { if (is_file($file) && !unlink($file)) { return false; } } if (!rmdir($imageDir)) { return false; } } get_all_pages(true, true); build_search_index(); cache_clear(); return true; } function update_front_matter_field(string $filepath, string $field, string $value): bool { $raw = file_get_contents($filepath); if ($raw === false) { return false; } $raw = str_replace("\r\n", "\n", $raw); if (!preg_match('/\A(---\n.*?\n---\n)/s', $raw, $matches)) { return false; } $frontBlock = $matches[1]; $body = substr($raw, strlen($frontBlock)); $pattern = '/^' . preg_quote($field, '/') . ':.*\n?/m'; if ($value !== '') { $line = $field . ': ' . $value . "\n"; if (preg_match($pattern, $frontBlock)) { $frontBlock = preg_replace($pattern, $line, $frontBlock); } else { $frontBlock = substr($frontBlock, 0, -4) . $line . "---\n"; } } else { $frontBlock = preg_replace($pattern, '', $frontBlock); } return file_put_contents($filepath, $frontBlock . $body) !== false; } function find_post_filepath_by_slug(string $slug): ?string { foreach (get_all_posts(true) as $post) { if ($post['slug'] === $slug) { return $post['path']; } } return null; } function delete_post_by_slug(string $slug): bool { $path = find_post_filepath_by_slug($slug); if ($path === null) { return false; } $deleted = unlink($path); if ($deleted) { $imageDir = PUREBLOG_CONTENT_IMAGES_PATH . '/' . $slug; if (is_dir($imageDir)) { $thumbDir = $imageDir . '/thumbs'; if (is_dir($thumbDir)) { foreach (glob($thumbDir . '/*') ?: [] as $thumbFile) { if (is_file($thumbFile)) { @unlink($thumbFile); } } @rmdir($thumbDir); } $files = glob($imageDir . '/*') ?: []; foreach ($files as $file) { if (is_file($file) && !unlink($file)) { return false; } } if (!rmdir($imageDir)) { return false; } } build_search_index(); build_tag_index(); cache_clear(); call_hook('on_post_deleted', [$slug]); } return $deleted; } function slug_in_use(string $slug, string $type, ?string $originalSlug = null): bool { if ($type === 'post') { $postPath = find_post_filepath_by_slug($slug); if ($postPath !== null && ($originalSlug === null || $originalSlug !== $slug)) { return true; } if (get_page_by_slug($slug, true)) { return true; } return false; } if ($type === 'page') { $page = get_page_by_slug($slug, true); if ($page && ($originalSlug === null || $originalSlug !== $slug)) { return true; } if (find_post_filepath_by_slug($slug) !== null) { return true; } return false; } return false; } function save_post(array &$post, ?string $originalSlug = null, ?string $originalDate = null, ?string $originalStatus = null, ?string &$error = null): bool { $error = null; $title = trim($post['title'] ?? ''); $slug = trim($post['slug'] ?? ''); $date = trim($post['date'] ?? ''); $status = trim($post['status'] ?? 'draft'); $tags = $post['tags'] ?? []; $content = str_replace("\r", '', $post['content'] ?? ''); $description = trim($post['description'] ?? ''); $slug = slugify($slug === '' ? $title : $slug); if ($slug !== '') { $baseSlug = $slug; $suffix = 2; while (slug_in_use($slug, 'post', $originalSlug)) { $slug = $baseSlug . '-' . $suffix; $suffix++; } } $post['slug'] = $slug; if ($originalSlug !== null && $originalSlug !== '' && $originalSlug !== $slug) { $oldImageFolder = PUREBLOG_BASE_PATH . '/content/images/' . $originalSlug; $newImageFolder = PUREBLOG_BASE_PATH . '/content/images/' . $slug; if (is_dir($oldImageFolder)) { @rename($oldImageFolder, $newImageFolder); } if (isset($post['content'])) { $post['content'] = str_replace( '/content/images/' . $originalSlug . '/', '/content/images/' . $slug . '/', $post['content'] ); $content = str_replace("\r", '', $post['content']); } if (isset($post['feature_image']) && $post['feature_image'] !== '') { $post['feature_image'] = str_replace( '/content/images/' . $originalSlug . '/', '/content/images/' . $slug . '/', $post['feature_image'] ); } } $config = load_config(); if ($date === '') { $date = current_site_datetime_for_storage($config); } $datePrefix = format_datetime_for_display($date, $config, 'Y-m-d'); if ($datePrefix === '') { $datePrefix = format_datetime_for_display(current_site_datetime_for_storage($config), $config, 'Y-m-d'); } $filename = $datePrefix . '-' . $slug . '.md'; $path = PUREBLOG_POSTS_PATH . '/' . $filename; $layout = trim($post['layout'] ?? ''); $layoutFields = is_array($post['layout_fields'] ?? null) ? $post['layout_fields'] : []; $frontMatter = [ 'title' => $title, 'slug' => $slug, 'date' => $date, 'status' => $status, 'tags' => $tags, 'description' => $description, ]; if ($layout !== '') { $frontMatter['layout'] = $layout; } $featureImage = trim($post['feature_image'] ?? ''); if ($featureImage !== '') { $frontMatter['feature_image'] = $featureImage; } foreach ($layoutFields as $fieldName => $fieldValue) { $fieldName = trim((string) $fieldName); if ($fieldName !== '') { $frontMatter[$fieldName] = trim((string) $fieldValue); } } $frontLines = _build_front_matter_lines($frontMatter); $body = implode("\n", $frontLines) . "\n\n" . ltrim($content) . "\n"; if (!is_dir(PUREBLOG_POSTS_PATH)) { mkdir(PUREBLOG_POSTS_PATH, 0755, true); } $existingPath = null; $renameFrom = null; if ($originalSlug !== null && $originalSlug !== $slug) { $existingPath = find_post_filepath_by_slug($originalSlug); } elseif ($originalSlug !== null) { $actualPath = find_post_filepath_by_slug($originalSlug); if ($actualPath !== null && $actualPath !== $path) { $renameFrom = $actualPath; } } if ($renameFrom !== null) { if (!rename($renameFrom, $path)) { $error = 'Unable to rename post file after date change.'; return false; } } if (file_put_contents($path, $body) === false) { $error = 'Unable to write post file.'; return false; } if ($existingPath && $existingPath !== $path) { if (!unlink($existingPath)) { $error = 'Post saved, but could not remove the old file. Check permissions.'; return false; } } build_search_index(); build_tag_index(); cache_clear(); if ($status === 'published') { call_hook('on_post_updated', [$slug]); if ($originalStatus !== 'published') { call_hook('on_post_published', [$slug]); } } return true; } /** * Convert relative URLs in feed content to absolute URLs. * Correctly handles installations in a sub-folder to prevent duplication. */ function absolutize_feed_html(string $html, string $baseUrl, string $postUrl = ''): string { if (trim($html) === '') { return $html; } // Temporarily replace
/ blocks so their contents are not modified.
    $placeholders = [];
    $html = preg_replace_callback(
        '/<(pre|code)[^>]*>.*?<\/\1>/si',
        function ($match) use (&$placeholders): string {
            $key = "\x00PH_" . count($placeholders) . "\x00";
            $placeholders[$key] = $match[0];
            return $key;
        },
        $html
    ) ?? $html;

    $parsed = parse_url($baseUrl);
    $basePath = rtrim((string) ($parsed['path'] ?? ''), '/');
    $scheme = $parsed['scheme'] ?? 'http';
    $host = $parsed['host'] ?? '';
    $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
    $domainUrl = $scheme . '://' . $host . $port;

    $html = preg_replace_callback(
        '/(href|src)="\/(?P[^"]*)"/i',
        function ($matches) use ($baseUrl, $domainUrl, $basePath): string {
            $attribute = $matches[1];
            $path = $matches['path'];

            // If the path starts with the sub-folder/base path, prepend domainUrl.
            // Otherwise, prepend baseUrl.
            if ($basePath !== '' && (str_starts_with('/' . $path, $basePath . '/') || '/' . $path === $basePath)) {
                return $attribute . '="' . $domainUrl . '/' . $path . '"';
            }

            return $attribute . '="' . $baseUrl . '/' . $path . '"';
        },
        $html
    ) ?? $html;

    if ($postUrl !== '') {
        $html = preg_replace('/href="#/', 'href="' . $postUrl . '#', $html) ?? $html;
    }

    // Restore 
/ blocks.
    if ($placeholders !== []) {
        $html = str_replace(array_keys($placeholders), array_values($placeholders), $html);
    }

    return $html;
}

// ---------------------------------------------------------------------------
// Theme Management helpers
// ---------------------------------------------------------------------------

function normalize_theme_item(array $raw, string $source, string $filename = '', int $index = 0): ?array
{
    $name = trim((string) ($raw['name'] ?? ''));
    if ($name === '') {
        return null;
    }

    $id = $source === 'core'
        ? 'core:' . ($filename !== '' ? basename($filename, '.json') . ':' : '') . ($index > 0 ? $index . ':' : '') . slugify($name)
        : 'user:' . ($filename !== '' ? basename($filename, '.json') : slugify($name));

    $defaults = default_config()['theme'];

    $hasLight = isset($raw['light']) && is_array($raw['light']);
    $hasDark = isset($raw['dark']) && is_array($raw['dark']);

    if ($hasLight || $hasDark) {
        $light = [
            'bg'        => trim((string) ($raw['light']['bg'] ?? $raw['light']['background_color'] ?? $defaults['background_color'])),
            'text'      => trim((string) ($raw['light']['text'] ?? $raw['light']['text_color'] ?? $defaults['text_color'])),
            'accent'    => trim((string) ($raw['light']['accent'] ?? $raw['light']['accent_color'] ?? $defaults['accent_color'])),
            'border'    => trim((string) ($raw['light']['border'] ?? $raw['light']['border_color'] ?? $defaults['border_color'])),
            'accent_bg' => trim((string) ($raw['light']['accent_bg'] ?? $raw['light']['accent_bg_color'] ?? $defaults['accent_bg_color'])),
        ];
        $dark = [
            'bg'        => trim((string) ($raw['dark']['bg'] ?? $raw['dark']['background_color'] ?? $raw['dark']['background_color_dark'] ?? $defaults['background_color_dark'])),
            'text'      => trim((string) ($raw['dark']['text'] ?? $raw['dark']['text_color'] ?? $raw['dark']['text_color_dark'] ?? $defaults['text_color_dark'])),
            'accent'    => trim((string) ($raw['dark']['accent'] ?? $raw['dark']['accent_color'] ?? $raw['dark']['accent_color_dark'] ?? $defaults['accent_color_dark'])),
            'border'    => trim((string) ($raw['dark']['border'] ?? $raw['dark']['border_color'] ?? $raw['dark']['border_color_dark'] ?? $defaults['border_color_dark'])),
            'accent_bg' => trim((string) ($raw['dark']['accent_bg'] ?? $raw['dark']['accent_bg_color'] ?? $raw['dark']['accent_bg_color_dark'] ?? $defaults['accent_bg_color_dark'])),
        ];
    } else {
        $isDark = (isset($raw['mode']) && $raw['mode'] === 'dark') || str_contains(strtolower($name), 'dark');
        $palette = [
            'bg'        => trim((string) ($raw['bg'] ?? $raw['background_color'] ?? ($isDark ? $defaults['background_color_dark'] : $defaults['background_color']))),
            'text'      => trim((string) ($raw['text'] ?? $raw['text_color'] ?? ($isDark ? $defaults['text_color_dark'] : $defaults['text_color']))),
            'accent'    => trim((string) ($raw['accent'] ?? $raw['accent_color'] ?? ($isDark ? $defaults['accent_color_dark'] : $defaults['accent_color']))),
            'border'    => trim((string) ($raw['border'] ?? $raw['border_color'] ?? ($isDark ? $defaults['border_color_dark'] : $defaults['border_color']))),
            'accent_bg' => trim((string) ($raw['accent_bg'] ?? $raw['accent_bg_color'] ?? ($isDark ? $defaults['accent_bg_color_dark'] : $defaults['accent_bg_color']))),
        ];

        if ($isDark) {
            $hasLight = false;
            $hasDark = true;
            $light = [
                'bg'        => $defaults['background_color'],
                'text'      => $defaults['text_color'],
                'accent'    => $defaults['accent_color'],
                'border'    => $defaults['border_color'],
                'accent_bg' => $defaults['accent_bg_color'],
            ];
            $dark = $palette;
        } else {
            $hasLight = true;
            $hasDark = false;
            $light = $palette;
            $dark = [
                'bg'        => $defaults['background_color_dark'],
                'text'      => $defaults['text_color_dark'],
                'accent'    => $defaults['accent_color_dark'],
                'border'    => $defaults['border_color_dark'],
                'accent_bg' => $defaults['accent_bg_color_dark'],
            ];
        }
    }

    return [
        'id'        => $id,
        'name'      => $name,
        'source'    => $source,
        'filename'  => $filename,
        'is_custom' => $source === 'user',
        'has_light' => $hasLight,
        'has_dark'  => $hasDark,
        'light'     => $light,
        'dark'      => $dark,
    ];
}

function get_available_themes(): array
{
    $themes = [];

    if (is_dir(PUREBLOG_CORE_THEMES_PATH)) {
        $coreFiles = glob(PUREBLOG_CORE_THEMES_PATH . '/*.json') ?: [];
        sort($coreFiles);
        foreach ($coreFiles as $file) {
            $content = @file_get_contents($file);
            if (!$content) continue;
            $data = json_decode($content, true);
            if (!is_array($data)) continue;

            $filename = basename($file);
            if (isset($data['name'])) {
                $item = normalize_theme_item($data, 'core', $filename);
                if ($item) $themes[$item['id']] = $item;
            } else {
                foreach ($data as $idx => $rawItem) {
                    if (is_array($rawItem)) {
                        $item = normalize_theme_item($rawItem, 'core', $filename, $idx + 1);
                        if ($item) $themes[$item['id']] = $item;
                    }
                }
            }
        }
    }

    if (is_dir(PUREBLOG_THEMES_PATH)) {
        $userFiles = glob(PUREBLOG_THEMES_PATH . '/*.json') ?: [];
        sort($userFiles);
        foreach ($userFiles as $file) {
            $content = @file_get_contents($file);
            if (!$content) continue;
            $data = json_decode($content, true);
            if (!is_array($data)) continue;

            $filename = basename($file);
            if (isset($data['name'])) {
                $item = normalize_theme_item($data, 'user', $filename);
                if ($item) $themes[$item['id']] = $item;
            } else {
                foreach ($data as $idx => $rawItem) {
                    if (is_array($rawItem)) {
                        $item = normalize_theme_item($rawItem, 'user', $filename, $idx + 1);
                        if ($item) $themes[$item['id']] = $item;
                    }
                }
            }
        }
    }

    return array_values($themes);
}

function get_theme_by_id(string $id): ?array
{
    foreach (get_available_themes() as $theme) {
        if ($theme['id'] === $id) {
            return $theme;
        }
    }
    return null;
}

function apply_theme_to_config(array $themeData): bool
{
    $config = load_config();
    $hasLight = !empty($themeData['has_light']) || (!isset($themeData['has_light']) && !empty($themeData['light']));
    $hasDark  = !empty($themeData['has_dark'])  || (!isset($themeData['has_dark'])  && !empty($themeData['dark']));

    if ($hasLight) {
        $config['theme']['background_color'] = $themeData['light']['bg'] ?? '#FAFAFA';
        $config['theme']['text_color'] = $themeData['light']['text'] ?? '#212121';
        $config['theme']['accent_color'] = $themeData['light']['accent'] ?? '#0D47A1';
        $config['theme']['border_color'] = $themeData['light']['border'] ?? '#898EA4';
        $config['theme']['accent_bg_color'] = $themeData['light']['accent_bg'] ?? '#F5F7FF';
    }

    if ($hasDark) {
        $config['theme']['background_color_dark'] = $themeData['dark']['bg'] ?? '#212121';
        $config['theme']['text_color_dark'] = $themeData['dark']['text'] ?? '#DCDCDC';
        $config['theme']['accent_color_dark'] = $themeData['dark']['accent'] ?? '#FFB300';
        $config['theme']['border_color_dark'] = $themeData['dark']['border'] ?? '#555555';
        $config['theme']['accent_bg_color_dark'] = $themeData['dark']['accent_bg'] ?? '#2B2B2B';
    }

    $config['theme']['active_theme_name'] = $themeData['name'] ?? '';

    return save_config($config);
}

function save_theme_json(string $name, ?array $light, ?array $dark): array
{
    $name = trim($name);
    if ($name === '') {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_name')];
    }

    if ($light === null && $dark === null) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_empty')];
    }

    $themeDir = PUREBLOG_THEMES_PATH;
    if (!is_dir($themeDir)) {
        if (!mkdir($themeDir, 0755, true) && !is_dir($themeDir)) {
            return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_folder')];
        }
    }

    $slug = slugify($name);
    if ($slug === '') {
        $slug = 'theme-' . time();
    }
    $filename = $slug . '.json';
    $filePath = $themeDir . '/' . $filename;

    $defaults = default_config()['theme'];
    $cleanPalette = function (array $palette, bool $isDark) use ($defaults): array {
        $map = [
            'bg'        => $isDark ? $defaults['background_color_dark'] : $defaults['background_color'],
            'text'      => $isDark ? $defaults['text_color_dark'] : $defaults['text_color'],
            'accent'    => $isDark ? $defaults['accent_color_dark'] : $defaults['accent_color'],
            'border'    => $isDark ? $defaults['border_color_dark'] : $defaults['border_color'],
            'accent_bg' => $isDark ? $defaults['accent_bg_color_dark'] : $defaults['accent_bg_color'],
        ];
        $cleaned = [];
        foreach ($map as $key => $defaultVal) {
            $val = trim((string) ($palette[$key] ?? ''));
            if ($val === '') {
                $val = $defaultVal;
            } elseif (!str_starts_with($val, '#')) {
                $val = '#' . $val;
            }
            $cleaned[$key] = $val;
        }
        return $cleaned;
    };

    $themeData = ['name' => $name];
    if ($light !== null) {
        $themeData['light'] = $cleanPalette($light, false);
    }
    if ($dark !== null) {
        $themeData['dark'] = $cleanPalette($dark, true);
    }

    $json = json_encode($themeData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    if (file_put_contents($filePath, $json) === false) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_save')];
    }

    return ['ok' => true, 'filename' => $filename, 'name' => $name];
}

function save_uploaded_theme(array $file): array
{
    if (empty($file['name']) || ($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_upload')];
    }

    $content = @file_get_contents($file['tmp_name']);
    if (!$content) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_invalid')];
    }

    $json = json_decode($content, true);
    if (!is_array($json)) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_invalid')];
    }

    $themeDir = PUREBLOG_THEMES_PATH;
    if (!is_dir($themeDir)) {
        if (!mkdir($themeDir, 0755, true) && !is_dir($themeDir)) {
            return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_folder')];
        }
    }

    $baseName = pathinfo((string) $file['name'], PATHINFO_FILENAME);
    $slug = slugify($baseName);
    if ($slug === '') {
        $slug = 'imported-theme-' . time();
    }
    $filename = $slug . '.json';
    $targetPath = $themeDir . '/' . $filename;

    if (file_put_contents($targetPath, json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) === false) {
        return ['ok' => false, 'error' => t('admin.settings.theme.error_theme_save')];
    }

    return ['ok' => true, 'filename' => $filename];
}

function delete_theme_file(string $filename): bool
{
    $cleanFilename = basename($filename);
    if ($cleanFilename === '' || !str_ends_with(strtolower($cleanFilename), '.json')) {
        return false;
    }

    $targetFile = PUREBLOG_THEMES_PATH . '/' . $cleanFilename;
    if (is_file($targetFile)) {
        return @unlink($targetFile);
    }
    return false;
}