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