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