88 lines
2.3 KiB
PHP
88 lines
2.3 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../config.php';
|
|
|
|
$__er = error_reporting();
|
|
error_reporting($__er & ~E_DEPRECATED);
|
|
require_once __DIR__ . '/Parsedown.php';
|
|
error_reporting($__er);
|
|
|
|
const POSTS_DIR = __DIR__ . '/../posts';
|
|
|
|
function post_slug_valid(string $slug): bool {
|
|
return (bool) preg_match('/^[a-z0-9][a-z0-9-]*$/', $slug);
|
|
}
|
|
|
|
function parse_front_matter(string $raw): array {
|
|
$meta = [];
|
|
$body = $raw;
|
|
if (preg_match('/^(?:\xEF\xBB\xBF)?---\r?\n(.*?)\r?\n---\r?\n?(.*)$/s', $raw, $m)) {
|
|
foreach (preg_split('/\r?\n/', $m[1]) as $line) {
|
|
if (preg_match('/^(\w+):\s*(.*)$/', $line, $kv)) {
|
|
$meta[strtolower($kv[1])] = trim($kv[2]);
|
|
}
|
|
}
|
|
$body = $m[2];
|
|
}
|
|
return [$meta, $body];
|
|
}
|
|
|
|
function load_post(string $slug): ?array {
|
|
if (!post_slug_valid($slug)) {
|
|
return null;
|
|
}
|
|
$file = POSTS_DIR . '/' . $slug . '.md';
|
|
if (!is_file($file)) {
|
|
return null;
|
|
}
|
|
$raw = (string) file_get_contents($file);
|
|
[$meta, $body] = parse_front_matter($raw);
|
|
return [
|
|
'slug' => $slug,
|
|
'title' => $meta['title'] ?? $slug,
|
|
'date' => $meta['date'] ?? date('Y-m-d', filemtime($file)),
|
|
'body' => $body,
|
|
];
|
|
}
|
|
|
|
function all_posts(): array {
|
|
$posts = [];
|
|
foreach (glob(POSTS_DIR . '/*.md') ?: [] as $file) {
|
|
if ($p = load_post(basename($file, '.md'))) {
|
|
$posts[] = $p;
|
|
}
|
|
}
|
|
usort($posts, fn($a, $b) => strcmp($b['date'], $a['date']));
|
|
return $posts;
|
|
}
|
|
|
|
function render_markdown(string $md): string {
|
|
static $pd = null;
|
|
if ($pd === null) {
|
|
$pd = new Parsedown();
|
|
$pd->setSafeMode(true);
|
|
}
|
|
return $pd->text($md);
|
|
}
|
|
|
|
function post_date_display(string $date): string {
|
|
$ts = strtotime($date);
|
|
return $ts ? date('m/d/Y', $ts) : htmlspecialchars($date);
|
|
}
|
|
|
|
function render_post_list(array $posts): void {
|
|
if (!$posts) {
|
|
echo '<p class="muted">no posts yet.</p>';
|
|
return;
|
|
}
|
|
echo '<ul class="post-list">';
|
|
foreach ($posts as $p) {
|
|
printf(
|
|
'<li><a href="/post.php?slug=%s">%s</a><span class="date">%s</span></li>',
|
|
urlencode($p['slug']),
|
|
htmlspecialchars($p['title']),
|
|
post_date_display($p['date'])
|
|
);
|
|
}
|
|
echo '</ul>';
|
|
}
|