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