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