Added tag filtering and RSS feed
This commit is contained in:
68
posts/posts.php
Normal file
68
posts/posts.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
function parseFrontMatter($raw) {
|
||||
if (preg_match('/^---\r?\n(.+?)\r?\n---\r?\n(.*)$/s', $raw, $m)) {
|
||||
$meta = [];
|
||||
foreach (preg_split('/\r?\n/', $m[1]) as $line) {
|
||||
if (strpos($line, ':') === false) continue;
|
||||
[$key, $value] = explode(':', $line, 2);
|
||||
$meta[trim($key)] = trim($value, " \t\"'");
|
||||
}
|
||||
return [$meta, $m[2]];
|
||||
}
|
||||
return [[], $raw];
|
||||
}
|
||||
|
||||
function makeExcerpt($body, $length = 220) {
|
||||
$text = preg_replace('/```.*?```/s', '', $body); // code blocks
|
||||
$text = preg_replace('/[#>*_`~\[\]]/', '', $text); // markdown symbols
|
||||
$text = preg_replace('/\(.*?\)/', '', $text); // link targets
|
||||
$text = preg_replace('/\s+/', ' ', $text); // collapse whitespace
|
||||
$text = trim($text);
|
||||
if (mb_strlen($text) > $length) {
|
||||
$text = mb_substr($text, 0, $length) . '…';
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
function getPosts($dir) {
|
||||
$skip = ['.', '..', 'list.php', 'feed.php', 'posts.php'];
|
||||
$files = array_diff(scandir($dir), $skip);
|
||||
|
||||
$posts = [];
|
||||
foreach ($files as $file) {
|
||||
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
|
||||
if (!in_array($ext, ['html', 'md'])) continue;
|
||||
|
||||
$path = $dir . '/' . $file;
|
||||
$fallbackTitle = ucwords(str_replace(['-', '_'], ' ', pathinfo($file, PATHINFO_FILENAME)));
|
||||
$created = filectime($path);
|
||||
|
||||
$meta = [];
|
||||
$body = '';
|
||||
if ($ext === 'md') {
|
||||
$raw = file_get_contents($path);
|
||||
[$meta, $body] = parseFrontMatter($raw);
|
||||
}
|
||||
|
||||
$title = $meta['title'] ?? $fallbackTitle;
|
||||
$date = isset($meta['date']) ? strtotime($meta['date']) : $created;
|
||||
$tags = isset($meta['tags']) && trim($meta['tags']) !== ''
|
||||
? array_map('trim', explode(',', $meta['tags']))
|
||||
: [];
|
||||
|
||||
$posts[] = [
|
||||
'file' => $file,
|
||||
'title' => $title,
|
||||
'type' => $ext,
|
||||
'created' => $date ?: $created,
|
||||
'date' => date('F j, Y', $date ?: $created),
|
||||
'tags' => $tags,
|
||||
'excerpt' => $body ? makeExcerpt($body) : '',
|
||||
];
|
||||
}
|
||||
|
||||
usort($posts, fn($a, $b) => $b['created'] - $a['created']); // newest first
|
||||
|
||||
return $posts;
|
||||
}
|
||||
Reference in New Issue
Block a user