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