48 lines
1.4 KiB
PHP
48 lines
1.4 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
|
|
$dir = __DIR__;
|
|
$files = array_diff(scandir($dir), ['.', '..', 'list.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;
|
|
}
|
|
return [];
|
|
}
|
|
|
|
$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); // fallback if no front matter date
|
|
|
|
$meta = [];
|
|
if ($ext === 'md') {
|
|
$raw = file_get_contents($path, false, null, 0, 4096); // just need the header
|
|
$meta = parseFrontMatter($raw);
|
|
}
|
|
|
|
$title = $meta['title'] ?? $fallbackTitle;
|
|
$date = isset($meta['date']) ? strtotime($meta['date']) : $created;
|
|
|
|
$posts[] = [
|
|
'file' => $file,
|
|
'title' => $title,
|
|
'type' => $ext,
|
|
'created' => $date ?: $created,
|
|
];
|
|
}
|
|
|
|
usort($posts, fn($a, $b) => $b['created'] - $a['created']); // newest first
|
|
|
|
echo json_encode($posts); |