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