Phoebe/Oddmuse.pm untested

filter: Statementstmt 0.0% 0 / 748 Branchbran 0.0% 0 / 226 Conditioncond 0.0% 0 / 85 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 1195 CC 114 SCAR 48.9
CC
114
Cov
0%
oddmuse_process_request
650.0
oddmuse_serve_changes
110.0
oddmuse_http_error
90.0
CRAP 132.7
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 App::Phoebe::Oddmuse - act as a Gemini proxy for an Oddmuse wiki
22  
23 =head1 DESCRIPTION
24  
25 This extension allows you to serve files from an Oddmuse wiki instead of a real
26 Phoebe wiki directory.
27  
28 The tricky part is that most Oddmuse wikis don't use Gemini markup (“gemtext”)
29 and therefore care is required. The extension tries to transmogrify typical
30 Oddmuse markup (based on my own wikis) to Gemini.
31  
32 Here's one way to configure it. I use Apache as my proxy server and have
33 multiple Oddmuse wikis running on the same machine, each only serving
34 C<localhost>. I need to recreate some of the Apache configuration, here.
35  
36 package App::Phoebe::Oddmuse;
37  
38 our %oddmuse_wikis = (
39 "alexschroeder.ch" => "http://localhost:4023/wiki",
40 "communitywiki.org" => "http://localhost:4019/wiki",
41 "emacswiki.org" => "http://localhost:4002/wiki",
42 "campaignwiki.org" => "http://localhost:4004/wiki", );
43  
44 our %oddmuse_wiki_names = (
45 "alexschroeder.ch" => "Alex Schroeder",
46 "communitywiki.org" => "Community Wiki",
47 "emacswiki.org" => "Emacs Wiki",
48 "campaignwiki.org" => "Campaign Wiki", );
49  
50 our %oddmuse_wiki_dirs = (
51 "alexschroeder.ch" => "/home/alex/alexschroeder",
52 "communitywiki.org" => "/home/alex/communitywiki",
53 "emacswiki.org" => "/home/alex/emacswiki",
54 "campaignwiki.org" => "/home/alex/campaignwiki", );
55  
56 our %oddmuse_wiki_links = (
57 "communitywiki.org" => 1,
58 "campaignwiki.org" => 1, );
59  
60 use App::Phoebe::Oddmuse;
61  
62 =cut
63  
64 package App::Phoebe::Oddmuse;
65 use App::Phoebe qw(@request_handlers @extensions @main_menu $server $log $full_url_regex
66 success result reserved_regex port gemini_link modified changes diff
67 colourize quote_html bogus_hash print_link decode_query);
68 use Mojo::UserAgent;
69 use Modern::Perl;
70 use MIME::Base64;
71 use URI::Escape;
72 use List::Util qw(uniq);
73 use File::Slurper qw(read_dir read_text write_text);
74 use Encode qw(encode_utf8 decode_utf8);
75 use DateTime::Format::ISO8601;
76 use utf8; # the source contains UTF-8 encoded strings
77 no warnings 'redefine';
78  
79 # Oddmuse Wiki
80  
81 our %oddmuse_wikis = (
82 "alexschroeder.ch" => "http://localhost:4023/wiki",
83 "communitywiki.org" => "http://localhost:4019/wiki",
84 "emacswiki.org" => "http://localhost:4002/wiki" );
85  
86 our %oddmuse_wiki_names = (
87 "alexschroeder.ch" => "Alex Schroeder",
88 "communitywiki.org" => "Community Wiki",
89 "emacswiki.org" => "Emacs Wiki" );
90  
91 our %oddmuse_wiki_dirs = (
92 "alexschroeder.ch" => "/home/alex/alexschroeder",
93 "communitywiki.org" => "/home/alex/communitywiki",
94 "emacswiki.org" => "/home/alex/emacswiki" );
95  
96 # The Oddmuse wiki uses WikiLinks
97 our %oddmuse_wiki_links = ("communitywiki.org" => 1);
98  
99 # The Oddmuse wiki uses a different token as the answer to a security question
100 # (i.e. not the Phoebe server token). This only works if the Oddmuse wiki has
101 # just one security question (or accepts the same answer for all questions).
102 our %oddmuse_wiki_tokens = (
103 "emacswiki.org" => "emacs" );
104  
105 # Also allow percent encoded…
106 our $oddmuse_namespace_regex = '[\p{Uppercase}\d][%\w_  ]*';
107  
108 *oddmuse_old_space_regex = \&App::Phoebe::space_regex;
109 *App::Phoebe::space_regex = \&oddmuse_new_space_regex;
110  
111 sub oddmuse_new_space_regex {
112 my $spaces = oddmuse_old_space_regex();
113 return "$spaces|$oddmuse_namespace_regex" if $spaces;
114 return $oddmuse_namespace_regex;
115 }
116  
117 *oddmuse_old_space = \&App::Phoebe::space;
118 *App::Phoebe::space = \&oddmuse_new_space;
119  
120 sub oddmuse_new_space {
121 my $stream = shift;
122 my $host = shift;
123 my $space = shift;
124 if (grep { $_ eq $host } keys %oddmuse_wikis) {
125 # Let Oddmuse handle namespaces
126 return $space;
127 }
128 return oddmuse_old_space($stream, $host, $space);
129 }
130  
131 *oddmuse_old_save_page = \&App::Phoebe::save_page;
132 *App::Phoebe::save_page = \&oddmuse_new_save_page;
133  
134 sub oddmuse_new_save_page {
135 my $stream = shift;
136 my $host = shift;
137 my $space = shift;
138 my $id = shift;
139 my $type = shift;
140 my $data = shift;
141 my $length = shift;
142 my $port = port($stream);
143 if (not grep { $_ eq $host } keys %oddmuse_wikis) {
144 return oddmuse_old_save_page($stream, $host, $space, $id, $type, $data, $length);
145 }
146 if ($type ne "text/plain") {
147 $data = "#FILE $type\n" . encode_base64($data);
148 } elsif (not utf8::decode($data)) {
149 $log->debug("The text is invalid UTF-8");
150 result($stream, "59", "The text is invalid UTF-8");
151 $stream->close_gracefully();
152 return;
153 }
154 my @tokens = @{$server->{wiki_token}};
155 push(@tokens, $oddmuse_wiki_tokens{$host}) if $oddmuse_wiki_tokens{$host};
156 my $token = pop(@tokens); # the oddmuse wiki token, preferrably
157 my $name = ref($stream->handle) eq 'IO::Socket::SSL' && $stream->handle->peer_certificate('cn') || "";
158 my $ua = Mojo::UserAgent->new;
159 my $tx = $ua->post(
160 $oddmuse_wikis{$host}
161 => {'X-Forwarded-For' => $stream->handle->peerhost}
162 => form => {
163 title => $id,
164 text => $data,
165 ns => $space,
166 answer => $token,
167 username => $name,
168 gemini => 1 });
169 $log->debug("Got " . $tx->result->code . " response");
170 if ($tx->result->code == 302) {
171 my $url = "gemini://$host:$port";
172 $url .= "/$space" if $space;
173 result($stream, "30", "$url/page/" . uri_escape_utf8($id) . "");
174 } else {
175 $stream->write("59 Got HTTP code " . $tx->result->code . " " . $tx->result->message
176 . " (" . $tx->req->url->to_abs . " " . $tx->req->params . ")\r\n");
177 }
178 $stream->close_gracefully();
179 }
180  
181 *oddmuse_old_valid_token = \&App::Phoebe::valid_token;
182 *App::Phoebe::valid_token = \&oddmuse_new_valid_token;
183  
184 sub oddmuse_new_valid_token {
185 my ($stream, $host, $space, $id, $params) = @_;
186 my $token = $params->{token}||"";
187 if ($oddmuse_wiki_tokens{$host}) {
188 $log->debug("Comparing $token with $oddmuse_wiki_tokens{$host}");
189 } else {
190 $log->debug("There is no specific token for this Oddmuse wiki");
191 }
192 return 1 if $oddmuse_wiki_tokens{$host} and $oddmuse_wiki_tokens{$host} eq $token;
193 return oddmuse_old_valid_token(@_);
194 }
195  
196 push(@extensions, \&oddmuse_process_request);
197  
198 sub oddmuse_process_request {
199 my $stream = shift;
200 my $url = shift;
201 my $headers = shift;
202 my $hosts = "(" . join("|", keys %oddmuse_wikis) . ")";
203 my $spaces = $oddmuse_namespace_regex;
204 my $reserved = reserved_regex();
205 my $port = port($stream);
206 my ($host, $space, $id, $query, $n, $style, $token);
207 if ($url =~ m!^gemini://$hosts(?::$port)?/robots\.txt$!) {
208 # must come before redirection to regular pages since it contains no slash
209 oddmuse_serve_robots($stream);
210 } elsif (($host, $n, $space) = $url =~ m!^gemini://$hosts(:$port)?(?:/($spaces))?/(?:$reserved)$!) {
211 result($stream, "31", "gemini://$host" . ($n ? ":$port" : "") . "/" . ($space ? $space : "") . ""); # this supports "up"
212 } elsif (($host, $space, $id, $n) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/page/([^/]+)(?:/(\d+))?$!
213 and $id ne $server->{wiki_main_page}) {
214 oddmuse_serve_page($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))), $n);
215 } elsif (($host, $space, $id) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/tag/([^/]+)$!) {
216 oddmuse_serve_tag($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))));
217 } elsif (($host, $space, $id) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/raw/([^/]+)$!
218 and $id ne $server->{wiki_main_page}) {
219 oddmuse_serve_raw($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))));
220 } elsif (($host, $space, $id) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/html/([^/]+)$!) {
221 oddmuse_serve_html($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))));
222 } elsif (($host, $space, $n) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/(?:blog|more)(?:/(\d+))?$!) {
223 oddmuse_serve_blog($stream, $host, decode_utf8(uri_unescape($space)), $n||10);
224 } elsif (($host, $space, $n) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/index$!) {
225 oddmuse_serve_index($stream, $host, decode_utf8(uri_unescape($space)));
226 } elsif (($host, $space, $n, $style) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/changes(?:/(\d+))?(?:/(colour|fancy))?$!) {
227 oddmuse_serve_changes($stream, $host, decode_utf8(uri_unescape($space)), $n||3, $style); # days!
228 } elsif (($host, $n, $style) = $url =~ m!^gemini://$hosts(?::$port)?/do/all/changes(?:/(\d+))?(?:/(colour|fancy))?$!) {
229 oddmuse_serve_changes($stream, $host, undef, $n||3, $style, 1); # days!
230 } elsif (($host, $space, $id, $style) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/history/([^/]*)(?:/(colour|fancy))?$!) {
231 oddmuse_serve_history($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))), $style);
232 } elsif (($host, $space, $id, $n, $style) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/diff/([^/]*)(?:/(\d+))?(?:/(colour))?$!) {
233 oddmuse_serve_diff($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))), $n, $style);
234 } elsif ($url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/match$!) {
235 result($stream, "10", "Find page by name (Perl regex)");
236 } elsif (($host, $space, $query) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/match\?([^#]+)!) {
237 oddmuse_serve_match($stream, $host, decode_utf8(uri_unescape($space)), decode_query($query));
238 } elsif ($url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/search$!) {
239 result($stream, "10", "Find page by content (Perl regex)");
240 } elsif (($host, $space, $query) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/search\?([^#]+)!) {
241 oddmuse_serve_search($stream, $host, decode_utf8(uri_unescape($space)), decode_query($query));
242 } elsif (($host, $space, $id, $query) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/comment/([^/#?]+)(?:\?([^#]+))?$!) {
243 oddmuse_comment($stream, $host, decode_utf8(uri_unescape($space)), free_to_normal(decode_utf8(uri_unescape($id))), decode_query($query));
244 } elsif (($host, $space) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/atom$!) {
245 oddmuse_serve_atom($stream, $host, decode_utf8(uri_unescape($space)), 'rc');
246 } elsif (($host, $space) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/rss$!) {
247 oddmuse_serve_rss($stream, $host, decode_utf8(uri_unescape($space)), 'rc');
248 } elsif (($host, $space) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/blog/atom$!) {
249 oddmuse_serve_atom($stream, $host, decode_utf8(uri_unescape($space)), 'journal');
250 } elsif (($host, $space) = $url =~ m!^gemini://$hosts(?::$port)?(?:/($spaces))?/do/blog/rss$!) {
251 oddmuse_serve_rss($stream, $host, decode_utf8(uri_unescape($space)), 'journal');
252 } elsif (($query) = $url =~ m!^GET (\S*) HTTP/1\.[01]$!
253 and ($host) = $headers->{host} =~ m!^$hosts(?::$port)(.*)$!) {
254 $log->info("Redirecting to https://$host$query");
255 $stream->write("HTTP/1.1 301 Back to port 443!\r\n");
256 $stream->write("Location: https://$host:443$query\r\n");
257 $stream->write("\r\n");
258 } else {
259 # We still rely on things like /do/spaces
260 # result($stream, "59", "I don't know how to handle this $url");
261 return 0;
262 }
263 return 1;
264 }
265  
266 sub oddmuse_serve_robots {
267 my $stream = shift;
268 $log->info("Serving robots.txt");
269 success($stream, 'text/plain');
270 $stream->write(<<'EOT');
271 User-agent: *
272 Disallow: /raw
273 Disallow: /html
274 Disallow: /diff
275 Disallow: /history
276 Disallow: /tag
277 Disallow: /do/comment
278 Disallow: /do/changes
279 Disallow: /do/rss
280 Disallow: /do/atom
281 Disallow: /do/blog/rss
282 Disallow: /do/blog/atom
283 Disallow: /do/new
284 Disallow: /do/more
285 Disallow: /do/match
286 Disallow: /do/search
287 # allowing /do/index!
288 Crawl-delay: 10
289 EOT
290 }
291  
292 sub oddmuse_serve_page {
293 my $stream = shift;
294 my $host = shift;
295 my $space = shift;
296 my $id = shift;
297 my $revision = shift;
298 # cannot use text() because we don't know if we're serving a file or plain
299 # text when querying Oddmuse
300 my $page = oddmuse_get_page($stream, $host, $space, $id, $revision) // return;
301 if (my ($type, $data) = $page =~ /^#FILE (\S+) ?(?:\S+)?\n(.*)/s) {
302 oddmuse_serve_file_page($stream, $id, $type, $data);
303 } else {
304 my $text = oddmuse_gemini_text($stream, $host, $space, $page, $id);
305 oddmuse_serve_gemini_page($stream, $host, $space, $id, $text, $revision);
306 }
307 }
308  
309 # this is required when combining gopher with oddmuse!
310 *oddmuse_text_old = \&App::Phoebe::text;
311 *App::Phoebe::text = \&oddmuse_text_new;
312  
313 sub oddmuse_text_new {
314 my ($stream, $host, $space, $id, $revision) = @_;
315 if (exists $oddmuse_wikis{$host}) {
316 my $text = oddmuse_get_page(@_);
317 return oddmuse_gemini_text($stream, $host, $space, $text, $id);
318 } else {
319 return oddmuse_text_old(@_);
320 }
321 }
322  
323 sub oddmuse_get_page {
324 my $stream = shift;
325 my $host = shift;
326 my $space = shift;
327 my $id = shift;
328 my $revision = shift;
329 my $url = "$oddmuse_wikis{$host}";
330 $url .= "/$space" if $space;
331 $url .= "/raw/" . uri_escape_utf8($id);
332 $url .= "?revision=$revision" if $revision;
333 return oddmuse_get_raw($stream, $url);
334 }
335  
336 # It would be cool if this were streaming...
337 sub oddmuse_get_raw {
338 my $stream = shift;
339 my $url = shift;
340 $log->debug("Requesting $url");
341 my $ua = Mojo::UserAgent->new;
342 my $res = $ua->get($url => {'X-Forwarded-For' => $stream->handle->peerhost})->result;
343 if ($res->is_success) {
344 return $res->text;
345 } elsif ($res->code == 404) {
346 return "";
347 }
348 oddmuse_http_error($stream, $res->code, $res->message, $url); # false
349 }
350  
351 sub oddmuse_http_error {
352 my $stream = shift;
353 my $code = shift;
354 my $message = shift;
355 my $url = shift;
356 if ($code >= 200 and $code < 300) { $code = 20 }
357 elsif ($code == 301) { $code = 31 }
358 elsif ($code >= 300 and $code < 400) { $code = 30 }
359 elsif ($code == 403) { $code = 60 }
360 elsif ($code == 404) { $code = 51 }
361 elsif ($code == 405) { $code = 59 }
362 elsif ($code >= 400 and $code < 500) { $code = 50 }
363 elsif ($code >= 500 and $code < 600) { $code = 40 }
364 else { $code = 50 }
365 $log->warn("$code $message requesting $url");
366 $stream->write(encode_utf8 "$code $message\r\n");
367 return; # false
368 }
369  
370 sub oddmuse_serve_file_page {
371 my $stream = shift;
372 my $id = shift;
373 my $type = shift;
374 my $data = shift;
375 $log->info("Serving $id as $type file");
376 $data = decode_base64($data);
377 $log->debug("Bytes: " . length($data));
378 success($stream, $type);
379 binmode(STDOUT, ":raw");
380 $stream->write($data);
381 }
382  
383 sub oddmuse_serve_gemini_page {
384 my $stream = shift;
385 my $host = shift;
386 my $space = shift;
387 my $id = shift;
388 my $text = shift;
389 my $revision = shift;
390 $log->info("Serve page $id");
391 success($stream);
392 $stream->write(encode_utf8 "# " . normal_to_free($id) . "\n");
393 $stream->write(encode_utf8 $text);
394 if (not $revision and $id !~ /^Comments_on_(.*)/) {
395 my $comments = oddmuse_get_page($stream, $host, $space, "Comments_on_$id");
396 if ($comments) {
397 $stream->write("\n\n## Comments\n");
398 $stream->write(encode_utf8 oddmuse_gemini_text($stream, $host, $space, $comments, $id));
399 }
400 }
401 $stream->write(encode_utf8 oddmuse_footer($stream, $host, $space, $id));
402 }
403  
404 sub oddmuse_gemini_text {
405 my $stream = shift;
406 my $host = shift;
407 my $space = shift;
408 my $text = shift;
409 my $id = shift;
410 # escape the preformatted blocks
411 my $ref = 0;
412 my @escaped;
413 my $link_regex = "([-,.()'%&!?;<> _1-9A-Za-z\x{0080}-\x{fffd}]|[-,.()'%&!?;<> _0-9A-Za-z\x{0080}-\x{fffd}][-,.()'%&!?;<> _0-9A-Za-z\x{0080}-\x{fffd}]+)";
414 my $wiki_word = '(\p{Uppercase}+\p{Lowercase}+\p{Uppercase}\p{Alphabetic}*)';
415 # newline magic: the escaped block does not include the newline; it is
416 # retained in $text so that the following rules still deal with newlines
417 # correctly; when we replace the escaped blocks back in, they'll be without
418 # the trailing newline and fit right in.
419 $text =~ s/^(```.*?\n```)\n/push(@escaped, $1); "\x03" . $ref++ . "\x04\n"/mesg;
420 $text =~ s/^<pre>\n?(.*?\n)<\/pre>\n?/push(@escaped, "```\n$1```\n"); "\x03" . $ref++ . "\x04\n"/mesg;
421 $text =~ s/^((\|.*\|\n)*\|.*\|)/push(@escaped, "```\n$1\n```"); "\x03" . $ref++ . "\x04\n"/meg;
422 my @blocks = split(/\n\n+|(?=\\\\\n)|\n(?=[*-]|=>)|\n\> *\n/, $text);
423 for my $block (@blocks) {
424 $block =~ s/^- /* /g; # fix list items
425 $block =~ s/\s+/ /g; # unwrap lines
426 $block =~ s/^\s+//; # trim
427 $block =~ s/\s+$//; # trim
428 my @links;
429 $block =~ s/^(=>.*)\n?/push(@links, $1); ""/gem;
430 $block =~ s/^$full_url_regex\n?/push(@links, "=> $1"); ""/ge;
431 $block =~ s/\[\[image(?:\/[^\/:]+)*:([^]|]+)\]\]\s*/push(@links, oddmuse_gemini_link($stream, $host, $space, "$1 (image)", $1)); ""/ge;
432 $block =~ s/\[\[image(?:\/[^\/:]+)*:([^]|]+)\|([^\]|]*)\]\]\s*/push(@links, oddmuse_gemini_link($stream, $host, $space, "$2 (image)", $1)) if $2; ""/ge;
433 $block =~ s/\[\[image(?:\/[^\/:]+)*:([^]|]+)\|([^\]|]*)\|([^\]|]+)\]\]\s*/push(@links, oddmuse_gemini_link($stream, $host, $space, "$2 (image)", $1), oddmuse_gemini_link($stream, $host, $space, "$2 (follow-up)", $3)); ""/ge;
434 $block =~ s/\[\[image(?:\/[^\/:]+)*:([^]|]+)\|([^\]|]*)\|([^\]|]*)\|([^\]|]+)\]\]\s*/push(@links, oddmuse_gemini_link($stream, $host, "$2 (image)", $1), oddmuse_gemini_link($stream, $host, $space, "$4 (follow-up)", $3)); ""/ge;
435 $block =~ s/\[([^]]+)\]\($full_url_regex\)/push(@links, oddmuse_gemini_link($stream, $host, $space, $1, $2)); $1/ge;
436 $block =~ s/\[([^]]+)\]\(([^) ]+)\)/push(@links, oddmuse_gemini_link($stream, $host, $space, $1, $2)); $1/ge;
437 $block =~ s/\[$full_url_regex\s+([^]]+)\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $2, $1)); $2/ge;
438 $block =~ s/\[\[([a-z\/-]+):$full_url_regex\|([^]]+)\]\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $3, $2)); $3/ge;
439 # numbered entities are not hashtags, e.g. &#x2605; is ★
440 $block =~ s/&#x([0-9a-f]{4});/chr(hex($1))/gie;
441 $block =~ s/\[\[tag:([^]|]+)\]\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $1, "tag\/$1")); $1/ge;
442 $block =~ s/\[\[tag:([^]|]+)\|([^\]|]+)\]\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $2, "tag\/$1")); $2/ge;
443 $block =~ s/<journal search tag:(\S+)>\n*/push(@links, oddmuse_gemini_link($stream, $host, $space, "Explore the $1 tag", "tag\/$1")); ""/ge;
444 # free links with text, e.g. [[Alex Schroeder|code monkey]]
445 $block =~ s/\[\[$link_regex\|([^\]|]+)\]\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $2, $1)); $2/ge;
446 # free links, e.g. [[Alex Schröder]]
447 $block =~ s/\[\[$link_regex\]\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $1)); $1/ge;
448 # but excluding special typing like [[h/p-note:I'm interested in ...]]
449 $block =~ s/\[\[(?:[^]:]+:)?$link_regex\]\]/$1/g;
450 # handle the ?action=index url abbreviation [Tau_Subsector:?action=index 39 pages]
451 $block =~ s/\[($oddmuse_namespace_regex):\?action=index\s+([^\]]+)\]/push(@links, oddmuse_gemini_link($stream, $host, $1, $2, "do\/index")); $2/ge;
452 # namespaces, e.g. on campaignwiki.org: [Tau_Subsector:HomePage Tau Subsector]
453 $block =~ s/\[($oddmuse_namespace_regex):([^?#[:space:]]*) ([^\]]+)\]/push(@links, oddmuse_gemini_link($stream, $host, $1, $3, $2)); $3/ge;
454 # wiki words with text, e.g. [AlexSchroeder code monkey]
455 $block =~ s/\[$wiki_word ([^\]]+)\]/push(@links, oddmuse_gemini_link($stream, $host, $space, $2, $1)); $2/ge
456 if $oddmuse_wiki_links{$host};
457 $block =~ s/\[Self:\S+ ([^\]]+)\]/$1/ge;
458 $block =~ s/\[new:([^\]:]+)[^\]]*\]/join(' ', split(':', $1)) . ': '/ge;
459 $block =~ s/$wiki_word/push(@links, oddmuse_gemini_link($stream, $host, $space, $1)); $1/ge
460 if $oddmuse_wiki_links{$host};
461 $block =~ s/\[color=([^]]+)\]/colour($stream, $1)/ge;
462 $block =~ s/\[\/color\]/colour($stream, "reset")/ge;
463 $block =~ s/^(=+)(.*?)=*$/'#' x length($1) . ' ' . $2/gem;
464 $block =~ s/<[a-z]+(?:\s+[a-z-]+="[^"]+")>//g;
465 $block =~ s/<\/[a-z]+>//g;
466 $block =~ s/^((?:> .*\n?)+)$/join(" ", split("\n> ", $1))/ge; # unwrap quotes
467 $block =~ s/#(\w+) */push(@links, oddmuse_gemini_link($stream, $host, $space, normal_to_free($1), "tag\/$1")); ""/ge; # hashtags at the end
468 $block .= "\n" if $block and @links; # no empty line if the block was all links
469 $block .= join("\n", uniq(@links));
470 }
471 $text = join("\n\n", @blocks); # add paragraph separation
472 $text =~ s/\n\\\\ //g; # remove paragraph separation for linebreaks
473 $text =~ s/^\* (.*)\n(=> \S+ \1)/$2/mg; # remove list items that are just links
474 $text =~ s/^(=?>.*\n)\n(?==>)/$1/mg; # remove empty lines between links or between links and quotes
475 $text =~ s/^(\* .*\n)\n(?=\* )/$1/mg; # remove empty lines between list items
476 $text =~ s/^Tags: .*/Tags:/m;
477 $text =~ s/\x03(\d+)\x04/$escaped[$1]/ge;
478 return $text . "\n";
479 }
480  
481 sub oddmuse_gemini_link {
482 my $stream = shift;
483 my $host = shift;
484 my $space = shift;
485 my $title = shift;
486 my $id = shift;
487 $id = "page/" . free_to_normal($id) if $id and $id !~ /\//;
488 return gemini_link($stream, $host, $space, $title, $id);
489 }
490  
491 # This is only used for the [color=foo]. I'm keeping this simple (the old eight
492 # colours) because that's what Emacs and therefore Elpher understand.
493 sub colour {
494 my $stream = shift;
495 my $colour = shift;
496 my $code = { black => 30, red => 31, green => 32, yellow => 93, blue => 94, magenta => 35, cyan => 36, white => 37,
497 orange => 33, purple => 35, indigo => 34, violet => 35, # various synonyms
498 reset => 0 };
499 return "" unless exists $code->{$colour};
500 return "\e[$code->{$colour}m";
501 }
502  
503 sub oddmuse_footer {
504 my $stream = shift;
505 my $host = shift;
506 my $space = shift;
507 my $id = shift;
508 my @links;
509 $stream->write("\n\n\n");
510 if (my ($original) = $id =~ /^Comments_on_(.*)/) {
511 push(@links, oddmuse_gemini_link($stream, $host, $space, "Back to the original page", $original));
512 }
513 my $token = $oddmuse_wiki_tokens{$host};
514 $token = $server->{wiki_token}->[0] if not $token and $server->{wiki_token};
515 $stream->write(encode_utf8 "(The access token for short comments is “$token”.)\n");
516 push(@links, oddmuse_gemini_link($stream, $host, $space, "Leave a short comment", "do/comment/$id"));
517 push(@links, oddmuse_gemini_link($stream, $host, $space, "How to leave a longer comment", "How_to_comment_without_a_browser"));
518 push(@links, oddmuse_gemini_link($stream, $host, $space, "Raw comments", "raw/Comments_on_$id")) if $id !~ /^Comments_on_(.*)/;
519 push(@links, oddmuse_gemini_link($stream, $host, $space, "Raw text", "raw/$id"));
520 push(@links, oddmuse_gemini_link($stream, $host, $space, "HTML", "html/$id"));
521 return join("\n", @links, "");
522 }
523  
524 sub oddmuse_serve_tag {
525 my $stream = shift;
526 my $host = shift;
527 my $space = shift;
528 my $tag = shift;
529 success($stream);
530 $log->info("Serving tag $tag");
531 $stream->write("This page lists all the pages tagged $tag.\n");
532 print_link($stream, $host, $space, normal_to_free($tag), "page/$tag");
533 $stream->write("\n");
534 my $url = "$oddmuse_wikis{$host}?raw=1&search=tag:$tag";
535 my $page = oddmuse_get_raw($stream, $url) // return;
536 my @entries = split(/\n\n+/, $page);
537 shift @entries; # skip head
538 foreach my $entry (@entries) {
539 my $data = parse_data($entry);
540 my $id = $data->{title};
541 print_link($stream, $host, $space, normal_to_free($id), "page/$id");
542 }
543 }
544  
545 sub parse_data {
546 my $data = shift;
547 my %result = (description => "");
548 while ($data =~ /(\S+?): (.*?)(?=\n[^ \t]|\Z)/gs) {
549 my ($key, $value) = ($1, $2);
550 $value =~ s/\n\t/\n/g;
551 $result{$key} = $value;
552 }
553 return \%result;
554 }
555  
556 sub oddmuse_serve_raw {
557 my $stream = shift;
558 my $host = shift;
559 my $space = shift;
560 my $id = shift;
561 my $revision = shift;
562 my $url = "$oddmuse_wikis{$host}";
563 $url .= "/$space" if $space;
564 $url .= "/raw/" . uri_escape_utf8($id);
565 $url .= "?revision=$revision" if $revision;
566 my $page = oddmuse_get_raw($stream, $url) // return;
567 if (my ($type, $data) = $page =~ /^#FILE (\S+) ?(?:\S+)?\n(.*)/s) {
568 oddmuse_serve_file_page($stream, $id, $type, $data);
569 return;
570 }
571 $log->info("Serving raw $id");
572 success($stream, 'text/plain; charset=UTF-8');
573 $stream->write(encode_utf8 $page);
574 }
575  
576 sub oddmuse_serve_html {
577 my $stream = shift;
578 my $host = shift;
579 my $space = shift;
580 my $id = shift;
581 my $revision = shift;
582 my $url = "$oddmuse_wikis{$host}";
583 $url .= "/$space" if $space;
584 $url .= "/" . uri_escape_utf8($id);
585 $url .= "?revision=$revision" if $revision;
586 my $page = oddmuse_get_raw($stream, $url) // return;
587 $log->info("Serving $id as HTML");
588 success($stream, 'text/html');
589 $stream->write(encode_utf8 $page);
590 }
591  
592 sub free_to_normal {
593 my $title = shift;
594 $title =~ s/^ +//g;
595 $title =~ s/ +$//g;
596 $title =~ s/ +/_/g;
597 return $title;
598 }
599  
600 sub normal_to_free {
601 my $title = shift;
602 $title =~ s/_/ /g;
603 return $title;
604 }
605  
606 # this is required when combining gopher with oddmuse!
607 *blog_pages_old = \&App::Phoebe::blog_pages;
608 *App::Phoebe::blog_pages = \&blog_pages;
609  
610 sub blog_pages {
611 my $stream = shift;
612 my $host = shift;
613 my $space = shift;
614 my $n = shift;
615 if (exists $oddmuse_wikis{$host}) {
616 my $url = "$oddmuse_wikis{$host}?raw=1;action=index;match=^\\d\\d\\d\\d\\-\\d\\d-\\d\\d;n=$n";
617 return map { s/_/ /g; $_ } split(/\n/, oddmuse_get_raw($stream, $url) // '');
618 }
619 return blog_pages_old($stream, $host, $space, $n);
620 }
621  
622 sub oddmuse_blog {
623 my $stream = shift;
624 my $host = shift;
625 my $space = shift;
626 my $n = shift;
627 my @pages = blog_pages($stream, $host, $space, $n);
628 return unless @pages;
629 for my $id (@pages) {
630 print_link($stream, $host, $space, normal_to_free($id), "page/$id");
631 }
632 print_link($stream, $host, $space, "More...", "do/blog/" . 10 * $n);
633 }
634  
635 sub oddmuse_serve_blog {
636 my $stream = shift;
637 my $host = shift;
638 my $space = shift;
639 my $n = shift;
640 $log->info("Serving $n blog items for $host");
641 success($stream);
642 $stream->write("# Blog\n");
643 $stream->write("Serving the last $n items.\n");
644 oddmuse_blog($stream, $host, $space, $n);
645 }
646  
647 sub oddmuse_serve_index {
648 my $stream = shift;
649 my $host = shift;
650 my $space = shift;
651 $log->info("Serving all pages for $host");
652 success($stream);
653 $stream->write("# All Pages\n");
654 # we need to call our own: if we import pages from App:Phoebe, we get a copy
655 # and would have to remap that just like we do App::Phoebe::pages below
656 my @pages = oddmuse_pages_new($stream, $host, $space);
657 return unless @pages;
658 for my $id (@pages) {
659 print_link($stream, $host, $space, normal_to_free($id), "page/$id");
660 }
661 }
662  
663 sub oddmuse_serve_match {
664 my $stream = shift;
665 my $host = shift;
666 my $space = shift;
667 my $term = shift;
668 $log->info("Serving pages matching $term");
669 success($stream);
670 $stream->write(encode_utf8 "# Pages matching ‘$term’\n");
671 # we need to call our own: if we import pages from App:Phoebe, we get a copy
672 # and would have to remap that just like we do App::Phoebe::pages below
673 my @pages = oddmuse_pages_new($stream, $host, $space, $term);
674 for my $id (@pages) {
675 print_link($stream, $host, $space, normal_to_free($id), "page/$id");
676 }
677 }
678  
679 sub oddmuse_serve_search {
680 my $stream = shift;
681 my $host = shift;
682 my $space = shift;
683 my $term = shift;
684 $log->info("Serving search for $term");
685 success($stream);
686 $stream->write(encode_utf8 "# Search ‘$term’\n");
687 my $url = "$oddmuse_wikis{$host}?raw=1&search=" . uri_escape_utf8($term);
688 my $page = oddmuse_get_raw($stream, $url) // return;
689 my @entries = split(/\n\n+/, $page);
690 shift @entries; # skip head
691 foreach my $entry (@entries) {
692 my $data = parse_data($entry);
693 my $id = $data->{title};
694 print_link($stream, $host, $space, normal_to_free($id), "page/$id");
695 }
696 }
697  
698 # this is required when combining gopher with oddmuse!
699 *oddmuse_pages_old = \&App::Phoebe::pages;
700 *App::Phoebe::pages = \&oddmuse_pages_new;
701  
702 sub oddmuse_pages_new {
703 my $stream = shift;
704 my $host = shift;
705 my $space = shift;
706 my $re = shift;
707 if (exists $oddmuse_wikis{$host}) {
708 my $url = "$oddmuse_wikis{$host}?raw=1;action=index";
709 $url .= ";ns=$space" if $space;
710 $url .= ";match=" . uri_escape_utf8($re) if $re;
711 return map { s/_/ /g; $_ } split(/\n/, oddmuse_get_raw($stream, $url));
712 }
713 return oddmuse_pages_old($stream, $host, $space, $re);
714 }
715  
716 # this is required when combining gopher with oddmuse!
717 *oddmuse_search_old = \&App::Phoebe::search;
718 *App::Phoebe::search = \&oddmuse_search_new;
719  
720 sub oddmuse_search_new {
721 my $stream = shift;
722 my $host = shift;
723 my $space = shift;
724 my $re = shift;
725 if (exists $oddmuse_wikis{$host}) {
726 my $url = "$oddmuse_wikis{$host}?raw=1";
727 $url .= ";ns=$space" if $space;
728 $url .= ";context=0;search=" . uri_escape($re) if $re;
729 return map { s/_/ /g; $_ } split(/\n/, oddmuse_get_raw($stream, $url));
730 }
731 return oddmuse_search_old($stream, $host, $space, $re, @_);
732 }
733  
734 sub oddmuse_serve_changes {
735 my $stream = shift;
736 my $host = shift;
737 my $space = shift;
738 my $n = shift;
739 my $style = shift;
740 my $all = shift;
741 $log->info("Serving changes for $n days");
742 success($stream);
743 $stream->write("# Changes\n");
744 if (not $style) { print_link($stream, $host, $space, "Colour changes", "do/changes/$n/colour") }
745 elsif ($style eq "colour") { print_link($stream, $host, $space, "Fancy changes", "do/changes/$n/fancy") }
746 elsif ($style eq "fancy") { print_link($stream, $host, $space, "Normal changes", "do/changes/$n") }
747 print_link($stream, $host, $space, "Atom Feed", "do/atom");
748 print_link($stream, $host, $space, "RSS Feed", "do/rss");
749 my $url = "$oddmuse_wikis{$host}?raw=1;action=rc;all=1;showedit=1;days=$n";
750 if ($space) {
751 $url .= ";ns=$space";
752 } if (not $all) {
753 $url .= ";local=1";
754 }
755 my $page = oddmuse_get_raw($stream, $url) // return;
756 my @entries = split(/\n\n+/, $page);
757 shift @entries; # skip head
758 my $log;
759 foreach my $entry (@entries) {
760 my $data = parse_data($entry);
761 # namespaces
762 my $ns = $space;
763 my $title = $data->{title};
764 if (not $ns and $title =~ /:/) {
765 ($ns, $title) = split(/:/, $title);
766 }
767 # timestamp from 2020-07-22T20:59Z back to a number
768 my $ts = $data->{"last-modified"};
769 $ts =~ s/Z/:00Z/; # apparently seconds are mandatory?
770 $ts = DateTime::Format::ISO8601->parse_datetime($ts)->epoch();
771 # author from some string back to a bogus hash: [0-7]{4}
772 my $author = $data->{generator};
773 $author = bogus_hash($stream, encode_utf8($author)) unless $author =~ /^[0-7]{4}$/;
774 push(@$log, [
775 $ts,
776 free_to_normal($title),
777 $data->{revision},
778 $author,
779 $host,
780 $ns,
781 1]); # show space
782 }
783 # taking the head of the @$log to get new log entries
784 $stream->write("Showing up to $n days.\n");
785 changes($stream,
786 scalar(@$log), # just show them all
787 sub { $stream->write("## " . shift . "\n") },
788 sub { $stream->write(encode_utf8 shift . " by " . colourize($stream, shift, $style) . "\n") },
789 sub {
790 my ($host, $space, $title, $id) = @_;
791 $title =~ s/_/ /g;
792 print_link($stream, $host, $space, $title, $id) },
793 sub { $stream->write(encode_utf8 join("\n", @_, "")) },
794 sub { @{shift(@$log) } if @$log },
795 sub { 1 }, # show a diff link, always
796 );
797 # there is always more...
798 $stream->write("\n");
799 print_link($stream, $host, $space, "More...", "do/changes/" . 2 * $n . ($style ? "/$style" : ""));
800 }
801  
802 sub oddmuse_serve_history {
803 my $stream = shift;
804 my $host = shift;
805 my $space = shift;
806 my $id = shift;
807 my $style = shift;
808 success($stream);
809 $log->info("Serve history for $id");
810 $stream->write("# Page history for " . normal_to_free($id) . "\n");
811 if (not $style) { print_link($stream, $host, $space, "Colour history", "history/$id/colour") }
812 elsif ($style eq "colour") { print_link($stream, $host, $space, "Fancy history", "history/$id/fancy") }
813 elsif ($style eq "fancy") { print_link($stream, $host, $space, "Normal history", "history/$id") }
814 my $url = "$oddmuse_wikis{$host}?raw=1;action=history;id=" . uri_escape_utf8($id);
815 $url .= ";ns=$space" if $space;
816 my $page = oddmuse_get_raw($stream, $url) // return;
817 my @entries = split(/\n\n+/, $page);
818 shift @entries; # skip head
819 my $log;
820 foreach my $entry (@entries) {
821 my $data = parse_data($entry);
822 # timestamp from 2020-07-22T20:59Z back to a number
823 my $ts = $data->{"last-modified"};
824 $ts =~ s/Z/:00Z/; # apparently seconds are mandatory?
825 $ts = DateTime::Format::ISO8601->parse_datetime($ts)->epoch();
826 # author from some string back to a bogus hash: [0-7]{4}
827 my $author = $data->{generator};
828 $author = bogus_hash($stream, encode_utf8($author)) unless $author =~ /^[0-7]{4}$/;
829 push(@$log, [
830 $ts,
831 free_to_normal($data->{title}),
832 $data->{revision},
833 $author,
834 $host,
835 $space, # space
836 0]); # show space
837 }
838 # taking the head of the @$log to get new log entries
839 changes($stream,
840 scalar(@$log), # just show them all
841 sub { $stream->write("## " . shift . "\n") },
842 sub { $stream->write(shift . " by " . colourize($stream, shift, $style) . "\n") },
843 sub {
844 my ($host, $space, $title, $id) = @_;
845 $title =~ s/_/ /g;
846 print_link($stream, $host, $space, $title, $id) },
847 sub { $stream->write(join("\n", @_, "")) },
848 sub { @{shift(@$log) } if @$log },
849 sub { 1 }, # show a diff link, always
850 );
851 }
852  
853 sub oddmuse_serve_diff {
854 my $stream = shift;
855 my $host = shift;
856 my $space = shift;
857 my $id = shift;
858 my $revision = shift;
859 my $style = shift;
860 $log->info("Serving the diff of $id");
861 success($stream);
862 $stream->write("# Differences for " . normal_to_free($id) . "\n");
863 if (not $style) { print_link($stream, $host, $space, "Colour diff", "diff/$id/$revision/colour") }
864 else { print_link($stream, $host, $space, "Normal diff", "diff/$id/$revision") }
865 $stream->write("Showing the differences between revision $revision and the current revision.\n");
866 my $url = $oddmuse_wikis{$host} . ($space ? "/$space" : "") . "/raw/" . uri_escape_utf8($id);
867 my $new = oddmuse_get_raw($stream, $url);
868 $url .= "?revision=$revision" if $revision;
869 my $old = oddmuse_get_raw($stream, $url);
870 if (not $style) {
871 diff($old, $new,
872 sub { $stream->write(encode_utf8 "$_\n") for @_ },
873 sub { $stream->write(encode_utf8 "> $_\n") for map { $_||"⏎" } @_ },
874 sub { $stream->write(encode_utf8 "> $_\n") for map { $_||"⏎" } @_ },
875 sub { "「$_[0]」" });
876 } else {
877 diff($old, $new,
878 sub { $stream->write(encode_utf8 "$_\n") for @_ },
879 sub { $stream->write(encode_utf8 "> \033[31m$_\033[0m\n") for map { $_||"⏎" } @_ },
880 sub { $stream->write(encode_utf8 "> \033[32m$_\033[0m\n") for map { $_||"⏎" } @_ },
881 sub { "\033[1m$_[0]\033[22m" });
882 }
883 }
884  
885 sub oddmuse_serve_rss {
886 my $stream = shift;
887 my $host = shift;
888 my $space = shift;
889 my $action = shift;
890 my $scheme = 'gemini';
891 my $port = port($stream);
892 $log->info("Serving Gemini RSS");
893 success($stream, "application/rss+xml");
894 $stream->write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
895 $stream->write("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n");
896 my $url = "$oddmuse_wikis{$host}?action=$action;raw=1;full=1";
897 if ($space) {
898 $url .= ";ns=$space";
899 }
900 my $page = oddmuse_get_raw($stream, $url) // return;
901 my @entries = split(/\n\n+/, $page);
902 my $entry = shift @entries;
903 my $data = parse_data($entry);
904 $stream->write("<channel>\n");
905 $stream->write(encode_utf8 "<title>" . quote_html($data->{title}) . "</title>\n");
906 $stream->write(encode_utf8 "<description>" . quote_html($data->{description}) . "</description>\n");
907 $stream->write("<link>$scheme://$host:$port/</link>\n");
908 $stream->write("<atom:link rel=\"self\" type=\"application/rss+xml\" href=\"$scheme://$host:$port/do/rss\" />\n");
909 $stream->write("<generator>Phoebe + Config</generator>\n");
910 $stream->write("<docs>http://blogs.law.harvard.edu/tech/rss</docs>\n");
911 my $dir = $oddmuse_wiki_dirs{$host};
912 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(modified("$dir/pageidx"));
913 $stream->write("<updated>"
914 . sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
915 . "</updated>\n");
916 while (@entries) {
917 $data = parse_data(shift(@entries));
918 $stream->write("<item>\n");
919 # namespaces
920 my $ns;
921 my $title = $data->{title};
922 if ($title =~ /:/) {
923 ($ns, $title) = split(/:/, $title);
924 }
925 my $id = free_to_normal($title);
926 $stream->write(encode_utf8 "<title>" . quote_html($data->{title}) . "</title>\n");
927 my $link = "gemini://$host:$port/" . ($ns ? "$ns/" : "") . "page/" . uri_escape_utf8($id);
928 $stream->write("<link>$link</link>\n");
929 $stream->write("<guid>$link</guid>\n");
930 $link = "gemini://$host:$port/" . ($ns ? "$ns/" : "") . "page/Comments_on_" . uri_escape_utf8($id);
931 $stream->write("<comments>$link</comments>\n");
932 my $summary = quote_html(oddmuse_gemini_text($stream, $host, $space, $data->{description}, $id));
933 $stream->write(encode_utf8 "<description>$summary</description>\n") if $summary;
934 # timestamp from 2020-07-22T20:59Z back to a number
935 my $ts = $data->{"last-modified"};
936 $ts =~ s/Z/:00Z/; # apparently seconds are mandatory?
937 $ts = DateTime::Format::ISO8601->parse_datetime($ts)->epoch();
938 my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($ts); # Sat, 07 Sep 2002 00:00:01 GMT
939 $stream->write("<pubDate>"
940 . sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", qw(Sun Mon Tue Wed Thu Fri Sat)[$wday], $mday,
941 qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$mon], $year + 1900, $hour, $min, $sec)
942 . "</pubDate>\n");
943 $stream->write("</item>\n");
944 };
945 $stream->write("</channel>\n");
946 $stream->write("</rss>\n");
947 }
948  
949 sub oddmuse_serve_atom {
950 my $stream = shift;
951 my $host = shift;
952 my $space = shift;
953 my $action = shift;
954 my $port = port($stream);
955 $log->info("Serving Gemini Atom");
956 success($stream, "application/atom+xml");
957 $stream->write(qq{<?xml version="1.0" encoding="UTF-8"?>\n});
958 $stream->write("<feed xmlns=\"http://www.w3.org/2005/Atom\">\n");
959 $stream->write("<link href=\"gemini:/$host:$port/\"/>\n");
960 $stream->write("<link rel=\"self\" type=\"application/atom+xml\" href=\"gemini://$host:$port/do/atom\"/>\n");
961 $stream->write("<id>gemini:/$host:$port/do/atom</id>\n");
962 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(modified("$oddmuse_wiki_dirs{$host}/pageidx"));
963 $stream->write("<updated>"
964 . sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year + 1900, $mon + 1, $mday, $hour, $min, $sec)
965 . "</updated>\n");
966 $stream->write("<generator uri=\"gemini://$host:$port/\" version=\"1.0\">Phoebe + Config</generator>\n");
967 # now get the data and print the entries
968 my $url = "$oddmuse_wikis{$host}?action=$action;raw=1;full=1";
969 if ($space) {
970 $url .= ";ns=$space";
971 }
972 my $page = oddmuse_get_raw($stream, $url) // return;
973 my @entries = split(/\n\n+/, $page);
974 my $data = parse_data(shift @entries);
975 $stream->write(encode_utf8 "<title>" . quote_html($data->{title}) . "</title>\n");
976 while (@entries) {
977 $data = parse_data(shift @entries);
978 $stream->write("<entry>\n");
979 my $name = $data->{title};
980 my $id = free_to_normal($name);
981 $stream->write(encode_utf8 "<title>$name</title>\n");
982 my $link = "gemini://$host:$port/page/" . uri_escape_utf8($id);
983 $stream->write("<link href=\"$link\"/>\n");
984 $stream->write("<id>$link</id>\n");
985 my $summary = quote_html(oddmuse_gemini_text($stream, $host, $space, $data->{description}, $id));
986 $stream->write(encode_utf8 "<content type=\"text\">$summary</content>\n") if $summary;
987 $stream->write("<updated>$data->{'last-modified'}</updated>\n");
988 $stream->write("</entry>\n");
989 };
990 $stream->write("</feed>\n");
991 }
992  
993 sub oddmuse_comment {
994 my $stream = shift;
995 my $host = shift;
996 my $space = shift;
997 my $id = shift;
998 my $query = shift; # token or comment
999 my $port = port($stream);
1000 if (not $id) {
1001 $log->debug("The URL lacks a page name");
1002 result($stream, "59", "The URL lacks a page name");
1003 return;
1004 }
1005 my $name = oddmuse_fingerprint_name($stream, $host, $query);
1006 return unless defined $name;
1007 if (not $query) {
1008 result($stream, "10", "Short comment");
1009 return;
1010 }
1011 $id = "Comments_on_$id" unless $id =~ /^Comments_on_/;
1012 my $token = $oddmuse_wiki_tokens{$host};
1013 $token = $server->{wiki_token}->[0] if not $token and $server->{wiki_token};
1014 my $ua = Mojo::UserAgent->new;
1015 my $tx = $ua->post(
1016 $oddmuse_wikis{$host}
1017 => {'X-Forwarded-For' => $stream->handle->peerhost}
1018 => form => {
1019 title => $id,
1020 ns => $space,
1021 aftertext => $query,
1022 username => $name,
1023 answer => $token,
1024 gemini => 1 });
1025 $log->debug("Got " . $tx->result->code . " response");
1026 if ($tx->result->code == 302) {
1027 my $url = "gemini://$host:$port";
1028 $url .= "/$space" if $space;
1029 result($stream, "30", "$url/page/" . uri_escape_utf8($id) . "");
1030 return;
1031 }
1032 $stream->write("59 Got HTTP code " . $tx->result->code . " " . $tx->result->message
1033 . " (" . $tx->req->url->to_abs . " " . $tx->req->params . ")\r\n");
1034 }
1035  
1036 # If the fingerprint exists in our file, no need to ask for the $token; it
1037 # expires after a day (24 * 60 * 60 seconds). If no fingerprint is found, ask
1038 # for a cert.
1039 sub oddmuse_fingerprint_name {
1040 my $stream = shift;
1041 my $host = shift;
1042 my $token = shift;
1043 # This requires SSL_verify_mode => SSL_VERIFY_PEER and SSL_verify_callback =>
1044 # \&verify_fingerprint (which must not reject self-signed certificates).
1045 my $fingerprint = $stream->handle->get_fingerprint();
1046 if (not $fingerprint) {
1047 result($stream, "60", "You need a client certificate with a common name to edit this wiki");
1048 return;
1049 }
1050 my $dir = $server->{wiki_dir};
1051 my @lines;
1052 my $now = time();
1053 # Read the known fingerprint from the file.
1054 my %fingerprints;
1055 my $file = "$dir/fingerprints";
1056 %fingerprints = split(/\s+/, read_text($file)) if -e $file;
1057 # Forget about fingerprints older than 10min.
1058 for my $fp (keys %fingerprints) {
1059 delete $fingerprints{$fp} if $fingerprints{$fp} > $now + 600;
1060 }
1061 my @tokens;
1062 push(@tokens, $oddmuse_wiki_tokens{$host}) if $oddmuse_wiki_tokens{$host};
1063 push(@tokens, @{$server->{wiki_token}}) unless @tokens;
1064 if (not $fingerprints{$fingerprint}) {
1065 if (not $token) {
1066 result($stream, "10", "Token required to edit this wiki");
1067 } elsif (not grep { $token eq $_ } @tokens) {
1068 result($stream, "59", "Wrong token");
1069 } else {
1070 result($stream, "10", "Short comment");
1071 $fingerprints{$fingerprint} = $now;
1072 }
1073 # Save new or updated fingerprint timestamp.
1074 write_text($file, join("\n", map { "$_ $fingerprints{$_}" } keys %fingerprints));
1075 # Return undefined so that the user needs to react to the message above.
1076 return;
1077 }
1078 # Fingerprint found!
1079 $fingerprints{$fingerprint} = $now;
1080 # Save new or updated fingerprint timestamp.
1081 write_text($file, join("\n", map { "$_ $fingerprints{$_}" } keys %fingerprints));
1082 # User wants to provide no name: use "" so that we have a defined name.
1083 return ($stream->handle->peer_certificate('cn') || "");
1084 }