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