]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
reply: allow ":none=$REASON" in "replyto" config
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
7 use strict;
8 use warnings;
9 use PublicInbox::MsgTime qw(msg_datestamp);
10 use PublicInbox::Hval qw/ascii_html obfuscate_addrs/;
11 use PublicInbox::Linkify;
12 use PublicInbox::MID qw/id_compress mid_escape mids references/;
13 use PublicInbox::MsgIter;
14 use PublicInbox::Address;
15 use PublicInbox::WwwStream;
16 use PublicInbox::Reply;
17 require POSIX;
18 use Time::Local qw(timegm);
19
20 use constant COLS => 72;
21 use constant INDENT => '  ';
22 use constant TCHILD => '` ';
23 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
24
25 # public functions: (unstable)
26
27 sub msg_html {
28         my ($ctx, $mime, $more, $smsg) = @_;
29         my $hdr = $mime->header_obj;
30         my $ibx = $ctx->{-inbox};
31         my $obfs_ibx = $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
32         my $tip = _msg_html_prepare($hdr, $ctx, $more, 0);
33         my $end = 2;
34         PublicInbox::WwwStream->response($ctx, 200, sub {
35                 my ($nr, undef) = @_;
36                 if ($nr == 1) {
37                         # $more cannot be true w/o $smsg being defined:
38                         my $upfx = $more ? '../'.mid_escape($smsg->mid).'/' : '';
39                         $tip . multipart_text_as_html($mime, $upfx, $obfs_ibx) .
40                                 '</pre><hr>'
41                 } elsif ($more && @$more) {
42                         ++$end;
43                         msg_html_more($ctx, $more, $nr);
44                 } elsif ($nr == $end) {
45                         # fake an EOF if generating the footer fails;
46                         # we want to at least show the message if something
47                         # here crashes:
48                         eval {
49                                 '<pre>' . html_footer($hdr, 1, $ctx) .
50                                 '</pre>' . msg_reply($ctx, $hdr)
51                         };
52                 } else {
53                         undef
54                 }
55         });
56 }
57
58 sub msg_page {
59         my ($ctx) = @_;
60         my $mid = $ctx->{mid};
61         my $ibx = $ctx->{-inbox};
62         my ($first, $more);
63         my $smsg;
64         if (my $srch = $ibx->search) {
65                 my ($id, $prev);
66                 $smsg = $srch->next_by_mid($mid, \$id, \$prev);
67                 $first = $ibx->msg_by_smsg($smsg) if $smsg;
68                 if ($first) {
69                         my $next = $srch->next_by_mid($mid, \$id, \$prev);
70                         $more = [ $id, $prev, $next ] if $next;
71                 }
72                 return unless $first;
73         } else {
74                 $first = $ibx->msg_by_mid($mid) or return;
75         }
76         msg_html($ctx, PublicInbox::MIME->new($first), $more, $smsg);
77 }
78
79 sub msg_html_more {
80         my ($ctx, $more, $nr) = @_;
81         my $str = eval {
82                 my ($id, $prev, $smsg) = @$more;
83                 my $mid = $ctx->{mid};
84                 $smsg = $ctx->{-inbox}->smsg_mime($smsg);
85                 my $next = $ctx->{srch}->next_by_mid($mid, \$id, \$prev);
86                 @$more = $next ? ($id, $prev, $next) : ();
87                 if ($smsg) {
88                         my $mime = $smsg->{mime};
89                         my $upfx = '../' . mid_escape($smsg->mid) . '/';
90                         _msg_html_prepare($mime->header_obj, $ctx, $more, $nr) .
91                                 multipart_text_as_html($mime, $upfx,
92                                                         $ctx->{-obfs_ibx}) .
93                                 '</pre><hr>'
94                 } else {
95                         '';
96                 }
97         };
98         if ($@) {
99                 warn "Error lookup up additional messages: $@\n";
100                 $str = '<pre>Error looking up additional messages</pre>';
101         }
102         $str;
103 }
104
105 # /$INBOX/$MESSAGE_ID/#R
106 sub msg_reply {
107         my ($ctx, $hdr) = @_;
108         my $se_url =
109          'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
110         my $p_url =
111          'https://en.wikipedia.org/wiki/Posting_style#Interleaved_style';
112
113         my $info = '';
114         my $ibx = $ctx->{-inbox};
115         if (my $url = $ibx->{infourl}) {
116                 $url = PublicInbox::Hval::prurl($ctx->{env}, $url);
117                 $info = qq(\n  List information: <a\nhref="$url">$url</a>\n);
118         }
119
120         my ($arg, $link, $reply_to_all) =
121                         PublicInbox::Reply::mailto_arg_link($ibx, $hdr);
122         if (ref($arg) eq 'SCALAR') {
123                 return '<pre id=R>'.ascii_html($$arg).'</pre>';
124         }
125
126         # mailto: link only works if address obfuscation is disabled
127         if ($link) {
128                 $link = <<EOF;
129
130 * If your mail client supports setting the <b>In-Reply-To</b> header
131   via mailto: links, try the <a
132 href="$link">mailto: link</a>
133 EOF
134         }
135
136         push @$arg, '/path/to/YOUR_REPLY';
137         $arg = ascii_html(join(" \\\n    ", '', @$arg));
138         <<EOF
139 <hr><pre
140 id=R><b>Reply instructions:</b>
141
142 You may reply publically to <a
143 href=#t>this message</a> via plain-text email
144 using any one of the following methods:
145
146 * Save the following mbox file, import it into your mail client,
147   and $reply_to_all from there: <a
148 href=raw>mbox</a>
149
150   Avoid top-posting and favor interleaved quoting:
151   <a
152 href="$p_url">$p_url</a>
153 $info
154 * Reply using the <b>--to</b>, <b>--cc</b>, and <b>--in-reply-to</b>
155   switches of git-send-email(1):
156
157   git send-email$arg
158
159   <a
160 href="$se_url">$se_url</a>
161 $link</pre>
162 EOF
163 }
164
165 sub in_reply_to {
166         my ($hdr) = @_;
167         my $refs = references($hdr);
168         $refs->[-1];
169 }
170
171 sub fold_addresses ($) {
172         return $_[0] if length($_[0]) <= COLS;
173         # try to fold on commas after non-word chars before $lim chars,
174         # Try to get the "," preceeded by ">" or ")", but avoid folding
175         # on the comma where somebody uses "Lastname, Firstname".
176         # We also try to keep the last and penultimate addresses in
177         # the list on the same line if possible, hence the extra \z
178         # Fall back to folding on spaces at $lim + 1 chars
179         my $lim = COLS - 8; # 8 = "\t" display width
180         my $too_long = $lim + 1;
181         $_[0] =~ s/\s*\z//s; # Email::Simple doesn't strip trailing spaces
182         $_[0] = join("\n\t",
183                 ($_[0] =~ /(.{0,$lim}\W(?:,|\z)|
184                                 .{1,$lim}(?:,|\z)|
185                                 .{1,$lim}|
186                                 .{$too_long,}?)(?:\s|\z)/xgo));
187 }
188
189 sub _hdr_names_html ($$) {
190         my ($hdr, $field) = @_;
191         my $val = $hdr->header($field) or return '';
192         ascii_html(join(', ', PublicInbox::Address::names($val)));
193 }
194
195 sub nr_to_s ($$$) {
196         my ($nr, $singular, $plural) = @_;
197         return "0 $plural" if $nr == 0;
198         $nr == 1 ? "$nr $singular" : "$nr $plural";
199 }
200
201 # this is already inside a <pre>
202 sub index_entry {
203         my ($smsg, $ctx, $more) = @_;
204         my $srch = $ctx->{srch};
205         my $subj = $smsg->subject;
206         my $mid_raw = $smsg->mid;
207         my $id = id_compress($mid_raw, 1);
208         my $id_m = 'm'.$id;
209
210         my $root_anchor = $ctx->{root_anchor} || '';
211         my $irt;
212         my $obfs_ibx = $ctx->{-obfs_ibx};
213
214         my $rv = "<a\nhref=#e$id\nid=m$id>*</a> ";
215         $subj = '<b>'.ascii_html($subj).'</b>';
216         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
217         $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id_m;
218         $rv .= $subj . "\n";
219         $rv .= _th_index_lite($mid_raw, \$irt, $id, $ctx);
220         my @tocc;
221         my $mime = $smsg->{mime};
222         my $hdr = $mime->header_obj;
223         my $from = _hdr_names_html($hdr, 'From');
224         obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
225         $rv .= "From: $from @ ".fmt_ts($smsg->ds)." UTC";
226         my $upfx = $ctx->{-upfx};
227         my $mhref = $upfx . mid_escape($mid_raw) . '/';
228         $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
229         $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
230         my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
231         my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
232         my ($tlen, $clen) = (length($to), length($cc));
233         my $to_cc = '';
234         if (($tlen + $clen) > COLS) {
235                 $to_cc .= '  To: '.$to."\n" if $tlen;
236                 $to_cc .= '  Cc: '.$cc."\n" if $clen;
237         } else {
238                 if ($tlen) {
239                         $to_cc .= '  To: '.$to;
240                         $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
241                 } else {
242                         $to_cc .= '  Cc: '.$cc if $clen;
243                 }
244                 $to_cc .= "\n";
245         }
246         obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
247         $rv .= $to_cc;
248
249         my $mapping = $ctx->{mapping};
250         if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
251                 my $mirt = PublicInbox::Hval->new_msgid($irt);
252                 my $href = $upfx . $mirt->{href}. '/';
253                 my $html = $mirt->as_html;
254                 $rv .= qq(In-Reply-To: &lt;<a\nhref="$href">$html</a>&gt;\n)
255         }
256         $rv .= "\n";
257
258         # scan through all parts, looking for displayable text
259         msg_iter($mime, sub { $rv .= add_text_body($mhref, $obfs_ibx, $_[0]) });
260
261         # add the footer
262         $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
263                 "<a\nhref=\"$mhref\">permalink</a>" .
264                 " <a\nhref=\"${mhref}raw\">raw</a>" .
265                 " <a\nhref=\"${mhref}#R\">reply</a>";
266
267         my $hr;
268         if (my $pct = $ctx->{pct}) { # used by SearchView.pm
269                 $rv .= "\t[relevance $pct->{$mid_raw}%]";
270                 $hr = 1;
271         } elsif ($mapping) {
272                 my $nested = 'nested';
273                 my $flat = 'flat';
274                 my $end = '';
275                 if ($ctx->{flat}) {
276                         $hr = 1;
277                         $flat = "<b>$flat</b>";
278                 } else {
279                         $nested = "<b>$nested</b>";
280                 }
281                 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
282                 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
283                 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
284         } else {
285                 $hr = $ctx->{-hr};
286         }
287
288         $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
289         $rv;
290 }
291
292 sub pad_link ($$;$) {
293         my ($mid, $level, $s) = @_;
294         $s ||= '...';
295         my $id = id_compress($mid, 1);
296         (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
297 }
298
299 sub _th_index_lite {
300         my ($mid_raw, $irt, $id, $ctx) = @_;
301         my $rv = '';
302         my $mapping = $ctx->{mapping} or return $rv;
303         my $pad = '  ';
304         my $mid_map = $mapping->{$mid_raw};
305         defined $mid_map or
306                 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
307         my ($attr, $node, $idx, $level) = @$mid_map;
308         my $children = $node->{children};
309         my $nr_c = scalar @$children;
310         my $nr_s = 0;
311         my $siblings;
312         if (my $smsg = $node->{smsg}) {
313                 ($$irt) = (($smsg->{references} || '') =~ m/<([^>]+)>\z/);
314         }
315         my $irt_map = $mapping->{$$irt} if defined $$irt;
316         if (defined $irt_map) {
317                 $siblings = $irt_map->[1]->{children};
318                 $nr_s = scalar(@$siblings) - 1;
319                 $rv .= $pad . $irt_map->[0];
320                 if ($idx > 0) {
321                         my $prev = $siblings->[$idx - 1];
322                         my $pmid = $prev->{id};
323                         if ($idx > 2) {
324                                 my $s = ($idx - 1). ' preceding siblings ...';
325                                 $rv .= pad_link($pmid, $level, $s);
326                         } elsif ($idx == 2) {
327                                 my $ppmid = $siblings->[0]->{id};
328                                 $rv .= $pad . $mapping->{$ppmid}->[0];
329                         }
330                         $rv .= $pad . $mapping->{$pmid}->[0];
331                 }
332         }
333         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
334         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
335         $attr =~ s!\n\z!</b>\n!s;
336         $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
337         $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
338         $rv .= "<b>@ $attr";
339         if ($nr_c) {
340                 my $cmid = $children->[0]->{id};
341                 $rv .= $pad . $mapping->{$cmid}->[0];
342                 if ($nr_c > 2) {
343                         my $s = ($nr_c - 1). ' more replies';
344                         $rv .= pad_link($cmid, $level + 1, $s);
345                 } elsif (my $cn = $children->[1]) {
346                         $rv .= $pad . $mapping->{$cn->{id}}->[0];
347                 }
348         }
349
350         my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
351         if ($next) {
352                 my $nmid = $next->{id};
353                 $rv .= $pad . $mapping->{$nmid}->[0];
354                 my $nnext = $nr_s - $idx;
355                 if ($nnext > 2) {
356                         my $s = ($nnext - 1).' subsequent siblings';
357                         $rv .= pad_link($nmid, $level, $s);
358                 } elsif (my $nn = $siblings->[$idx + 2]) {
359                         $rv .= $pad . $mapping->{$nn->{id}}->[0];
360                 }
361         }
362         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
363 }
364
365 sub walk_thread {
366         my ($rootset, $ctx, $cb) = @_;
367         my @q = map { (0, $_, -1) } @$rootset;
368         while (@q) {
369                 my ($level, $node, $i) = splice(@q, 0, 3);
370                 defined $node or next;
371                 $cb->($ctx, $level, $node, $i) or return;
372                 ++$level;
373                 $i = 0;
374                 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
375         }
376 }
377
378 sub pre_thread  {
379         my ($ctx, $level, $node, $idx) = @_;
380         $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
381         skel_dump($ctx, $level, $node);
382 }
383
384 sub thread_index_entry {
385         my ($ctx, $level, $smsg) = @_;
386         my ($beg, $end) = thread_adj_level($ctx, $level);
387         $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
388 }
389
390 sub stream_thread ($$) {
391         my ($rootset, $ctx) = @_;
392         my $inbox = $ctx->{-inbox};
393         my @q = map { (0, $_) } @$rootset;
394         my $level;
395         my $smsg;
396         while (@q) {
397                 $level = shift @q;
398                 my $node = shift @q or next;
399                 my $cl = $level + 1;
400                 unshift @q, map { ($cl, $_) } @{$node->{children}};
401                 $smsg = $inbox->smsg_mime($node->{smsg}) and last;
402         }
403         return missing_thread($ctx) unless $smsg;
404
405         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
406         $ctx->{-title_html} = ascii_html($smsg->subject);
407         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
408         $smsg = undef;
409         PublicInbox::WwwStream->response($ctx, 200, sub {
410                 return unless $ctx;
411                 while (@q) {
412                         $level = shift @q;
413                         my $node = shift @q or next;
414                         my $cl = $level + 1;
415                         unshift @q, map { ($cl, $_) } @{$node->{children}};
416                         if ($smsg = $inbox->smsg_mime($node->{smsg})) {
417                                 return thread_index_entry($ctx, $level, $smsg);
418                         } else {
419                                 return ghost_index_entry($ctx, $level, $node);
420                         }
421                 }
422                 my $ret = join('', thread_adj_level($ctx, 0));
423                 $ret .= ${$ctx->{dst}}; # skel
424                 $ctx = undef;
425                 $ret;
426         });
427 }
428
429 sub thread_html {
430         my ($ctx) = @_;
431         my $mid = $ctx->{mid};
432         my $srch = $ctx->{srch};
433         my ($nr, $msgs) = $srch->get_thread($mid);
434         return missing_thread($ctx) if $nr == 0;
435         my $skel = '<hr><pre>';
436         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
437         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
438         $skel .= "<b\nid=t>Thread overview:</b> ";
439         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
440         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
441         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
442         $skel .= "-- links below jump to the message on this page --\n";
443         $ctx->{-upfx} = '../../';
444         $ctx->{cur_level} = 0;
445         $ctx->{dst} = \$skel;
446         $ctx->{prev_attr} = '';
447         $ctx->{prev_level} = 0;
448         $ctx->{root_anchor} = anchor_for($mid);
449         $ctx->{mapping} = {};
450         $ctx->{s_nr} = "$nr+ messages in thread";
451
452         my $rootset = thread_results($ctx, $msgs);
453
454         # reduce hash lookups in pre_thread->skel_dump
455         my $inbox = $ctx->{-inbox};
456         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
457         walk_thread($rootset, $ctx, *pre_thread);
458
459         $skel .= '</pre>';
460         return stream_thread($rootset, $ctx) unless $ctx->{flat};
461
462         # flat display: lazy load the full message from smsg
463         my $smsg;
464         while (my $m = shift @$msgs) {
465                 $smsg = $inbox->smsg_mime($m) and last;
466         }
467         return missing_thread($ctx) unless $smsg;
468         $ctx->{-title_html} = ascii_html($smsg->subject);
469         $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
470         $smsg = undef;
471         PublicInbox::WwwStream->response($ctx, 200, sub {
472                 return unless $msgs;
473                 $smsg = undef;
474                 while (my $m = shift @$msgs) {
475                         $smsg = $inbox->smsg_mime($m) and last;
476                 }
477                 return index_entry($smsg, $ctx, scalar @$msgs) if $smsg;
478                 $msgs = undef;
479                 $skel;
480         });
481 }
482
483 sub multipart_text_as_html {
484         my ($mime, $upfx, $obfs_ibx) = @_;
485         my $rv = "";
486
487         # scan through all parts, looking for displayable text
488         msg_iter($mime, sub { $rv .= add_text_body($upfx, $obfs_ibx, $_[0]) });
489         $rv;
490 }
491
492 sub flush_quote {
493         my ($s, $l, $quot) = @_;
494
495         # show everything in the full version with anchor from
496         # short version (see above)
497         my $rv = $l->linkify_1(join('', @$quot));
498         @$quot = ();
499
500         # we use a <span> here to allow users to specify their own
501         # color for quoted text
502         $rv = $l->linkify_2(ascii_html($rv));
503         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
504 }
505
506 sub attach_link ($$$$;$) {
507         my ($upfx, $ct, $p, $fn, $err) = @_;
508         my ($part, $depth, @idx) = @$p;
509         my $nl = $idx[-1] > 1 ? "\n" : '';
510         my $idx = join('.', @idx);
511         my $size = bytes::length($part->body);
512
513         # hide attributes normally, unless we want to aid users in
514         # spotting MUA problems:
515         $ct =~ s/;.*// unless $err;
516         $ct = ascii_html($ct);
517         my $desc = $part->header('Content-Description');
518         $desc = $fn unless defined $desc;
519         $desc = '' unless defined $desc;
520         my $sfn;
521         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
522                 $sfn = $fn;
523         } elsif ($ct eq 'text/plain') {
524                 $sfn = 'a.txt';
525         } else {
526                 $sfn = 'a.bin';
527         }
528         my $ret = qq($nl<a\nhref="$upfx$idx-$sfn">);
529         if ($err) {
530                 $ret .=
531 "[-- Warning: decoded text below may be mangled --]\n";
532         }
533         $ret .= "[-- Attachment #$idx: ";
534         my $ts = "Type: $ct, Size: $size bytes";
535         $desc = ascii_html($desc);
536         $ret .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
537         $ret .= "</a>\n";
538 }
539
540 sub add_text_body {
541         my ($upfx, $obfs_ibx, $p) = @_;
542         # $p - from msg_iter: [ Email::MIME, depth, @idx ]
543         my ($part, $depth) = @$p; # attachment @idx is unused
544         my $ct = $part->content_type || 'text/plain';
545         my $fn = $part->filename;
546
547         if ($ct =~ m!\btext/x?html\b!i) {
548                 return attach_link($upfx, $ct, $p, $fn);
549         }
550
551         my $s = eval { $part->body_str };
552
553         # badly-encoded message? tell the world about it!
554         my $err = $@;
555         if ($err) {
556                 if ($ct =~ m!\btext/plain\b!i) {
557                         # Try to assume UTF-8 because Alpine seems to
558                         # do wacky things and set charset=X-UNKNOWN
559                         $part->charset_set('UTF-8');
560                         $s = eval { $part->body_str };
561
562                         # If forcing charset=UTF-8 failed,
563                         # attach_link will warn further down...
564                         $s = $part->body if $@;
565                 } else {
566                         return attach_link($upfx, $ct, $p, $fn);
567                 }
568         }
569
570         my @lines = split(/^/m, $s);
571         $s = '';
572         if (defined($fn) || $depth > 0 || $err) {
573                 $s .= attach_link($upfx, $ct, $p, $fn, $err);
574                 $s .= "\n";
575         }
576         my @quot;
577         my $l = PublicInbox::Linkify->new;
578         foreach my $cur (@lines) {
579                 if ($cur !~ /^>/) {
580                         # show the previously buffered quote inline
581                         flush_quote(\$s, $l, \@quot) if @quot;
582
583                         # regular line, OK
584                         $l->linkify_1($cur);
585                         $s .= $l->linkify_2(ascii_html($cur));
586                 } else {
587                         push @quot, $cur;
588                 }
589         }
590
591         if (@quot) { # ugh, top posted
592                 flush_quote(\$s, $l, \@quot);
593                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
594                 $s;
595         } else {
596                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
597                 if ($s =~ /\n\z/s) { # common, last line ends with a newline
598                         $s;
599                 } else { # some editors don't do newlines...
600                         $s .= "\n";
601                 }
602         }
603 }
604
605 sub _msg_html_prepare {
606         my ($hdr, $ctx, $more, $nr) = @_;
607         my $srch = $ctx->{srch} if $ctx;
608         my $atom = '';
609         my $obfs_ibx = $ctx->{-obfs_ibx};
610         my $rv = '';
611         my $mids = mids($hdr);
612         my $multiple = scalar(@$mids) > 1; # zero, one, infinity
613         if ($nr == 0) {
614                 if ($more) {
615                         $rv .=
616 "<pre>WARNING: multiple messages refer to this Message-ID\n</pre>";
617                 }
618                 $rv .= "<pre\nid=b>"; # anchor for body start
619         } else {
620                 $rv .= '<pre>';
621         }
622         if ($srch) {
623                 $ctx->{-upfx} = '../';
624         }
625         my @title;
626         my $v;
627         if (defined($v = $hdr->header('From'))) {
628                 $v = PublicInbox::Hval->new($v);
629                 my @n = PublicInbox::Address::names($v->raw);
630                 $title[1] = ascii_html(join(', ', @n));
631                 $v = $v->as_html;
632                 if ($obfs_ibx) {
633                         obfuscate_addrs($obfs_ibx, $v);
634                         obfuscate_addrs($obfs_ibx, $title[1]);
635                 }
636                 $rv .= "From: $v\n" if $v ne '';
637         }
638         foreach my $h (qw(To Cc)) {
639                 defined($v = $hdr->header($h)) or next;
640                 fold_addresses($v);
641                 $v = ascii_html($v);
642                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
643                 $rv .= "$h: $v\n" if $v ne '';
644         }
645         if (defined($v = $hdr->header('Subject')) && ($v ne '')) {
646                 $v = ascii_html($v);
647                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
648                 if ($srch) {
649                         $rv .= qq(Subject: <a\nhref="#r"\nid=t>$v</a>\n);
650                 } else {
651                         $rv .= "Subject: $v\n";
652                 }
653                 $title[0] = $v;
654         } else { # dummy anchor for thread skeleton at bottom of page
655                 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $srch;
656                 $title[0] = '(no subject)';
657         }
658         if (defined($v = $hdr->header('Date'))) {
659                 $v = ascii_html($v);
660                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
661                 $rv .= "Date: $v\n";
662         }
663         $ctx->{-title_html} = join(' - ', @title);
664         foreach (@$mids) {
665                 my $mid = PublicInbox::Hval->new_msgid($_) ;
666                 my $mhtml = $mid->as_html;
667                 if ($multiple) {
668                         my $href = $mid->{href};
669                         $rv .= "Message-ID: ";
670                         $rv .= "<a\nhref=\"../$href/\">";
671                         $rv .= "&lt;$mhtml&gt;</a> ";
672                         $rv .= "(<a\nhref=\"../$href/raw\">raw</a>)\n";
673                 } else {
674                         $rv .= "Message-ID: &lt;$mhtml&gt; ";
675                         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
676                 }
677         }
678         $rv .= _parent_headers($hdr, $srch);
679         $rv .= "\n";
680 }
681
682 sub thread_skel {
683         my ($dst, $ctx, $hdr, $tpfx) = @_;
684         my $srch = $ctx->{srch};
685         my $mid = mids($hdr)->[0];
686         my ($nr, $msgs) = $srch->get_thread($mid);
687         my $expand = qq(expand[<a\nhref="${tpfx}T/#u">flat</a>) .
688                         qq(|<a\nhref="${tpfx}t/#u">nested</a>]  ) .
689                         qq(<a\nhref="${tpfx}t.mbox.gz">mbox.gz</a>  ) .
690                         qq(<a\nhref="${tpfx}t.atom">Atom feed</a>);
691
692         my $parent = in_reply_to($hdr);
693         $$dst .= "\n<b>Thread overview: </b>";
694         if ($nr <= 1) {
695                 if (defined $parent) {
696                         $$dst .= "$expand\n ";
697                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
698                 } else {
699                         $$dst .= "[no followups] $expand\n";
700                 }
701                 $ctx->{next_msg} = undef;
702                 $ctx->{parent_msg} = $parent;
703                 return;
704         }
705
706         $$dst .= "$nr+ messages / $expand";
707         $$dst .= qq!  <a\nhref="#b">top</a>\n!;
708
709         my $subj = $hdr->header('Subject');
710         defined $subj or $subj = '';
711         $ctx->{prev_subj} = [ split(/ /, $srch->subject_normalized($subj)) ];
712         $ctx->{cur} = $mid;
713         $ctx->{prev_attr} = '';
714         $ctx->{prev_level} = 0;
715         $ctx->{dst} = $dst;
716
717         # reduce hash lookups in skel_dump
718         my $ibx = $ctx->{-inbox};
719         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
720         walk_thread(thread_results($ctx, $msgs), $ctx, *skel_dump);
721
722         $ctx->{parent_msg} = $parent;
723 }
724
725 sub _parent_headers {
726         my ($hdr, $srch) = @_;
727         my $rv = '';
728
729         my $refs = references($hdr);
730         my $irt = pop @$refs;
731         if (defined $irt) {
732                 my $v = PublicInbox::Hval->new_msgid($irt);
733                 my $html = $v->as_html;
734                 my $href = $v->{href};
735                 $rv .= "In-Reply-To: &lt;";
736                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
737         }
738
739         # do not display References: if search is present,
740         # we show the thread skeleton at the bottom, instead.
741         return $rv if $srch;
742
743         if (@$refs) {
744                 @$refs = map { linkify_ref_nosrch($_) } @$refs;
745                 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
746         }
747         $rv;
748 }
749
750 sub html_footer {
751         my ($hdr, $standalone, $ctx, $rhref) = @_;
752
753         my $srch = $ctx->{srch} if $ctx;
754         my $upfx = '../';
755         my $tpfx = '';
756         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
757         my $irt = '';
758         if ($idx && $srch) {
759                 $idx .= "\n";
760                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
761                 my ($next, $prev);
762                 my $parent = '       ';
763                 $next = $prev = '    ';
764
765                 if (my $n = $ctx->{next_msg}) {
766                         $n = PublicInbox::Hval->new_msgid($n)->{href};
767                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
768                 }
769                 my $u;
770                 my $par = $ctx->{parent_msg};
771                 if ($par) {
772                         $u = PublicInbox::Hval->new_msgid($par)->{href};
773                         $u = "$upfx$u/";
774                 }
775                 if (my $p = $ctx->{prev_msg}) {
776                         $prev = PublicInbox::Hval->new_msgid($p)->{href};
777                         if ($p && $par && $p eq $par) {
778                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
779                                         'rel=prev>prev parent</a>';
780                                 $parent = '';
781                         } else {
782                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
783                                         'rel=prev>prev</a>';
784                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
785                         }
786                 } elsif ($u) { # unlikely
787                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
788                 }
789                 $irt = "$next $prev$parent ";
790         } else {
791                 $irt = '';
792         }
793         $rhref ||= '#R';
794         $irt .= qq(<a\nhref="$rhref">reply</a>);
795         $irt .= $idx;
796 }
797
798 sub linkify_ref_nosrch {
799         my $v = PublicInbox::Hval->new_msgid($_[0]);
800         my $html = $v->as_html;
801         my $href = $v->{href};
802         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
803 }
804
805 sub anchor_for {
806         my ($msgid) = @_;
807         'm' . id_compress($msgid, 1);
808 }
809
810 sub ghost_parent {
811         my ($upfx, $mid) = @_;
812
813         $mid = PublicInbox::Hval->new_msgid($mid);
814         my $href = $mid->{href};
815         my $html = $mid->as_html;
816         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
817 }
818
819 sub indent_for {
820         my ($level) = @_;
821         $level ? INDENT x ($level - 1) : '';
822 }
823
824 sub find_mid_root {
825         my ($ctx, $level, $node, $idx) = @_;
826         ++$ctx->{root_idx} if $level == 0;
827         if ($node->{id} eq $ctx->{mid}) {
828                 $ctx->{found_mid_at} = $ctx->{root_idx};
829                 return 0;
830         }
831         1;
832 }
833
834 sub strict_loose_note ($) {
835         my ($nr) = @_;
836         my $msg =
837 "  -- strict thread matches above, loose matches on Subject: below --\n";
838
839         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
840                 $msg .=
841 "  -- use mbox.gz link to download all $nr messages --\n";
842         }
843         $msg;
844 }
845
846 sub thread_results {
847         my ($ctx, $msgs) = @_;
848         require PublicInbox::SearchThread;
849         my $ibx = $ctx->{-inbox};
850         my $rootset = PublicInbox::SearchThread::thread($msgs, *sort_ds, $ibx);
851
852         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
853         # and preserved in the future.  This bug is hidden by `sid' matches
854         # in get_thread, so we never noticed it until now.  And even when
855         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
856         # bump since reindexing is expensive and users may not do it
857
858         # loose threading could've returned too many results,
859         # put the root the message we care about at the top:
860         my $mid = $ctx->{mid};
861         if (defined($mid) && scalar(@$rootset) > 1) {
862                 $ctx->{root_idx} = -1;
863                 my $nr = scalar @$msgs;
864                 walk_thread($rootset, $ctx, *find_mid_root);
865                 my $idx = $ctx->{found_mid_at};
866                 if (defined($idx) && $idx != 0) {
867                         my $tip = splice(@$rootset, $idx, 1);
868                         @$rootset = reverse @$rootset;
869                         unshift @$rootset, $tip;
870                         $ctx->{sl_note} = strict_loose_note($nr);
871                 }
872         }
873         $rootset
874 }
875
876 sub missing_thread {
877         my ($ctx) = @_;
878         require PublicInbox::ExtMsg;
879         PublicInbox::ExtMsg::ext_msg($ctx);
880 }
881
882 sub _msg_date {
883         my ($hdr) = @_;
884         fmt_ts(msg_datestamp($hdr));
885 }
886
887 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
888
889 sub dedupe_subject {
890         my ($prev_subj, $subj, $val) = @_;
891
892         my $omit = ''; # '"' denotes identical text omitted
893         my (@prev_pop, @curr_pop);
894         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
895                 push(@prev_pop, pop(@$prev_subj));
896                 push(@curr_pop, pop(@$subj));
897                 $omit ||= $val;
898         }
899         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
900         if (scalar(@curr_pop) == 1) {
901                 $omit = '';
902                 push @$prev_subj, @prev_pop;
903                 push @$subj, @curr_pop;
904         }
905         $omit;
906 }
907
908 sub skel_dump {
909         my ($ctx, $level, $node) = @_;
910         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
911
912         my $dst = $ctx->{dst};
913         my $cur = $ctx->{cur};
914         my $mid = $smsg->{mid};
915
916         if ($level == 0 && $ctx->{skel_dump_roots}++) {
917                 $$dst .= delete $ctx->{sl_note} || '';
918         }
919
920         my $f = ascii_html($smsg->from_name);
921         my $obfs_ibx = $ctx->{-obfs_ibx};
922         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
923
924         my $d = fmt_ts($smsg->{ds}) . ' ' . indent_for($level) . th_pfx($level);
925         my $attr = $f;
926         $ctx->{first_level} ||= $level;
927
928         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
929                 $ctx->{prev_attr} = $attr;
930         }
931         $ctx->{prev_level} = $level;
932
933         if ($cur) {
934                 if ($cur eq $mid) {
935                         delete $ctx->{cur};
936                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
937                                  "$attr [this message]</a></b>\n";
938                         return 1;
939                 } else {
940                         $ctx->{prev_msg} = $mid;
941                 }
942         } else {
943                 $ctx->{next_msg} ||= $mid;
944         }
945
946         # Subject is never undef, this mail was loaded from
947         # our Xapian which would've resulted in '' if it were
948         # really missing (and Filter rejects empty subjects)
949         my @subj = split(/ /, $ctx->{srch}->subject_normalized($smsg->subject));
950
951         # remove common suffixes from the subject if it matches the previous,
952         # so we do not show redundant text at the end.
953         my $prev_subj = $ctx->{prev_subj} || [];
954         $ctx->{prev_subj} = [ @subj ];
955         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
956         my $end;
957         if (@subj) {
958                 my $subj = join(' ', @subj);
959                 $subj = ascii_html($subj);
960                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
961                 $end = "$subj</a> $omit$f\n"
962         } else {
963                 $end = "$f</a>\n";
964         }
965         my $m;
966         my $id = '';
967         my $mapping = $ctx->{mapping};
968         if ($mapping) {
969                 my $map = $mapping->{$mid};
970                 $id = id_compress($mid, 1);
971                 $m = '#m'.$id;
972                 $map->[0] = "$d<a\nhref=\"$m\">$end";
973                 $id = "\nid=r".$id;
974         } else {
975                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
976         }
977         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
978         1;
979 }
980
981 sub _skel_ghost {
982         my ($ctx, $level, $node) = @_;
983
984         my $mid = $node->{id};
985         my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
986                             : '     [not found] ';
987         $d .= indent_for($level) . th_pfx($level);
988         my $upfx = $ctx->{-upfx};
989         my $m = PublicInbox::Hval->new_msgid($mid);
990         my $href = $upfx . $m->{href} . '/';
991         my $html = $m->as_html;
992
993         my $mapping = $ctx->{mapping};
994         my $map = $mapping->{$mid} if $mapping;
995         if ($map) {
996                 my $id = id_compress($mid, 1);
997                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
998                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
999         } else {
1000                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
1001         }
1002         my $dst = $ctx->{dst};
1003         $$dst .= $d;
1004         1;
1005 }
1006
1007 sub sort_ds {
1008         [ sort {
1009                 (eval { $a->topmost->{smsg}->ds } || 0) <=>
1010                 (eval { $b->topmost->{smsg}->ds } || 0)
1011         } @{$_[0]} ];
1012 }
1013
1014 # accumulate recent topics if search is supported
1015 # returns 200 if done, 404 if not
1016 sub acc_topic {
1017         my ($ctx, $level, $node) = @_;
1018         my $srch = $ctx->{srch};
1019         my $mid = $node->{id};
1020         my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1021         my ($subj, $ds);
1022         my $topic;
1023         if ($x) {
1024                 $subj = $x->subject;
1025                 $subj = $srch->subject_normalized($subj);
1026                 $ds = $x->ds;
1027                 if ($level == 0) {
1028                         $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1029                         $ctx->{-cur_topic} = $topic;
1030                         push @{$ctx->{order}}, $topic;
1031                         return 1;
1032                 }
1033
1034                 $topic = $ctx->{-cur_topic}; # should never be undef
1035                 $topic->[0] = $ds if $ds > $topic->[0];
1036                 $topic->[1]++;
1037                 my $seen = $topic->[2];
1038                 if (scalar(@$topic) == 3) { # parent was a ghost
1039                         push @$topic, $subj;
1040                 } elsif (!$seen->{$subj}) {
1041                         push @$topic, $level, $subj;
1042                 }
1043                 $seen->{$subj} = $mid; # latest for subject
1044         } else { # ghost message
1045                 return 1 if $level != 0; # ignore child ghosts
1046                 $topic = [ -666, 0, {} ];
1047                 $ctx->{-cur_topic} = $topic;
1048                 push @{$ctx->{order}}, $topic;
1049         }
1050         1;
1051 }
1052
1053 sub dump_topics {
1054         my ($ctx) = @_;
1055         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1056         if (!@$order) {
1057                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1058                 return 404;
1059         }
1060
1061         my @out;
1062         my $ibx = $ctx->{-inbox};
1063         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1064         my $srch = $ctx->{srch};
1065
1066         # sort by recency, this allows new posts to "bump" old topics...
1067         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1068                 my ($ds, $n, $seen, $top, @ex) = @$topic;
1069                 @$topic = ();
1070                 next unless defined $top;  # ghost topic
1071                 my $mid = delete $seen->{$top};
1072                 my $href = mid_escape($mid);
1073                 my $prev_subj = [ split(/ /, $top) ];
1074                 $top = PublicInbox::Hval->new($top)->as_html;
1075                 $ds = fmt_ts($ds);
1076
1077                 # $n isn't the total number of posts on the topic,
1078                 # just the number of posts in the current results window
1079                 my $anchor;
1080                 if ($n == 1) {
1081                         $n = '';
1082                         $anchor = '#u'; # top of only message
1083                 } else {
1084                         $n = " ($n+ messages)";
1085                         $anchor = '#t'; # thread skeleton
1086                 }
1087
1088                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1089                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1090                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
1091                         " $ds UTC $n - $mbox / $atom\n";
1092                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1093                         my $level = $ex[$i];
1094                         my $subj = $ex[$i + 1];
1095                         $mid = delete $seen->{$subj};
1096                         my @subj = split(/ /, $srch->subject_normalized($subj));
1097                         my @next_prev = @subj; # full copy
1098                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1099                         $prev_subj = \@next_prev;
1100                         $subj = ascii_html(join(' ', @subj));
1101                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1102                         $href = mid_escape($mid);
1103                         $s .= indent_for($level) . TCHILD;
1104                         $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1105                 }
1106                 push @out, $s;
1107         }
1108         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1109         200;
1110 }
1111
1112 sub ts2str ($) {
1113         my ($ts) = @_;
1114         POSIX::strftime('%Y%m%d%H%M%S', gmtime($ts));
1115 }
1116
1117 sub str2ts ($) {
1118         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1119         timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1120 }
1121
1122 sub pagination_footer ($$) {
1123         my ($ctx, $latest) = @_;
1124         delete $ctx->{qp} or return;
1125         my $next = $ctx->{next_page} || '';
1126         my $prev = $ctx->{prev_page} || '';
1127         if ($prev) {
1128                 $next = $next ? "$next " : '     ';
1129                 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1130         }
1131         "<hr><pre>page: $next$prev</pre>";
1132 }
1133
1134 sub index_nav { # callback for WwwStream
1135         my (undef, $ctx) = @_;
1136         pagination_footer($ctx, '.')
1137 }
1138
1139 sub paginate_recent ($$) {
1140         my ($ctx, $lim) = @_;
1141         my $t = $ctx->{qp}->{t} || '';
1142         my $opts = { limit => $lim };
1143         my ($after, $before);
1144
1145         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1146         # if only $after exists "YYYYMMDD.." because "." could be skipped
1147         # if interpreted as an end-of-sentence
1148         $t =~ s/\A(\d{8,14})-// and $after = str2ts($1);
1149         $t =~ /\A(\d{8,14})\z/ and $before = str2ts($1);
1150
1151         my $ibx = $ctx->{-inbox};
1152         my $msgs = $ibx->recent($opts, $after, $before);
1153         my $nr = scalar @$msgs;
1154         if ($nr < $lim && defined($after)) {
1155                 $after = $before = undef;
1156                 $msgs = $ibx->recent($opts);
1157                 $nr = scalar @$msgs;
1158         }
1159         my $more = $nr == $lim;
1160         my ($newest, $oldest);
1161         if ($nr) {
1162                 $newest = $msgs->[0]->{ts};
1163                 $oldest = $msgs->[-1]->{ts};
1164                 # if we only had $after, our SQL query in ->recent ordered
1165                 if ($newest < $oldest) {
1166                         ($oldest, $newest) = ($newest, $oldest);
1167                         $more = 0 if defined($after) && $after < $oldest;
1168                 }
1169         }
1170         if (defined($oldest) && $more) {
1171                 my $s = ts2str($oldest);
1172                 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1173         }
1174         if (defined($newest) && (defined($before) || defined($after))) {
1175                 my $s = ts2str($newest);
1176                 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1177         }
1178         $msgs;
1179 }
1180
1181 sub index_topics {
1182         my ($ctx) = @_;
1183         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1184         if (@$msgs) {
1185                 walk_thread(thread_results($ctx, $msgs), $ctx, *acc_topic);
1186         }
1187         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1188 }
1189
1190 sub thread_adj_level {
1191         my ($ctx, $level) = @_;
1192
1193         my $max = $ctx->{cur_level};
1194         if ($level <= 0) {
1195                 return ('', '') if $max == 0; # flat output
1196
1197                 # reset existing lists
1198                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1199                 $ctx->{cur_level} = 0;
1200                 ("$beg</ul>", '');
1201         } elsif ($level == $max) { # continue existing list
1202                 qw(<li> </li>);
1203         } elsif ($level < $max) {
1204                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1205                 $ctx->{cur_level} = $level;
1206                 ("$beg<li>", '</li>');
1207         } else { # ($level > $max) # start a new level
1208                 $ctx->{cur_level} = $level;
1209                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1210                 ($beg, '</li>');
1211         }
1212 }
1213
1214 sub ghost_index_entry {
1215         my ($ctx, $level, $node) = @_;
1216         my ($beg, $end) = thread_adj_level($ctx,  $level);
1217         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1218                 . '</pre>' . $end;
1219 }
1220
1221 1;