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