]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: stop storing all MIME objects on large threads
[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 = delete $smsg->{mime}; # critical to memory use
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         my ($s, $err) = msg_part_text($part, $ct);
547
548         return attach_link($upfx, $ct, $p, $fn) unless defined $s;
549
550         my @lines = split(/^/m, $s);
551         $s = '';
552         if (defined($fn) || $depth > 0 || $err) {
553                 # badly-encoded message with $err? tell the world about it!
554                 $s .= attach_link($upfx, $ct, $p, $fn, $err);
555                 $s .= "\n";
556         }
557         my @quot;
558         my $l = PublicInbox::Linkify->new;
559         foreach my $cur (@lines) {
560                 if ($cur !~ /^>/) {
561                         # show the previously buffered quote inline
562                         flush_quote(\$s, $l, \@quot) if @quot;
563
564                         # regular line, OK
565                         $l->linkify_1($cur);
566                         $s .= $l->linkify_2(ascii_html($cur));
567                 } else {
568                         push @quot, $cur;
569                 }
570         }
571
572         if (@quot) { # ugh, top posted
573                 flush_quote(\$s, $l, \@quot);
574                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
575                 $s;
576         } else {
577                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
578                 if ($s =~ /\n\z/s) { # common, last line ends with a newline
579                         $s;
580                 } else { # some editors don't do newlines...
581                         $s .= "\n";
582                 }
583         }
584 }
585
586 sub _msg_html_prepare {
587         my ($hdr, $ctx, $more, $nr) = @_;
588         my $srch = $ctx->{srch} if $ctx;
589         my $atom = '';
590         my $obfs_ibx = $ctx->{-obfs_ibx};
591         my $rv = '';
592         my $mids = mids($hdr);
593         my $multiple = scalar(@$mids) > 1; # zero, one, infinity
594         if ($nr == 0) {
595                 if ($more) {
596                         $rv .=
597 "<pre>WARNING: multiple messages refer to this Message-ID\n</pre>";
598                 }
599                 $rv .= "<pre\nid=b>"; # anchor for body start
600         } else {
601                 $rv .= '<pre>';
602         }
603         if ($srch) {
604                 $ctx->{-upfx} = '../';
605         }
606         my @title;
607         my $v;
608         if (defined($v = $hdr->header('From'))) {
609                 $v = PublicInbox::Hval->new($v);
610                 my @n = PublicInbox::Address::names($v->raw);
611                 $title[1] = ascii_html(join(', ', @n));
612                 $v = $v->as_html;
613                 if ($obfs_ibx) {
614                         obfuscate_addrs($obfs_ibx, $v);
615                         obfuscate_addrs($obfs_ibx, $title[1]);
616                 }
617                 $rv .= "From: $v\n" if $v ne '';
618         }
619         foreach my $h (qw(To Cc)) {
620                 defined($v = $hdr->header($h)) or next;
621                 fold_addresses($v);
622                 $v = ascii_html($v);
623                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
624                 $rv .= "$h: $v\n" if $v ne '';
625         }
626         if (defined($v = $hdr->header('Subject')) && ($v ne '')) {
627                 $v = ascii_html($v);
628                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
629                 if ($srch) {
630                         $rv .= qq(Subject: <a\nhref="#r"\nid=t>$v</a>\n);
631                 } else {
632                         $rv .= "Subject: $v\n";
633                 }
634                 $title[0] = $v;
635         } else { # dummy anchor for thread skeleton at bottom of page
636                 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $srch;
637                 $title[0] = '(no subject)';
638         }
639         if (defined($v = $hdr->header('Date'))) {
640                 $v = ascii_html($v);
641                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
642                 $rv .= "Date: $v\n";
643         }
644         $ctx->{-title_html} = join(' - ', @title);
645         foreach (@$mids) {
646                 my $mid = PublicInbox::Hval->new_msgid($_) ;
647                 my $mhtml = $mid->as_html;
648                 if ($multiple) {
649                         my $href = $mid->{href};
650                         $rv .= "Message-ID: ";
651                         $rv .= "<a\nhref=\"../$href/\">";
652                         $rv .= "&lt;$mhtml&gt;</a> ";
653                         $rv .= "(<a\nhref=\"../$href/raw\">raw</a>)\n";
654                 } else {
655                         $rv .= "Message-ID: &lt;$mhtml&gt; ";
656                         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
657                 }
658         }
659         $rv .= _parent_headers($hdr, $srch);
660         $rv .= "\n";
661 }
662
663 sub thread_skel {
664         my ($dst, $ctx, $hdr, $tpfx) = @_;
665         my $srch = $ctx->{srch};
666         my $mid = mids($hdr)->[0];
667         my ($nr, $msgs) = $srch->get_thread($mid);
668         my $expand = qq(expand[<a\nhref="${tpfx}T/#u">flat</a>) .
669                         qq(|<a\nhref="${tpfx}t/#u">nested</a>]  ) .
670                         qq(<a\nhref="${tpfx}t.mbox.gz">mbox.gz</a>  ) .
671                         qq(<a\nhref="${tpfx}t.atom">Atom feed</a>);
672
673         my $parent = in_reply_to($hdr);
674         $$dst .= "\n<b>Thread overview: </b>";
675         if ($nr <= 1) {
676                 if (defined $parent) {
677                         $$dst .= "$expand\n ";
678                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
679                 } else {
680                         $$dst .= "[no followups] $expand\n";
681                 }
682                 $ctx->{next_msg} = undef;
683                 $ctx->{parent_msg} = $parent;
684                 return;
685         }
686
687         $$dst .= "$nr+ messages / $expand";
688         $$dst .= qq!  <a\nhref="#b">top</a>\n!;
689
690         my $subj = $hdr->header('Subject');
691         defined $subj or $subj = '';
692         $ctx->{prev_subj} = [ split(/ /, $srch->subject_normalized($subj)) ];
693         $ctx->{cur} = $mid;
694         $ctx->{prev_attr} = '';
695         $ctx->{prev_level} = 0;
696         $ctx->{dst} = $dst;
697
698         # reduce hash lookups in skel_dump
699         my $ibx = $ctx->{-inbox};
700         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
701         walk_thread(thread_results($ctx, $msgs), $ctx, *skel_dump);
702
703         $ctx->{parent_msg} = $parent;
704 }
705
706 sub _parent_headers {
707         my ($hdr, $srch) = @_;
708         my $rv = '';
709
710         my $refs = references($hdr);
711         my $irt = pop @$refs;
712         if (defined $irt) {
713                 my $v = PublicInbox::Hval->new_msgid($irt);
714                 my $html = $v->as_html;
715                 my $href = $v->{href};
716                 $rv .= "In-Reply-To: &lt;";
717                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
718         }
719
720         # do not display References: if search is present,
721         # we show the thread skeleton at the bottom, instead.
722         return $rv if $srch;
723
724         if (@$refs) {
725                 @$refs = map { linkify_ref_nosrch($_) } @$refs;
726                 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
727         }
728         $rv;
729 }
730
731 sub html_footer {
732         my ($hdr, $standalone, $ctx, $rhref) = @_;
733
734         my $srch = $ctx->{srch} if $ctx;
735         my $upfx = '../';
736         my $tpfx = '';
737         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
738         my $irt = '';
739         if ($idx && $srch) {
740                 $idx .= "\n";
741                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
742                 my ($next, $prev);
743                 my $parent = '       ';
744                 $next = $prev = '    ';
745
746                 if (my $n = $ctx->{next_msg}) {
747                         $n = PublicInbox::Hval->new_msgid($n)->{href};
748                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
749                 }
750                 my $u;
751                 my $par = $ctx->{parent_msg};
752                 if ($par) {
753                         $u = PublicInbox::Hval->new_msgid($par)->{href};
754                         $u = "$upfx$u/";
755                 }
756                 if (my $p = $ctx->{prev_msg}) {
757                         $prev = PublicInbox::Hval->new_msgid($p)->{href};
758                         if ($p && $par && $p eq $par) {
759                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
760                                         'rel=prev>prev parent</a>';
761                                 $parent = '';
762                         } else {
763                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
764                                         'rel=prev>prev</a>';
765                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
766                         }
767                 } elsif ($u) { # unlikely
768                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
769                 }
770                 $irt = "$next $prev$parent ";
771         } else {
772                 $irt = '';
773         }
774         $rhref ||= '#R';
775         $irt .= qq(<a\nhref="$rhref">reply</a>);
776         $irt .= $idx;
777 }
778
779 sub linkify_ref_nosrch {
780         my $v = PublicInbox::Hval->new_msgid($_[0]);
781         my $html = $v->as_html;
782         my $href = $v->{href};
783         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
784 }
785
786 sub anchor_for {
787         my ($msgid) = @_;
788         'm' . id_compress($msgid, 1);
789 }
790
791 sub ghost_parent {
792         my ($upfx, $mid) = @_;
793
794         $mid = PublicInbox::Hval->new_msgid($mid);
795         my $href = $mid->{href};
796         my $html = $mid->as_html;
797         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
798 }
799
800 sub indent_for {
801         my ($level) = @_;
802         $level ? INDENT x ($level - 1) : '';
803 }
804
805 sub find_mid_root {
806         my ($ctx, $level, $node, $idx) = @_;
807         ++$ctx->{root_idx} if $level == 0;
808         if ($node->{id} eq $ctx->{mid}) {
809                 $ctx->{found_mid_at} = $ctx->{root_idx};
810                 return 0;
811         }
812         1;
813 }
814
815 sub strict_loose_note ($) {
816         my ($nr) = @_;
817         my $msg =
818 "  -- strict thread matches above, loose matches on Subject: below --\n";
819
820         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
821                 $msg .=
822 "  -- use mbox.gz link to download all $nr messages --\n";
823         }
824         $msg;
825 }
826
827 sub thread_results {
828         my ($ctx, $msgs) = @_;
829         require PublicInbox::SearchThread;
830         my $ibx = $ctx->{-inbox};
831         my $rootset = PublicInbox::SearchThread::thread($msgs, *sort_ds, $ibx);
832
833         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
834         # and preserved in the future.  This bug is hidden by `sid' matches
835         # in get_thread, so we never noticed it until now.  And even when
836         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
837         # bump since reindexing is expensive and users may not do it
838
839         # loose threading could've returned too many results,
840         # put the root the message we care about at the top:
841         my $mid = $ctx->{mid};
842         if (defined($mid) && scalar(@$rootset) > 1) {
843                 $ctx->{root_idx} = -1;
844                 my $nr = scalar @$msgs;
845                 walk_thread($rootset, $ctx, *find_mid_root);
846                 my $idx = $ctx->{found_mid_at};
847                 if (defined($idx) && $idx != 0) {
848                         my $tip = splice(@$rootset, $idx, 1);
849                         @$rootset = reverse @$rootset;
850                         unshift @$rootset, $tip;
851                         $ctx->{sl_note} = strict_loose_note($nr);
852                 }
853         }
854         $rootset
855 }
856
857 sub missing_thread {
858         my ($ctx) = @_;
859         require PublicInbox::ExtMsg;
860         PublicInbox::ExtMsg::ext_msg($ctx);
861 }
862
863 sub _msg_date {
864         my ($hdr) = @_;
865         fmt_ts(msg_datestamp($hdr));
866 }
867
868 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
869
870 sub dedupe_subject {
871         my ($prev_subj, $subj, $val) = @_;
872
873         my $omit = ''; # '"' denotes identical text omitted
874         my (@prev_pop, @curr_pop);
875         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
876                 push(@prev_pop, pop(@$prev_subj));
877                 push(@curr_pop, pop(@$subj));
878                 $omit ||= $val;
879         }
880         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
881         if (scalar(@curr_pop) == 1) {
882                 $omit = '';
883                 push @$prev_subj, @prev_pop;
884                 push @$subj, @curr_pop;
885         }
886         $omit;
887 }
888
889 sub skel_dump {
890         my ($ctx, $level, $node) = @_;
891         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
892
893         my $dst = $ctx->{dst};
894         my $cur = $ctx->{cur};
895         my $mid = $smsg->{mid};
896
897         if ($level == 0 && $ctx->{skel_dump_roots}++) {
898                 $$dst .= delete $ctx->{sl_note} || '';
899         }
900
901         my $f = ascii_html($smsg->from_name);
902         my $obfs_ibx = $ctx->{-obfs_ibx};
903         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
904
905         my $d = fmt_ts($smsg->{ds}) . ' ' . indent_for($level) . th_pfx($level);
906         my $attr = $f;
907         $ctx->{first_level} ||= $level;
908
909         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
910                 $ctx->{prev_attr} = $attr;
911         }
912         $ctx->{prev_level} = $level;
913
914         if ($cur) {
915                 if ($cur eq $mid) {
916                         delete $ctx->{cur};
917                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
918                                  "$attr [this message]</a></b>\n";
919                         return 1;
920                 } else {
921                         $ctx->{prev_msg} = $mid;
922                 }
923         } else {
924                 $ctx->{next_msg} ||= $mid;
925         }
926
927         # Subject is never undef, this mail was loaded from
928         # our Xapian which would've resulted in '' if it were
929         # really missing (and Filter rejects empty subjects)
930         my @subj = split(/ /, $ctx->{srch}->subject_normalized($smsg->subject));
931
932         # remove common suffixes from the subject if it matches the previous,
933         # so we do not show redundant text at the end.
934         my $prev_subj = $ctx->{prev_subj} || [];
935         $ctx->{prev_subj} = [ @subj ];
936         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
937         my $end;
938         if (@subj) {
939                 my $subj = join(' ', @subj);
940                 $subj = ascii_html($subj);
941                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
942                 $end = "$subj</a> $omit$f\n"
943         } else {
944                 $end = "$f</a>\n";
945         }
946         my $m;
947         my $id = '';
948         my $mapping = $ctx->{mapping};
949         if ($mapping) {
950                 my $map = $mapping->{$mid};
951                 $id = id_compress($mid, 1);
952                 $m = '#m'.$id;
953                 $map->[0] = "$d<a\nhref=\"$m\">$end";
954                 $id = "\nid=r".$id;
955         } else {
956                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
957         }
958         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
959         1;
960 }
961
962 sub _skel_ghost {
963         my ($ctx, $level, $node) = @_;
964
965         my $mid = $node->{id};
966         my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
967                             : '     [not found] ';
968         $d .= indent_for($level) . th_pfx($level);
969         my $upfx = $ctx->{-upfx};
970         my $m = PublicInbox::Hval->new_msgid($mid);
971         my $href = $upfx . $m->{href} . '/';
972         my $html = $m->as_html;
973
974         my $mapping = $ctx->{mapping};
975         my $map = $mapping->{$mid} if $mapping;
976         if ($map) {
977                 my $id = id_compress($mid, 1);
978                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
979                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
980         } else {
981                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
982         }
983         my $dst = $ctx->{dst};
984         $$dst .= $d;
985         1;
986 }
987
988 sub sort_ds {
989         [ sort {
990                 (eval { $a->topmost->{smsg}->ds } || 0) <=>
991                 (eval { $b->topmost->{smsg}->ds } || 0)
992         } @{$_[0]} ];
993 }
994
995 # accumulate recent topics if search is supported
996 # returns 200 if done, 404 if not
997 sub acc_topic {
998         my ($ctx, $level, $node) = @_;
999         my $srch = $ctx->{srch};
1000         my $mid = $node->{id};
1001         my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1002         my ($subj, $ds);
1003         my $topic;
1004         if ($x) {
1005                 $subj = $x->subject;
1006                 $subj = $srch->subject_normalized($subj);
1007                 $ds = $x->ds;
1008                 if ($level == 0) {
1009                         $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1010                         $ctx->{-cur_topic} = $topic;
1011                         push @{$ctx->{order}}, $topic;
1012                         return 1;
1013                 }
1014
1015                 $topic = $ctx->{-cur_topic}; # should never be undef
1016                 $topic->[0] = $ds if $ds > $topic->[0];
1017                 $topic->[1]++;
1018                 my $seen = $topic->[2];
1019                 if (scalar(@$topic) == 3) { # parent was a ghost
1020                         push @$topic, $subj;
1021                 } elsif (!$seen->{$subj}) {
1022                         push @$topic, $level, $subj;
1023                 }
1024                 $seen->{$subj} = $mid; # latest for subject
1025         } else { # ghost message
1026                 return 1 if $level != 0; # ignore child ghosts
1027                 $topic = [ -666, 0, {} ];
1028                 $ctx->{-cur_topic} = $topic;
1029                 push @{$ctx->{order}}, $topic;
1030         }
1031         1;
1032 }
1033
1034 sub dump_topics {
1035         my ($ctx) = @_;
1036         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1037         if (!@$order) {
1038                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1039                 return 404;
1040         }
1041
1042         my @out;
1043         my $ibx = $ctx->{-inbox};
1044         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1045         my $srch = $ctx->{srch};
1046
1047         # sort by recency, this allows new posts to "bump" old topics...
1048         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1049                 my ($ds, $n, $seen, $top, @ex) = @$topic;
1050                 @$topic = ();
1051                 next unless defined $top;  # ghost topic
1052                 my $mid = delete $seen->{$top};
1053                 my $href = mid_escape($mid);
1054                 my $prev_subj = [ split(/ /, $top) ];
1055                 $top = PublicInbox::Hval->new($top)->as_html;
1056                 $ds = fmt_ts($ds);
1057
1058                 # $n isn't the total number of posts on the topic,
1059                 # just the number of posts in the current results window
1060                 my $anchor;
1061                 if ($n == 1) {
1062                         $n = '';
1063                         $anchor = '#u'; # top of only message
1064                 } else {
1065                         $n = " ($n+ messages)";
1066                         $anchor = '#t'; # thread skeleton
1067                 }
1068
1069                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1070                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1071                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
1072                         " $ds UTC $n - $mbox / $atom\n";
1073                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1074                         my $level = $ex[$i];
1075                         my $subj = $ex[$i + 1];
1076                         $mid = delete $seen->{$subj};
1077                         my @subj = split(/ /, $srch->subject_normalized($subj));
1078                         my @next_prev = @subj; # full copy
1079                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1080                         $prev_subj = \@next_prev;
1081                         $subj = ascii_html(join(' ', @subj));
1082                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1083                         $href = mid_escape($mid);
1084                         $s .= indent_for($level) . TCHILD;
1085                         $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1086                 }
1087                 push @out, $s;
1088         }
1089         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1090         200;
1091 }
1092
1093 sub ts2str ($) {
1094         my ($ts) = @_;
1095         POSIX::strftime('%Y%m%d%H%M%S', gmtime($ts));
1096 }
1097
1098 sub str2ts ($) {
1099         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1100         timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1101 }
1102
1103 sub pagination_footer ($$) {
1104         my ($ctx, $latest) = @_;
1105         delete $ctx->{qp} or return;
1106         my $next = $ctx->{next_page} || '';
1107         my $prev = $ctx->{prev_page} || '';
1108         if ($prev) {
1109                 $next = $next ? "$next " : '     ';
1110                 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1111         }
1112         "<hr><pre>page: $next$prev</pre>";
1113 }
1114
1115 sub index_nav { # callback for WwwStream
1116         my (undef, $ctx) = @_;
1117         pagination_footer($ctx, '.')
1118 }
1119
1120 sub paginate_recent ($$) {
1121         my ($ctx, $lim) = @_;
1122         my $t = $ctx->{qp}->{t} || '';
1123         my $opts = { limit => $lim };
1124         my ($after, $before);
1125
1126         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1127         # if only $after exists "YYYYMMDD.." because "." could be skipped
1128         # if interpreted as an end-of-sentence
1129         $t =~ s/\A(\d{8,14})-// and $after = str2ts($1);
1130         $t =~ /\A(\d{8,14})\z/ and $before = str2ts($1);
1131
1132         my $ibx = $ctx->{-inbox};
1133         my $msgs = $ibx->recent($opts, $after, $before);
1134         my $nr = scalar @$msgs;
1135         if ($nr < $lim && defined($after)) {
1136                 $after = $before = undef;
1137                 $msgs = $ibx->recent($opts);
1138                 $nr = scalar @$msgs;
1139         }
1140         my $more = $nr == $lim;
1141         my ($newest, $oldest);
1142         if ($nr) {
1143                 $newest = $msgs->[0]->{ts};
1144                 $oldest = $msgs->[-1]->{ts};
1145                 # if we only had $after, our SQL query in ->recent ordered
1146                 if ($newest < $oldest) {
1147                         ($oldest, $newest) = ($newest, $oldest);
1148                         $more = 0 if defined($after) && $after < $oldest;
1149                 }
1150         }
1151         if (defined($oldest) && $more) {
1152                 my $s = ts2str($oldest);
1153                 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1154         }
1155         if (defined($newest) && (defined($before) || defined($after))) {
1156                 my $s = ts2str($newest);
1157                 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1158         }
1159         $msgs;
1160 }
1161
1162 sub index_topics {
1163         my ($ctx) = @_;
1164         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1165         if (@$msgs) {
1166                 walk_thread(thread_results($ctx, $msgs), $ctx, *acc_topic);
1167         }
1168         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1169 }
1170
1171 sub thread_adj_level {
1172         my ($ctx, $level) = @_;
1173
1174         my $max = $ctx->{cur_level};
1175         if ($level <= 0) {
1176                 return ('', '') if $max == 0; # flat output
1177
1178                 # reset existing lists
1179                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1180                 $ctx->{cur_level} = 0;
1181                 ("$beg</ul>", '');
1182         } elsif ($level == $max) { # continue existing list
1183                 qw(<li> </li>);
1184         } elsif ($level < $max) {
1185                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1186                 $ctx->{cur_level} = $level;
1187                 ("$beg<li>", '</li>');
1188         } else { # ($level > $max) # start a new level
1189                 $ctx->{cur_level} = $level;
1190                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1191                 ($beg, '</li>');
1192         }
1193 }
1194
1195 sub ghost_index_entry {
1196         my ($ctx, $level, $node) = @_;
1197         my ($beg, $end) = thread_adj_level($ctx,  $level);
1198         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1199                 . '</pre>' . $end;
1200 }
1201
1202 1;