]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: remove unused _msg_date sub
[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 $ds = $smsg->ds; # for v1 non-Xapian/SQLite users
222         # deleting {mime} is critical to memory use,
223         # the rest of the fields saves about 400K as we iterate across 1K msgs
224         my ($mime) = delete @$smsg{qw(mime ds ts blob subject)};
225
226         my $hdr = $mime->header_obj;
227         my $from = _hdr_names_html($hdr, 'From');
228         obfuscate_addrs($obfs_ibx, $from) if $obfs_ibx;
229         $rv .= "From: $from @ ".fmt_ts($ds)." UTC";
230         my $upfx = $ctx->{-upfx};
231         my $mhref = $upfx . mid_escape($mid_raw) . '/';
232         $rv .= qq{ (<a\nhref="$mhref">permalink</a> / };
233         $rv .= qq{<a\nhref="${mhref}raw">raw</a>)\n};
234         my $to = fold_addresses(_hdr_names_html($hdr, 'To'));
235         my $cc = fold_addresses(_hdr_names_html($hdr, 'Cc'));
236         my ($tlen, $clen) = (length($to), length($cc));
237         my $to_cc = '';
238         if (($tlen + $clen) > COLS) {
239                 $to_cc .= '  To: '.$to."\n" if $tlen;
240                 $to_cc .= '  Cc: '.$cc."\n" if $clen;
241         } else {
242                 if ($tlen) {
243                         $to_cc .= '  To: '.$to;
244                         $to_cc .= '; <b>+Cc:</b> '.$cc if $clen;
245                 } else {
246                         $to_cc .= '  Cc: '.$cc if $clen;
247                 }
248                 $to_cc .= "\n";
249         }
250         obfuscate_addrs($obfs_ibx, $to_cc) if $obfs_ibx;
251         $rv .= $to_cc;
252
253         my $mapping = $ctx->{mapping};
254         if (!$mapping && (defined($irt) || defined($irt = in_reply_to($hdr)))) {
255                 my $mirt = PublicInbox::Hval->new_msgid($irt);
256                 my $href = $upfx . $mirt->{href}. '/';
257                 my $html = $mirt->as_html;
258                 $rv .= qq(In-Reply-To: &lt;<a\nhref="$href">$html</a>&gt;\n)
259         }
260         $rv .= "\n";
261
262         # scan through all parts, looking for displayable text
263         msg_iter($mime, sub { $rv .= add_text_body($mhref, $obfs_ibx, $_[0]) });
264
265         # add the footer
266         $rv .= "\n<a\nhref=#$id_m\nid=e$id>^</a> ".
267                 "<a\nhref=\"$mhref\">permalink</a>" .
268                 " <a\nhref=\"${mhref}raw\">raw</a>" .
269                 " <a\nhref=\"${mhref}#R\">reply</a>";
270
271         my $hr;
272         if (my $pct = $ctx->{pct}) { # used by SearchView.pm
273                 $rv .= "\t[relevance $pct->{$mid_raw}%]";
274                 $hr = 1;
275         } elsif ($mapping) {
276                 my $nested = 'nested';
277                 my $flat = 'flat';
278                 my $end = '';
279                 if ($ctx->{flat}) {
280                         $hr = 1;
281                         $flat = "<b>$flat</b>";
282                 } else {
283                         $nested = "<b>$nested</b>";
284                 }
285                 $rv .= "\t[<a\nhref=\"${mhref}T/#u\">$flat</a>";
286                 $rv .= "|<a\nhref=\"${mhref}t/#u\">$nested</a>]";
287                 $rv .= " <a\nhref=#r$id>$ctx->{s_nr}</a>";
288         } else {
289                 $hr = $ctx->{-hr};
290         }
291
292         $rv .= $more ? '</pre><hr><pre>' : '</pre>' if $hr;
293         $rv;
294 }
295
296 sub pad_link ($$;$) {
297         my ($mid, $level, $s) = @_;
298         $s ||= '...';
299         my $id = id_compress($mid, 1);
300         (' 'x19).indent_for($level).th_pfx($level)."<a\nhref=#r$id>($s)</a>\n";
301 }
302
303 sub _th_index_lite {
304         my ($mid_raw, $irt, $id, $ctx) = @_;
305         my $rv = '';
306         my $mapping = $ctx->{mapping} or return $rv;
307         my $pad = '  ';
308         my $mid_map = $mapping->{$mid_raw};
309         defined $mid_map or
310                 return 'public-inbox BUG: '.ascii_html($mid_raw).' not mapped';
311         my ($attr, $node, $idx, $level) = @$mid_map;
312         my $children = $node->{children};
313         my $nr_c = scalar @$children;
314         my $nr_s = 0;
315         my $siblings;
316         if (my $smsg = $node->{smsg}) {
317                 # delete saves about 200KB on a 1K message thread
318                 if (my $refs = delete $smsg->{references}) {
319                         ($$irt) = ($refs =~ m/<([^>]+)>\z/);
320                 }
321         }
322         my $irt_map = $mapping->{$$irt} if defined $$irt;
323         if (defined $irt_map) {
324                 $siblings = $irt_map->[1]->{children};
325                 $nr_s = scalar(@$siblings) - 1;
326                 $rv .= $pad . $irt_map->[0];
327                 if ($idx > 0) {
328                         my $prev = $siblings->[$idx - 1];
329                         my $pmid = $prev->{id};
330                         if ($idx > 2) {
331                                 my $s = ($idx - 1). ' preceding siblings ...';
332                                 $rv .= pad_link($pmid, $level, $s);
333                         } elsif ($idx == 2) {
334                                 my $ppmid = $siblings->[0]->{id};
335                                 $rv .= $pad . $mapping->{$ppmid}->[0];
336                         }
337                         $rv .= $pad . $mapping->{$pmid}->[0];
338                 }
339         }
340         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
341         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
342         $attr =~ s!\n\z!</b>\n!s;
343         $attr =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
344         $attr =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
345         $rv .= "<b>@ $attr";
346         if ($nr_c) {
347                 my $cmid = $children->[0]->{id};
348                 $rv .= $pad . $mapping->{$cmid}->[0];
349                 if ($nr_c > 2) {
350                         my $s = ($nr_c - 1). ' more replies';
351                         $rv .= pad_link($cmid, $level + 1, $s);
352                 } elsif (my $cn = $children->[1]) {
353                         $rv .= $pad . $mapping->{$cn->{id}}->[0];
354                 }
355         }
356
357         my $next = $siblings->[$idx+1] if $siblings && $idx >= 0;
358         if ($next) {
359                 my $nmid = $next->{id};
360                 $rv .= $pad . $mapping->{$nmid}->[0];
361                 my $nnext = $nr_s - $idx;
362                 if ($nnext > 2) {
363                         my $s = ($nnext - 1).' subsequent siblings';
364                         $rv .= pad_link($nmid, $level, $s);
365                 } elsif (my $nn = $siblings->[$idx + 2]) {
366                         $rv .= $pad . $mapping->{$nn->{id}}->[0];
367                 }
368         }
369         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
370 }
371
372 sub walk_thread {
373         my ($rootset, $ctx, $cb) = @_;
374         my @q = map { (0, $_, -1) } @$rootset;
375         while (@q) {
376                 my ($level, $node, $i) = splice(@q, 0, 3);
377                 defined $node or next;
378                 $cb->($ctx, $level, $node, $i) or return;
379                 ++$level;
380                 $i = 0;
381                 unshift @q, map { ($level, $_, $i++) } @{$node->{children}};
382         }
383 }
384
385 sub pre_thread  {
386         my ($ctx, $level, $node, $idx) = @_;
387         $ctx->{mapping}->{$node->{id}} = [ '', $node, $idx, $level ];
388         skel_dump($ctx, $level, $node);
389 }
390
391 sub thread_index_entry {
392         my ($ctx, $level, $smsg) = @_;
393         my ($beg, $end) = thread_adj_level($ctx, $level);
394         $beg . '<pre>' . index_entry($smsg, $ctx, 0) . '</pre>' . $end;
395 }
396
397 sub stream_thread ($$) {
398         my ($rootset, $ctx) = @_;
399         my $inbox = $ctx->{-inbox};
400         my @q = map { (0, $_) } @$rootset;
401         my $level;
402         my $smsg;
403         while (@q) {
404                 $level = shift @q;
405                 my $node = shift @q or next;
406                 my $cl = $level + 1;
407                 unshift @q, map { ($cl, $_) } @{$node->{children}};
408                 $smsg = $inbox->smsg_mime($node->{smsg}) and last;
409         }
410         return missing_thread($ctx) unless $smsg;
411
412         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
413         $ctx->{-title_html} = ascii_html($smsg->subject);
414         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $smsg);
415         $smsg = undef;
416         PublicInbox::WwwStream->response($ctx, 200, sub {
417                 return unless $ctx;
418                 while (@q) {
419                         $level = shift @q;
420                         my $node = shift @q or next;
421                         my $cl = $level + 1;
422                         unshift @q, map { ($cl, $_) } @{$node->{children}};
423                         if ($smsg = $inbox->smsg_mime($node->{smsg})) {
424                                 return thread_index_entry($ctx, $level, $smsg);
425                         } else {
426                                 return ghost_index_entry($ctx, $level, $node);
427                         }
428                 }
429                 my $ret = join('', thread_adj_level($ctx, 0));
430                 $ret .= ${$ctx->{dst}}; # skel
431                 $ctx = undef;
432                 $ret;
433         });
434 }
435
436 sub thread_html {
437         my ($ctx) = @_;
438         my $mid = $ctx->{mid};
439         my $srch = $ctx->{srch};
440         my ($nr, $msgs) = $srch->get_thread($mid);
441         return missing_thread($ctx) if $nr == 0;
442         my $skel = '<hr><pre>';
443         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
444         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
445         $skel .= "<b\nid=t>Thread overview:</b> ";
446         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
447         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
448         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
449         $skel .= "-- links below jump to the message on this page --\n";
450         $ctx->{-upfx} = '../../';
451         $ctx->{cur_level} = 0;
452         $ctx->{dst} = \$skel;
453         $ctx->{prev_attr} = '';
454         $ctx->{prev_level} = 0;
455         $ctx->{root_anchor} = anchor_for($mid);
456         $ctx->{mapping} = {};
457         $ctx->{s_nr} = "$nr+ messages in thread";
458
459         my $rootset = thread_results($ctx, $msgs);
460
461         # reduce hash lookups in pre_thread->skel_dump
462         my $inbox = $ctx->{-inbox};
463         $ctx->{-obfs_ibx} = $inbox->{obfuscate} ? $inbox : undef;
464         walk_thread($rootset, $ctx, *pre_thread);
465
466         $skel .= '</pre>';
467         return stream_thread($rootset, $ctx) unless $ctx->{flat};
468
469         # flat display: lazy load the full message from smsg
470         my $smsg;
471         while (my $m = shift @$msgs) {
472                 $smsg = $inbox->smsg_mime($m) and last;
473         }
474         return missing_thread($ctx) unless $smsg;
475         $ctx->{-title_html} = ascii_html($smsg->subject);
476         $ctx->{-html_tip} = '<pre>'.index_entry($smsg, $ctx, scalar @$msgs);
477         $smsg = undef;
478         PublicInbox::WwwStream->response($ctx, 200, sub {
479                 return unless $msgs;
480                 $smsg = undef;
481                 while (my $m = shift @$msgs) {
482                         $smsg = $inbox->smsg_mime($m) and last;
483                 }
484                 return index_entry($smsg, $ctx, scalar @$msgs) if $smsg;
485                 $msgs = undef;
486                 $skel;
487         });
488 }
489
490 sub multipart_text_as_html {
491         my ($mime, $upfx, $obfs_ibx) = @_;
492         my $rv = "";
493
494         # scan through all parts, looking for displayable text
495         msg_iter($mime, sub { $rv .= add_text_body($upfx, $obfs_ibx, $_[0]) });
496         $rv;
497 }
498
499 sub flush_quote {
500         my ($s, $l, $quot) = @_;
501
502         # show everything in the full version with anchor from
503         # short version (see above)
504         my $rv = $l->linkify_1(join('', @$quot));
505         @$quot = ();
506
507         # we use a <span> here to allow users to specify their own
508         # color for quoted text
509         $rv = $l->linkify_2(ascii_html($rv));
510         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
511 }
512
513 sub attach_link ($$$$;$) {
514         my ($upfx, $ct, $p, $fn, $err) = @_;
515         my ($part, $depth, @idx) = @$p;
516         my $nl = $idx[-1] > 1 ? "\n" : '';
517         my $idx = join('.', @idx);
518         my $size = bytes::length($part->body);
519
520         # hide attributes normally, unless we want to aid users in
521         # spotting MUA problems:
522         $ct =~ s/;.*// unless $err;
523         $ct = ascii_html($ct);
524         my $desc = $part->header('Content-Description');
525         $desc = $fn unless defined $desc;
526         $desc = '' unless defined $desc;
527         my $sfn;
528         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
529                 $sfn = $fn;
530         } elsif ($ct eq 'text/plain') {
531                 $sfn = 'a.txt';
532         } else {
533                 $sfn = 'a.bin';
534         }
535         my $ret = qq($nl<a\nhref="$upfx$idx-$sfn">);
536         if ($err) {
537                 $ret .=
538 "[-- Warning: decoded text below may be mangled --]\n";
539         }
540         $ret .= "[-- Attachment #$idx: ";
541         my $ts = "Type: $ct, Size: $size bytes";
542         $desc = ascii_html($desc);
543         $ret .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
544         $ret .= "</a>\n";
545 }
546
547 sub add_text_body {
548         my ($upfx, $obfs_ibx, $p) = @_;
549         # $p - from msg_iter: [ Email::MIME, depth, @idx ]
550         my ($part, $depth) = @$p; # attachment @idx is unused
551         my $ct = $part->content_type || 'text/plain';
552         my $fn = $part->filename;
553         my ($s, $err) = msg_part_text($part, $ct);
554
555         return attach_link($upfx, $ct, $p, $fn) unless defined $s;
556
557         my @lines = split(/^/m, $s);
558         $s = '';
559         if (defined($fn) || $depth > 0 || $err) {
560                 # badly-encoded message with $err? tell the world about it!
561                 $s .= attach_link($upfx, $ct, $p, $fn, $err);
562                 $s .= "\n";
563         }
564         my @quot;
565         my $l = PublicInbox::Linkify->new;
566         foreach my $cur (@lines) {
567                 if ($cur !~ /^>/) {
568                         # show the previously buffered quote inline
569                         flush_quote(\$s, $l, \@quot) if @quot;
570
571                         # regular line, OK
572                         $l->linkify_1($cur);
573                         $s .= $l->linkify_2(ascii_html($cur));
574                 } else {
575                         push @quot, $cur;
576                 }
577         }
578
579         if (@quot) { # ugh, top posted
580                 flush_quote(\$s, $l, \@quot);
581                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
582                 $s;
583         } else {
584                 obfuscate_addrs($obfs_ibx, $s) if $obfs_ibx;
585                 if ($s =~ /\n\z/s) { # common, last line ends with a newline
586                         $s;
587                 } else { # some editors don't do newlines...
588                         $s .= "\n";
589                 }
590         }
591 }
592
593 sub _msg_html_prepare {
594         my ($hdr, $ctx, $more, $nr) = @_;
595         my $srch = $ctx->{srch} if $ctx;
596         my $atom = '';
597         my $obfs_ibx = $ctx->{-obfs_ibx};
598         my $rv = '';
599         my $mids = mids($hdr);
600         my $multiple = scalar(@$mids) > 1; # zero, one, infinity
601         if ($nr == 0) {
602                 if ($more) {
603                         $rv .=
604 "<pre>WARNING: multiple messages refer to this Message-ID\n</pre>";
605                 }
606                 $rv .= "<pre\nid=b>"; # anchor for body start
607         } else {
608                 $rv .= '<pre>';
609         }
610         if ($srch) {
611                 $ctx->{-upfx} = '../';
612         }
613         my @title;
614         my $v;
615         if (defined($v = $hdr->header('From'))) {
616                 $v = PublicInbox::Hval->new($v);
617                 my @n = PublicInbox::Address::names($v->raw);
618                 $title[1] = ascii_html(join(', ', @n));
619                 $v = $v->as_html;
620                 if ($obfs_ibx) {
621                         obfuscate_addrs($obfs_ibx, $v);
622                         obfuscate_addrs($obfs_ibx, $title[1]);
623                 }
624                 $rv .= "From: $v\n" if $v ne '';
625         }
626         foreach my $h (qw(To Cc)) {
627                 defined($v = $hdr->header($h)) or next;
628                 fold_addresses($v);
629                 $v = ascii_html($v);
630                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
631                 $rv .= "$h: $v\n" if $v ne '';
632         }
633         if (defined($v = $hdr->header('Subject')) && ($v ne '')) {
634                 $v = ascii_html($v);
635                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx;
636                 if ($srch) {
637                         $rv .= qq(Subject: <a\nhref="#r"\nid=t>$v</a>\n);
638                 } else {
639                         $rv .= "Subject: $v\n";
640                 }
641                 $title[0] = $v;
642         } else { # dummy anchor for thread skeleton at bottom of page
643                 $rv .= qq(<a\nhref="#r"\nid=t></a>) if $srch;
644                 $title[0] = '(no subject)';
645         }
646         if (defined($v = $hdr->header('Date'))) {
647                 $v = ascii_html($v);
648                 obfuscate_addrs($obfs_ibx, $v) if $obfs_ibx; # possible :P
649                 $rv .= "Date: $v\n";
650         }
651         $ctx->{-title_html} = join(' - ', @title);
652         foreach (@$mids) {
653                 my $mid = PublicInbox::Hval->new_msgid($_) ;
654                 my $mhtml = $mid->as_html;
655                 if ($multiple) {
656                         my $href = $mid->{href};
657                         $rv .= "Message-ID: ";
658                         $rv .= "<a\nhref=\"../$href/\">";
659                         $rv .= "&lt;$mhtml&gt;</a> ";
660                         $rv .= "(<a\nhref=\"../$href/raw\">raw</a>)\n";
661                 } else {
662                         $rv .= "Message-ID: &lt;$mhtml&gt; ";
663                         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
664                 }
665         }
666         $rv .= _parent_headers($hdr, $srch);
667         $rv .= "\n";
668 }
669
670 sub thread_skel {
671         my ($dst, $ctx, $hdr, $tpfx) = @_;
672         my $srch = $ctx->{srch};
673         my $mid = mids($hdr)->[0];
674         my ($nr, $msgs) = $srch->get_thread($mid);
675         my $expand = qq(expand[<a\nhref="${tpfx}T/#u">flat</a>) .
676                         qq(|<a\nhref="${tpfx}t/#u">nested</a>]  ) .
677                         qq(<a\nhref="${tpfx}t.mbox.gz">mbox.gz</a>  ) .
678                         qq(<a\nhref="${tpfx}t.atom">Atom feed</a>);
679
680         my $parent = in_reply_to($hdr);
681         $$dst .= "\n<b>Thread overview: </b>";
682         if ($nr <= 1) {
683                 if (defined $parent) {
684                         $$dst .= "$expand\n ";
685                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
686                 } else {
687                         $$dst .= "[no followups] $expand\n";
688                 }
689                 $ctx->{next_msg} = undef;
690                 $ctx->{parent_msg} = $parent;
691                 return;
692         }
693
694         $$dst .= "$nr+ messages / $expand";
695         $$dst .= qq!  <a\nhref="#b">top</a>\n!;
696
697         my $subj = $hdr->header('Subject');
698         defined $subj or $subj = '';
699         $ctx->{prev_subj} = [ split(/ /, $srch->subject_normalized($subj)) ];
700         $ctx->{cur} = $mid;
701         $ctx->{prev_attr} = '';
702         $ctx->{prev_level} = 0;
703         $ctx->{dst} = $dst;
704
705         # reduce hash lookups in skel_dump
706         my $ibx = $ctx->{-inbox};
707         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
708         walk_thread(thread_results($ctx, $msgs), $ctx, *skel_dump);
709
710         $ctx->{parent_msg} = $parent;
711 }
712
713 sub _parent_headers {
714         my ($hdr, $srch) = @_;
715         my $rv = '';
716
717         my $refs = references($hdr);
718         my $irt = pop @$refs;
719         if (defined $irt) {
720                 my $v = PublicInbox::Hval->new_msgid($irt);
721                 my $html = $v->as_html;
722                 my $href = $v->{href};
723                 $rv .= "In-Reply-To: &lt;";
724                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
725         }
726
727         # do not display References: if search is present,
728         # we show the thread skeleton at the bottom, instead.
729         return $rv if $srch;
730
731         if (@$refs) {
732                 @$refs = map { linkify_ref_nosrch($_) } @$refs;
733                 $rv .= 'References: '. join("\n\t", @$refs) . "\n";
734         }
735         $rv;
736 }
737
738 sub html_footer {
739         my ($hdr, $standalone, $ctx, $rhref) = @_;
740
741         my $srch = $ctx->{srch} if $ctx;
742         my $upfx = '../';
743         my $tpfx = '';
744         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
745         my $irt = '';
746         if ($idx && $srch) {
747                 $idx .= "\n";
748                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
749                 my ($next, $prev);
750                 my $parent = '       ';
751                 $next = $prev = '    ';
752
753                 if (my $n = $ctx->{next_msg}) {
754                         $n = PublicInbox::Hval->new_msgid($n)->{href};
755                         $next = "<a\nhref=\"$upfx$n/\"\nrel=next>next</a>";
756                 }
757                 my $u;
758                 my $par = $ctx->{parent_msg};
759                 if ($par) {
760                         $u = PublicInbox::Hval->new_msgid($par)->{href};
761                         $u = "$upfx$u/";
762                 }
763                 if (my $p = $ctx->{prev_msg}) {
764                         $prev = PublicInbox::Hval->new_msgid($p)->{href};
765                         if ($p && $par && $p eq $par) {
766                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
767                                         'rel=prev>prev parent</a>';
768                                 $parent = '';
769                         } else {
770                                 $prev = "<a\nhref=\"$upfx$prev/\"\n" .
771                                         'rel=prev>prev</a>';
772                                 $parent = " <a\nhref=\"$u\">parent</a>" if $u;
773                         }
774                 } elsif ($u) { # unlikely
775                         $parent = " <a\nhref=\"$u\"\nrel=prev>parent</a>";
776                 }
777                 $irt = "$next $prev$parent ";
778         } else {
779                 $irt = '';
780         }
781         $rhref ||= '#R';
782         $irt .= qq(<a\nhref="$rhref">reply</a>);
783         $irt .= $idx;
784 }
785
786 sub linkify_ref_nosrch {
787         my $v = PublicInbox::Hval->new_msgid($_[0]);
788         my $html = $v->as_html;
789         my $href = $v->{href};
790         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
791 }
792
793 sub anchor_for {
794         my ($msgid) = @_;
795         'm' . id_compress($msgid, 1);
796 }
797
798 sub ghost_parent {
799         my ($upfx, $mid) = @_;
800
801         $mid = PublicInbox::Hval->new_msgid($mid);
802         my $href = $mid->{href};
803         my $html = $mid->as_html;
804         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
805 }
806
807 sub indent_for {
808         my ($level) = @_;
809         $level ? INDENT x ($level - 1) : '';
810 }
811
812 sub find_mid_root {
813         my ($ctx, $level, $node, $idx) = @_;
814         ++$ctx->{root_idx} if $level == 0;
815         if ($node->{id} eq $ctx->{mid}) {
816                 $ctx->{found_mid_at} = $ctx->{root_idx};
817                 return 0;
818         }
819         1;
820 }
821
822 sub strict_loose_note ($) {
823         my ($nr) = @_;
824         my $msg =
825 "  -- strict thread matches above, loose matches on Subject: below --\n";
826
827         if ($nr > PublicInbox::Over::DEFAULT_LIMIT()) {
828                 $msg .=
829 "  -- use mbox.gz link to download all $nr messages --\n";
830         }
831         $msg;
832 }
833
834 sub thread_results {
835         my ($ctx, $msgs) = @_;
836         require PublicInbox::SearchThread;
837         my $ibx = $ctx->{-inbox};
838         my $rootset = PublicInbox::SearchThread::thread($msgs, *sort_ds, $ibx);
839
840         # FIXME: `tid' is broken on --reindex, so that needs to be fixed
841         # and preserved in the future.  This bug is hidden by `sid' matches
842         # in get_thread, so we never noticed it until now.  And even when
843         # reindexing is fixed, we'll keep this code until a SCHEMA_VERSION
844         # bump since reindexing is expensive and users may not do it
845
846         # loose threading could've returned too many results,
847         # put the root the message we care about at the top:
848         my $mid = $ctx->{mid};
849         if (defined($mid) && scalar(@$rootset) > 1) {
850                 $ctx->{root_idx} = -1;
851                 my $nr = scalar @$msgs;
852                 walk_thread($rootset, $ctx, *find_mid_root);
853                 my $idx = $ctx->{found_mid_at};
854                 if (defined($idx) && $idx != 0) {
855                         my $tip = splice(@$rootset, $idx, 1);
856                         @$rootset = reverse @$rootset;
857                         unshift @$rootset, $tip;
858                         $ctx->{sl_note} = strict_loose_note($nr);
859                 }
860         }
861         $rootset
862 }
863
864 sub missing_thread {
865         my ($ctx) = @_;
866         require PublicInbox::ExtMsg;
867         PublicInbox::ExtMsg::ext_msg($ctx);
868 }
869
870 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
871
872 sub dedupe_subject {
873         my ($prev_subj, $subj, $val) = @_;
874
875         my $omit = ''; # '"' denotes identical text omitted
876         my (@prev_pop, @curr_pop);
877         while (@$prev_subj && @$subj && $subj->[-1] eq $prev_subj->[-1]) {
878                 push(@prev_pop, pop(@$prev_subj));
879                 push(@curr_pop, pop(@$subj));
880                 $omit ||= $val;
881         }
882         pop @$subj if @$subj && $subj->[-1] =~ /^re:\s*/i;
883         if (scalar(@curr_pop) == 1) {
884                 $omit = '';
885                 push @$prev_subj, @prev_pop;
886                 push @$subj, @curr_pop;
887         }
888         $omit;
889 }
890
891 sub skel_dump {
892         my ($ctx, $level, $node) = @_;
893         my $smsg = $node->{smsg} or return _skel_ghost($ctx, $level, $node);
894
895         my $dst = $ctx->{dst};
896         my $cur = $ctx->{cur};
897         my $mid = $smsg->{mid};
898
899         if ($level == 0 && $ctx->{skel_dump_roots}++) {
900                 $$dst .= delete $ctx->{sl_note} || '';
901         }
902
903         my $f = ascii_html($smsg->from_name);
904         my $obfs_ibx = $ctx->{-obfs_ibx};
905         obfuscate_addrs($obfs_ibx, $f) if $obfs_ibx;
906
907         my $d = fmt_ts($smsg->{ds}) . ' ' . indent_for($level) . th_pfx($level);
908         my $attr = $f;
909         $ctx->{first_level} ||= $level;
910
911         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
912                 $ctx->{prev_attr} = $attr;
913         }
914         $ctx->{prev_level} = $level;
915
916         if ($cur) {
917                 if ($cur eq $mid) {
918                         delete $ctx->{cur};
919                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
920                                  "$attr [this message]</a></b>\n";
921                         return 1;
922                 } else {
923                         $ctx->{prev_msg} = $mid;
924                 }
925         } else {
926                 $ctx->{next_msg} ||= $mid;
927         }
928
929         # Subject is never undef, this mail was loaded from
930         # our Xapian which would've resulted in '' if it were
931         # really missing (and Filter rejects empty subjects)
932         my @subj = split(/ /, $ctx->{srch}->subject_normalized($smsg->subject));
933
934         # remove common suffixes from the subject if it matches the previous,
935         # so we do not show redundant text at the end.
936         my $prev_subj = $ctx->{prev_subj} || [];
937         $ctx->{prev_subj} = [ @subj ];
938         my $omit = dedupe_subject($prev_subj, \@subj, '&#34; ');
939         my $end;
940         if (@subj) {
941                 my $subj = join(' ', @subj);
942                 $subj = ascii_html($subj);
943                 obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
944                 $end = "$subj</a> $omit$f\n"
945         } else {
946                 $end = "$f</a>\n";
947         }
948         my $m;
949         my $id = '';
950         my $mapping = $ctx->{mapping};
951         if ($mapping) {
952                 my $map = $mapping->{$mid};
953                 $id = id_compress($mid, 1);
954                 $m = '#m'.$id;
955                 $map->[0] = "$d<a\nhref=\"$m\">$end";
956                 $id = "\nid=r".$id;
957         } else {
958                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
959         }
960         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
961         1;
962 }
963
964 sub _skel_ghost {
965         my ($ctx, $level, $node) = @_;
966
967         my $mid = $node->{id};
968         my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
969                             : '     [not found] ';
970         $d .= indent_for($level) . th_pfx($level);
971         my $upfx = $ctx->{-upfx};
972         my $m = PublicInbox::Hval->new_msgid($mid);
973         my $href = $upfx . $m->{href} . '/';
974         my $html = $m->as_html;
975
976         my $mapping = $ctx->{mapping};
977         my $map = $mapping->{$mid} if $mapping;
978         if ($map) {
979                 my $id = id_compress($mid, 1);
980                 $map->[0] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
981                 $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
982         } else {
983                 $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
984         }
985         my $dst = $ctx->{dst};
986         $$dst .= $d;
987         1;
988 }
989
990 sub sort_ds {
991         [ sort {
992                 (eval { $a->topmost->{smsg}->ds } || 0) <=>
993                 (eval { $b->topmost->{smsg}->ds } || 0)
994         } @{$_[0]} ];
995 }
996
997 # accumulate recent topics if search is supported
998 # returns 200 if done, 404 if not
999 sub acc_topic {
1000         my ($ctx, $level, $node) = @_;
1001         my $srch = $ctx->{srch};
1002         my $mid = $node->{id};
1003         my $x = $node->{smsg} || $ctx->{-inbox}->smsg_by_mid($mid);
1004         my ($subj, $ds);
1005         my $topic;
1006         if ($x) {
1007                 $subj = $x->subject;
1008                 $subj = $srch->subject_normalized($subj);
1009                 $ds = $x->ds;
1010                 if ($level == 0) {
1011                         $topic = [ $ds, 1, { $subj => $mid }, $subj ];
1012                         $ctx->{-cur_topic} = $topic;
1013                         push @{$ctx->{order}}, $topic;
1014                         return 1;
1015                 }
1016
1017                 $topic = $ctx->{-cur_topic}; # should never be undef
1018                 $topic->[0] = $ds if $ds > $topic->[0];
1019                 $topic->[1]++;
1020                 my $seen = $topic->[2];
1021                 if (scalar(@$topic) == 3) { # parent was a ghost
1022                         push @$topic, $subj;
1023                 } elsif (!$seen->{$subj}) {
1024                         push @$topic, $level, $subj;
1025                 }
1026                 $seen->{$subj} = $mid; # latest for subject
1027         } else { # ghost message
1028                 return 1 if $level != 0; # ignore child ghosts
1029                 $topic = [ -666, 0, {} ];
1030                 $ctx->{-cur_topic} = $topic;
1031                 push @{$ctx->{order}}, $topic;
1032         }
1033         1;
1034 }
1035
1036 sub dump_topics {
1037         my ($ctx) = @_;
1038         my $order = delete $ctx->{order}; # [ ds, subj1, subj2, subj3, ... ]
1039         if (!@$order) {
1040                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
1041                 return 404;
1042         }
1043
1044         my @out;
1045         my $ibx = $ctx->{-inbox};
1046         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
1047         my $srch = $ctx->{srch};
1048
1049         # sort by recency, this allows new posts to "bump" old topics...
1050         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
1051                 my ($ds, $n, $seen, $top, @ex) = @$topic;
1052                 @$topic = ();
1053                 next unless defined $top;  # ghost topic
1054                 my $mid = delete $seen->{$top};
1055                 my $href = mid_escape($mid);
1056                 my $prev_subj = [ split(/ /, $top) ];
1057                 $top = PublicInbox::Hval->new($top)->as_html;
1058                 $ds = fmt_ts($ds);
1059
1060                 # $n isn't the total number of posts on the topic,
1061                 # just the number of posts in the current results window
1062                 my $anchor;
1063                 if ($n == 1) {
1064                         $n = '';
1065                         $anchor = '#u'; # top of only message
1066                 } else {
1067                         $n = " ($n+ messages)";
1068                         $anchor = '#t'; # thread skeleton
1069                 }
1070
1071                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
1072                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
1073                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
1074                         " $ds UTC $n - $mbox / $atom\n";
1075                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
1076                         my $level = $ex[$i];
1077                         my $subj = $ex[$i + 1];
1078                         $mid = delete $seen->{$subj};
1079                         my @subj = split(/ /, $srch->subject_normalized($subj));
1080                         my @next_prev = @subj; # full copy
1081                         my $omit = dedupe_subject($prev_subj, \@subj, ' &#34;');
1082                         $prev_subj = \@next_prev;
1083                         $subj = ascii_html(join(' ', @subj));
1084                         obfuscate_addrs($obfs_ibx, $subj) if $obfs_ibx;
1085                         $href = mid_escape($mid);
1086                         $s .= indent_for($level) . TCHILD;
1087                         $s .= "<a\nhref=\"$href/T/#u\">$subj</a>$omit\n";
1088                 }
1089                 push @out, $s;
1090         }
1091         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
1092         200;
1093 }
1094
1095 sub ts2str ($) {
1096         my ($ts) = @_;
1097         POSIX::strftime('%Y%m%d%H%M%S', gmtime($ts));
1098 }
1099
1100 sub str2ts ($) {
1101         my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $_[0]);
1102         timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
1103 }
1104
1105 sub pagination_footer ($$) {
1106         my ($ctx, $latest) = @_;
1107         delete $ctx->{qp} or return;
1108         my $next = $ctx->{next_page} || '';
1109         my $prev = $ctx->{prev_page} || '';
1110         if ($prev) {
1111                 $next = $next ? "$next " : '     ';
1112                 $prev .= qq! <a\nhref='$latest'>latest</a>!;
1113         }
1114         "<hr><pre>page: $next$prev</pre>";
1115 }
1116
1117 sub index_nav { # callback for WwwStream
1118         my (undef, $ctx) = @_;
1119         pagination_footer($ctx, '.')
1120 }
1121
1122 sub paginate_recent ($$) {
1123         my ($ctx, $lim) = @_;
1124         my $t = $ctx->{qp}->{t} || '';
1125         my $opts = { limit => $lim };
1126         my ($after, $before);
1127
1128         # Xapian uses '..' but '-' is perhaps friendier to URL linkifiers
1129         # if only $after exists "YYYYMMDD.." because "." could be skipped
1130         # if interpreted as an end-of-sentence
1131         $t =~ s/\A(\d{8,14})-// and $after = str2ts($1);
1132         $t =~ /\A(\d{8,14})\z/ and $before = str2ts($1);
1133
1134         my $ibx = $ctx->{-inbox};
1135         my $msgs = $ibx->recent($opts, $after, $before);
1136         my $nr = scalar @$msgs;
1137         if ($nr < $lim && defined($after)) {
1138                 $after = $before = undef;
1139                 $msgs = $ibx->recent($opts);
1140                 $nr = scalar @$msgs;
1141         }
1142         my $more = $nr == $lim;
1143         my ($newest, $oldest);
1144         if ($nr) {
1145                 $newest = $msgs->[0]->{ts};
1146                 $oldest = $msgs->[-1]->{ts};
1147                 # if we only had $after, our SQL query in ->recent ordered
1148                 if ($newest < $oldest) {
1149                         ($oldest, $newest) = ($newest, $oldest);
1150                         $more = 0 if defined($after) && $after < $oldest;
1151                 }
1152         }
1153         if (defined($oldest) && $more) {
1154                 my $s = ts2str($oldest);
1155                 $ctx->{next_page} = qq!<a\nhref="?t=$s"\nrel=next>next</a>!;
1156         }
1157         if (defined($newest) && (defined($before) || defined($after))) {
1158                 my $s = ts2str($newest);
1159                 $ctx->{prev_page} = qq!<a\nhref="?t=$s-"\nrel=prev>prev</a>!;
1160         }
1161         $msgs;
1162 }
1163
1164 sub index_topics {
1165         my ($ctx) = @_;
1166         my $msgs = paginate_recent($ctx, 200); # 200 is our window
1167         if (@$msgs) {
1168                 walk_thread(thread_results($ctx, $msgs), $ctx, *acc_topic);
1169         }
1170         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1171 }
1172
1173 sub thread_adj_level {
1174         my ($ctx, $level) = @_;
1175
1176         my $max = $ctx->{cur_level};
1177         if ($level <= 0) {
1178                 return ('', '') if $max == 0; # flat output
1179
1180                 # reset existing lists
1181                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1182                 $ctx->{cur_level} = 0;
1183                 ("$beg</ul>", '');
1184         } elsif ($level == $max) { # continue existing list
1185                 qw(<li> </li>);
1186         } elsif ($level < $max) {
1187                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1188                 $ctx->{cur_level} = $level;
1189                 ("$beg<li>", '</li>');
1190         } else { # ($level > $max) # start a new level
1191                 $ctx->{cur_level} = $level;
1192                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1193                 ($beg, '</li>');
1194         }
1195 }
1196
1197 sub ghost_index_entry {
1198         my ($ctx, $level, $node) = @_;
1199         my ($beg, $end) = thread_adj_level($ctx,  $level);
1200         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $node->{id})
1201                 . '</pre>' . $end;
1202 }
1203
1204 1;