1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
<?php declare(strict_types=1);
const HEADER = '/^(#+)\s+(.*)/';
const LINK = '/^=>\s+(\S+)\s*(.*)/';
const LIST_ITEM = '/^\*\s+(.*)/';
const PRE = '/^```(.*)?/';
const QUOTE = '/^>\s+(.*)/';
function getPages(string $src, string $output): array
{
$src = realpath($src);
$iter = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($src, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
$pages = [];
foreach ($iter as $fileInfo) {
if (!is_file($fileInfo->getRealPath())) {
continue;
}
$pages[] = getPageMetaData($fileInfo, $src, $output);
}
return $pages;
}
function getPageMetaData(\SplFileInfo $fileInfo, string $src, string $output): array
{
$input = $fileInfo->getRealPath();
$pathData = parsePath($input);
$url = str_replace([$src, 'index.gmi'], ['', ''], $input);
$contentData = parseContent(file_get_contents($input));
return [
'input' => $input,
'url' => $url,
'date' => $pathData['date'],
'tag' => $pathData['tag'],
'isPost' => $pathData['isPost'],
'isTag' => $pathData['isTag'],
'title' => $contentData['title'],
'author' => $contentData['author'],
'html' => gemtext2hmtl(file_get_contents($input)),
'output' => "$output{$url}index.html",
];
}
function parsePath(string $path): array
{
$date = null;
$tag = null;
$isPost = false;
$isTag = false;
/**
* Assume that only posts have both a date and a tag.
*/
if (preg_match('/\/posts\/(.+)\/(\d\d\d\d-\d\d-\d\d)\//', $path, $matches) === 1) {
[, $tag, $date] = $matches;
$isPost = true;
}
/**
* Assume tags have an index file that contains related posts.
*/
if (preg_match('/posts\/(?:[^\/]|\/\/)+\/index/', $path, $matches) === 1) {
$tag = explode('/', $matches[0])[1];
$isTag = true;
}
return [
'date' => $date,
'tag' => $tag,
'isPost' => $isPost,
'isTag' => $isTag,
];
}
function parseContent(string $content): array
{
$title = null;
$author = null;
if (preg_match('/^# (.+)$/m', $content, $matches) === 1) {
$title = $matches[1];
}
if (preg_match('/^> .+ By (.+)$/m', $content, $matches) === 1) {
$author = $matches[1];
}
return [
'title' => $title,
'author' => $author,
];
}
function buildWWWSite(array $pages, string $hostname, string $htmlTemplateDiretory, string $output): void
{
foreach ($pages as $page) {
$destDirectory = dirname($page['output']);
if (!file_exists($destDirectory) && !mkdir($destDirectory, 0777, true)) {
echo "Unable to create WWW site directory $destDirectory.";
exit(1);
}
file_put_contents(
$page['output'],
buildHtmlFile(
$page['title'],
$page['html'],
file_get_contents($htmlTemplateDiretory.DIRECTORY_SEPARATOR.'default.html')
)
);
}
generateAtomFeeds($pages, $hostname);
generateSiteMap($pages, $hostname, $output);
}
function buildHtmlFile(string $title, string $contents, string $template): string
{
return str_replace(
[
'{{ $title }}',
'{{ $contents }}'
],
[
$title,
$contents,
],
$template
);
}
function gemtext2hmtl(string $gemtext): string
{
$html = [];
$lines = preg_split('/\r?\n/', htmlspecialchars($gemtext));
$line = fn ($index) => $lines[$index];
$index = 0;
$numLines = count($lines);
while($index < $numLines) {
if (preg_match(HEADER, $line($index), $matches) === 1) {
[, $levels, $content] = $matches;
$level = strlen($levels);
$html[] = "<h$level>$content</h$level>";
} elseif (preg_match(LINK, $line($index), $matches) === 1) {
[, $href, $content] = $matches;
$content = $content ?: $href;
$html[] = "<a href=\"$href\">$content</a>";
} elseif (preg_match(LIST_ITEM, $line($index), $matches) === 1) {
$items = [];
while ($index < $numLines) {
if (preg_match(LIST_ITEM, $line($index), $matches) === 0) {
break;
}
$items[] = "<li>$matches[1]</li>";
$index++;
}
$index--;
$html[] = sprintf("<ul>%s</ul>", implode('', $items));
} elseif (preg_match(PRE, $line($index), $matches) === 1) {
[, $alt] = $matches;
$items = [];
$index++;
while ($index < $numLines) {
$item = $line($index);
if (preg_match(PRE, $item, $matches) === 1) {
break;
}
$items[] = $item;
$index++;
}
$items = implode("\n", $items);
$html[] = $alt ? "<pre><code class=\"$alt\">$items</code></pre>" : "<pre>$items</pre>";
} elseif (preg_match(QUOTE, $line($index), $matches) === 1) {
$html[] = "<blockquote>$matches[1]</blockquote>";
} else {
if ($line($index) !== '') {
$html[] = "<p>{$line($index)}</p>";
}
}
$index++;
}
return implode('', $html);
}
function generateAtomFeeds(array $pages, string $hostname): void
{
$posts = array_filter($pages, fn ($post) => $post['isPost']);
$tags = array_filter($pages, fn ($post) => $post['isTag']);
/**
* Sort by latest to previous date.
*/
usort($posts, fn ($a, $b) => $b['date'] <=> $a['date']);
/**
* Group posts by tag.
*/
$groupedPosts = array_reduce($posts, function ($carry, $post) {
$carry[$post['tag']][] = $post;
return $carry;
}, []);
/**
* Put posts with their tag page.
*/
$tags = array_map(function ($tag) use ($groupedPosts) {
return array_merge($tag, ['posts' => $groupedPosts[$tag['tag']]]);
}, $tags);
foreach ($tags as $tag) {
tagToAtomFeed($tag, $hostname);
}
/**
* Get the page that lists all posts.
*/
$allPostsIndex = array_values(array_filter($pages, fn ($post) => preg_match('/posts\/index/', $post['output']) == 1))[0];
$allPostsIndex['posts'] = $posts;
tagToAtomFeed($allPostsIndex, $hostname);
}
function tagToAtomFeed(array $tag, string $hostname): void
{
file_put_contents(
str_replace('index.html', 'atom.xml', $tag['output']),
buildAtomFeed(
$tag['title'],
"https://$hostname{$tag['url']}atom.xml",
"https://$hostname".$tag['url'],
$tag['posts'][0]['date'].'T12:00:00Z',
implode('', array_map(fn ($post) => postToAtomEntry($post, $hostname), $tag['posts']))
)
);
}
function postToAtomEntry(array $post, string $hostname): string
{
return buildAtomEntry(
$post['title'],
"https://$hostname{$post['url']}",
$post['author'],
"{$post['date']}T12:00:00Z",
htmlspecialchars($post['html']),
);
}
function buildAtomFeed(string $title, string $href, string $altHref, string $date, string $entries): string
{
return <<<EOF_STR
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">$title</title>
<id>$href</id>
<link rel="alternate" type="text/html" href="$altHref"/>
<link rel="self" type="application/atom+xml" href="$href"/>
<updated>$date</updated>
$entries
</feed>
EOF_STR;
}
function buildAtomEntry(string $title, string $href, string $author, string $date, string $content): string
{
return <<<EOF_STR
<entry>
<title type="text">$title</title>
<id>$href</id>
<link rel="alternate" type="text/html" href="$href"/>
<author><name>$author</name></author>
<published>$date</published>
<updated>$date</updated>
<content type="html">$content</content>
</entry>
EOF_STR;
}
function generateSiteMap(array $pages, string $hostname, $output): void
{
$posts = array_filter($pages, fn ($post) => $post['isPost']);
/**
* Sort by latest to previous date.
*/
usort($posts, fn ($a, $b) => $b['date'] <=> $a['date']);
file_put_contents(
$output.DIRECTORY_SEPARATOR.'sitemap.xml',
buildSiteMap(
implode('', array_map(fn ($post) => postToSiteMapUrl($post, $hostname), $posts))
)
);
}
function postToSiteMapUrl(array $post, string $hostname): string
{
return buildSiteMapUrl(
"https://$hostname{$post['url']}",
"{$post['date']}T12:00:00Z"
);
}
function buildSiteMap(string $urls): string
{
return <<<EOF_STR
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
$urls
</urlset>
EOF_STR;
}
function buildSiteMapUrl(string $loc, string $lastmod): string
{
return <<<EOF_STR
<url>
<loc>$loc</loc>
<lastmod>$lastmod</lastmod>
<changefreq>never</changefreq>
</url>
EOF_STR;
}
|