]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: try to display bogus charsets for text/plain
[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         # map = [children, attr, node, idx, level]
205         my $map = $mapping->{$mid_raw};
206         my $nr_c = scalar @{$map->[0]};
207         my $nr_s = 0;
208         my $level = $map->[4];
209         my $idx = $map->[3];
210         my $irt_map = $mapping->{$irt} if defined $irt;
211         if (defined $irt_map) {
212                 my $siblings = $irt_map->[0];
213                 $nr_s = scalar(@$siblings) - 1;
214                 $rv .= $pad . $irt_map->[1];
215                 if ($idx > 0) {
216                         my $prev = $siblings->[$idx - 1];
217                         my $pmid = $prev->messageid;
218                         if ($idx > 2) {
219                                 my $s = ($idx - 1). ' preceding siblings ...';
220                                 $rv .= pad_link($pmid, $level, $s);
221                         } elsif ($idx == 2) {
222                                 my $ppmid = $siblings->[0]->messageid;
223                                 $rv .= $pad . $mapping->{$ppmid}->[1];
224                         }
225                         $rv .= $pad . $mapping->{$pmid}->[1];
226                 }
227         }
228         my $s_s = nr_to_s($nr_s, 'sibling', 'siblings');
229         my $s_c = nr_to_s($nr_c, 'reply', 'replies');
230         my $this = $map->[1];
231         $this =~ s!\n\z!</b>\n!s;
232         $this =~ s!<a\nhref.*</a> !!s; # no point in duplicating subject
233         $this =~ s!<a\nhref=[^>]+>([^<]+)</a>!$1!s; # no point linking to self
234         $rv .= "<b>@ $this";
235         my $node = $map->[2];
236         if (my $child = $node->child) {
237                 my $cmid = $child->messageid;
238                 $rv .= $pad . $mapping->{$cmid}->[1];
239                 if ($nr_c > 2) {
240                         my $s = ($nr_c - 1). ' more replies';
241                         $rv .= pad_link($cmid, $level + 1, $s);
242                 } elsif (my $cn = $child->next) {
243                         $rv .= $pad . $mapping->{$cn->messageid}->[1];
244                 }
245         }
246         if (my $next = $node->next) {
247                 my $nmid = $next->messageid;
248                 $rv .= $pad . $mapping->{$nmid}->[1];
249                 my $nnext = $nr_s - $idx;
250                 if ($nnext > 2) {
251                         my $s = ($nnext - 1).' subsequent siblings';
252                         $rv .= pad_link($nmid, $level, $s);
253                 } elsif (my $nn = $next->next) {
254                         $rv .= $pad . $mapping->{$nn->messageid}->[1];
255                 }
256         }
257         $rv .= $pad ."<a\nhref=#r$id>$s_s, $s_c; $ctx->{s_nr}</a>\n";
258 }
259
260 sub walk_thread {
261         my ($th, $ctx, $cb) = @_;
262         my @q = map { (0, $_) } $th->rootset;
263         while (@q) {
264                 my $level = shift @q;
265                 my $node = shift @q or next;
266                 $cb->($ctx, $level, $node);
267                 unshift @q, $level+1, $node->child, $level, $node->next;
268         }
269 }
270
271 sub pre_thread  {
272         my ($ctx, $level, $node) = @_;
273         my $mapping = $ctx->{mapping};
274         my $idx = -1;
275         if (my $parent = $node->parent) {
276                 my $m = $mapping->{$parent->messageid}->[0];
277                 $idx = scalar @$m;
278                 push @$m, $node;
279         }
280         $mapping->{$node->messageid} = [ [], '', $node, $idx, $level ];
281         skel_dump($ctx, $level, $node);
282 }
283
284 sub thread_index_entry {
285         my ($ctx, $level, $mime) = @_;
286         my ($beg, $end) = thread_adj_level($ctx, $level);
287         $beg . '<pre>' . index_entry($mime, $ctx, 0) . '</pre>' . $end;
288 }
289
290 sub stream_thread ($$) {
291         my ($th, $ctx) = @_;
292         my $inbox = $ctx->{-inbox};
293         my $mime;
294         my @q = map { (0, $_) } $th->rootset;
295         my $level;
296         while (@q) {
297                 $level = shift @q;
298                 my $node = shift @q or next;
299                 unshift @q, $level+1, $node->child, $level, $node->next;
300                 $mime = $inbox->msg_by_mid($node->messageid) and last;
301         }
302         return missing_thread($ctx) unless $mime;
303
304         $mime = Email::MIME->new($mime);
305         $ctx->{-title_html} = ascii_html($mime->header('Subject'));
306         $ctx->{-html_tip} = thread_index_entry($ctx, $level, $mime);
307         PublicInbox::WwwStream->response($ctx, 200, sub {
308                 return unless $ctx;
309                 while (@q) {
310                         $level = shift @q;
311                         my $node = shift @q or next;
312                         unshift @q, $level+1, $node->child, $level, $node->next;
313                         my $mid = $node->messageid;
314                         if ($mime = $inbox->msg_by_mid($mid)) {
315                                 $mime = Email::MIME->new($mime);
316                                 return thread_index_entry($ctx, $level, $mime);
317                         } else {
318                                 return ghost_index_entry($ctx, $level, $mid);
319                         }
320                 }
321                 my $ret = join('', thread_adj_level($ctx, 0));
322                 $ret .= ${$ctx->{dst}}; # skel
323                 $ctx = undef;
324                 $ret;
325         });
326 }
327
328 sub thread_html {
329         my ($ctx) = @_;
330         my $mid = $ctx->{mid};
331         my $sres = $ctx->{srch}->get_thread($mid, { asc => 1 });
332         my $msgs = load_results($sres);
333         my $nr = $sres->{total};
334         return missing_thread($ctx) if $nr == 0;
335         my $skel = '<hr><pre>';
336         $skel .= $nr == 1 ? 'only message in thread' : 'end of thread';
337         $skel .= ", back to <a\nhref=\"../../\">index</a>\n\n";
338         $skel .= "<b\nid=t>Thread overview:</b> ";
339         $skel .= $nr == 1 ? '(only message)' : "$nr+ messages";
340         $skel .= " (download: <a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
341         $skel .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>)\n";
342         $skel .= "-- links below jump to the message on this page --\n";
343         $ctx->{-upfx} = '../../';
344         $ctx->{cur_level} = 0;
345         $ctx->{dst} = \$skel;
346         $ctx->{prev_attr} = '';
347         $ctx->{prev_level} = 0;
348         $ctx->{root_anchor} = anchor_for($mid);
349         $ctx->{seen} = {};
350         $ctx->{mapping} = {};
351         $ctx->{s_nr} = "$nr+ messages in thread";
352
353         my $th = thread_results($msgs);
354         walk_thread($th, $ctx, *pre_thread);
355         $skel .= '</pre>';
356         return stream_thread($th, $ctx) unless $ctx->{flat};
357
358         # flat display: lazy load the full message from mini_mime:
359         my $inbox = $ctx->{-inbox};
360         my $mime;
361         while ($mime = shift @$msgs) {
362                 $mime = $inbox->msg_by_mid(mid_clean(mid_mime($mime))) and last;
363         }
364         return missing_thread($ctx) unless $mime;
365         $mime = Email::MIME->new($mime);
366         $ctx->{-title_html} = ascii_html($mime->header('Subject'));
367         $ctx->{-html_tip} = '<pre>'.index_entry($mime, $ctx, scalar @$msgs);
368         $mime = undef;
369         PublicInbox::WwwStream->response($ctx, 200, sub {
370                 return unless $msgs;
371                 while ($mime = shift @$msgs) {
372                         $mid = mid_clean(mid_mime($mime));
373                         $mime = $inbox->msg_by_mid($mid) and last;
374                 }
375                 if ($mime) {
376                         $mime = Email::MIME->new($mime);
377                         return index_entry($mime, $ctx, scalar @$msgs);
378                 }
379                 $msgs = undef;
380                 $skel;
381         });
382 }
383
384 sub multipart_text_as_html {
385         my ($mime, $upfx) = @_;
386         my $rv = "";
387
388         # scan through all parts, looking for displayable text
389         msg_iter($mime, sub {
390                 my ($p) = @_;
391                 $rv .= add_text_body($upfx, $p);
392         });
393         $rv;
394 }
395
396 sub flush_quote {
397         my ($s, $l, $quot) = @_;
398
399         # show everything in the full version with anchor from
400         # short version (see above)
401         my $rv = $l->linkify_1(join('', @$quot));
402         @$quot = ();
403
404         # we use a <span> here to allow users to specify their own
405         # color for quoted text
406         $rv = $l->linkify_2(ascii_html($rv));
407         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
408 }
409
410 sub attach_link ($$$$;$) {
411         my ($upfx, $ct, $p, $fn, $err) = @_;
412         my ($part, $depth, @idx) = @$p;
413         my $nl = $idx[-1] > 1 ? "\n" : '';
414         my $idx = join('.', @idx);
415         my $size = bytes::length($part->body);
416         $ct ||= 'text/plain';
417
418         # hide attributes normally, unless we want to aid users in
419         # spotting MUA problems:
420         $ct =~ s/;.*// unless $err;
421         $ct = ascii_html($ct);
422         my $desc = $part->header('Content-Description');
423         $desc = $fn unless defined $desc;
424         $desc = '' unless defined $desc;
425         my $sfn;
426         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
427                 $sfn = $fn;
428         } elsif ($ct eq 'text/plain') {
429                 $sfn = 'a.txt';
430         } else {
431                 $sfn = 'a.bin';
432         }
433         my $ret = qq($nl<a\nhref="$upfx$idx-$sfn">);
434         if ($err) {
435                 $ret .=
436 "[-- Warning: decoded text below may be mangled --]\n";
437         }
438         $ret .= "[-- Attachment #$idx: ";
439         my $ts = "Type: $ct, Size: $size bytes";
440         $ret .= ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]";
441         $ret .= "</a>\n";
442 }
443
444 sub add_text_body {
445         my ($upfx, $p) = @_; # from msg_iter: [ Email::MIME, depth, @idx ]
446         my ($part, $depth, @idx) = @$p;
447         my $ct = $part->content_type;
448         my $fn = $part->filename;
449
450         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
451                 return attach_link($upfx, $ct, $p, $fn);
452         }
453
454         my $s = eval { $part->body_str };
455
456         # badly-encoded message? tell the world about it!
457         my $err = $@;
458         if ($err) {
459                 if ($ct =~ m!\btext/plain\b!i) {
460                         # attach_link will warn further down...
461                         $s = $part->body;
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         # 'subject dummy' is used internally by Mail::Thread
722         return '[no common parent]' if ($mid eq 'subject dummy');
723
724         $mid = PublicInbox::Hval->new_msgid($mid);
725         my $href = $mid->{href};
726         my $html = $mid->as_html;
727         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
728 }
729
730 sub indent_for {
731         my ($level) = @_;
732         INDENT x ($level - 1);
733 }
734
735 sub load_results {
736         my ($sres) = @_;
737
738         [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
739 }
740
741 sub msg_timestamp {
742         my ($hdr) = @_;
743         my $ts = eval { str2time($hdr->header('Date')) };
744         defined($ts) ? $ts : 0;
745 }
746
747 sub thread_results {
748         my ($msgs) = @_;
749         require PublicInbox::Thread;
750         my $th = PublicInbox::Thread->new(@$msgs);
751         $th->thread;
752         $th->order(*sort_ts);
753         $th
754 }
755
756 sub missing_thread {
757         my ($ctx) = @_;
758         require PublicInbox::ExtMsg;
759         PublicInbox::ExtMsg::ext_msg($ctx);
760 }
761
762 sub _msg_date {
763         my ($hdr) = @_;
764         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
765         fmt_ts($ts);
766 }
767
768 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
769
770 sub _skel_header {
771         my ($ctx, $hdr, $level) = @_;
772
773         my $dst = $ctx->{dst};
774         my $cur = $ctx->{cur};
775         my $mid = mid_clean($hdr->header_raw('Message-ID'));
776         my $f = ascii_html($hdr->header('X-PI-From'));
777         my $d = _msg_date($hdr) . ' ' . indent_for($level) . th_pfx($level);
778         my $attr = $f;
779         $ctx->{first_level} ||= $level;
780
781         if ($attr ne $ctx->{prev_attr} || $ctx->{prev_level} > $level) {
782                 $ctx->{prev_attr} = $attr;
783         }
784         $ctx->{prev_level} = $level;
785
786         if ($cur) {
787                 if ($cur eq $mid) {
788                         delete $ctx->{cur};
789                         $$dst .= "<b>$d<a\nid=r\nhref=\"#t\">".
790                                  "$attr [this message]</a></b>\n";
791                         return;
792                 } else {
793                         $ctx->{prev_msg} = $mid;
794                 }
795         } else {
796                 $ctx->{next_msg} ||= $mid;
797         }
798
799         # Subject is never undef, this mail was loaded from
800         # our Xapian which would've resulted in '' if it were
801         # really missing (and Filter rejects empty subjects)
802         my $s = $hdr->header('Subject');
803         my $h = $ctx->{srch}->subject_path($s);
804         if ($ctx->{seen}->{$h}) {
805                 $s = undef;
806         } else {
807                 $ctx->{seen}->{$h} = 1;
808                 $s = PublicInbox::Hval->new($s);
809                 $s = $s->as_html;
810         }
811         my $m;
812         my $id = '';
813         my $mapping = $ctx->{mapping};
814         my $end = defined($s) ? "$s</a> $f\n" : "$f</a>\n";
815         if ($mapping) {
816                 my $map = $mapping->{$mid};
817                 $id = id_compress($mid, 1);
818                 $m = '#m'.$id;
819                 $map->[1] = "$d<a\nhref=\"$m\">$end";
820                 $id = "\nid=r".$id;
821         } else {
822                 $m = $ctx->{-upfx}.mid_escape($mid).'/';
823         }
824         $$dst .=  $d . "<a\nhref=\"$m\"$id>" . $end;
825 }
826
827 sub skel_dump {
828         my ($ctx, $level, $node) = @_;
829         if (my $mime = $node->message) {
830                 _skel_header($ctx, $mime->header_obj, $level);
831         } else {
832                 my $mid = $node->messageid;
833                 my $dst = $ctx->{dst};
834                 my $mapping = $ctx->{mapping};
835                 my $map = $mapping->{$mid} if $mapping;
836                 if ($mid eq 'subject dummy') {
837                         my $ncp = "\t[no common parent]\n";
838                         $map->[1] = $ncp if $map;
839                         $$dst .= $ncp;
840                         return;
841                 }
842                 my $d = $ctx->{pct} ? '    [irrelevant] ' # search result
843                                     : '     [not found] ';
844                 $d .= indent_for($level) . th_pfx($level);
845                 my $upfx = $ctx->{-upfx};
846                 my $m = PublicInbox::Hval->new_msgid($mid);
847                 my $href = $upfx . $m->{href} . '/';
848                 my $html = $m->as_html;
849
850                 if ($map) {
851                         my $id = id_compress($mid, 1);
852                         $map->[1] = $d . qq{&lt;<a\nhref=#r$id>$html</a>&gt;\n};
853                         $d .= qq{&lt;<a\nhref="$href"\nid=r$id>$html</a>&gt;\n};
854                 } else {
855                         $d .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
856                 }
857                 $$dst .= $d;
858         }
859 }
860
861 sub sort_ts {
862         sort {
863                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
864                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
865         } @_;
866 }
867
868 sub _tryload_ghost ($$) {
869         my ($srch, $mid) = @_;
870         my $smsg = $srch->lookup_mail($mid) or return;
871         $smsg->mini_mime;
872 }
873
874 # accumulate recent topics if search is supported
875 # returns 200 if done, 404 if not
876 sub acc_topic {
877         my ($ctx, $level, $node) = @_;
878         my $srch = $ctx->{srch};
879         my $mid = $node->messageid;
880         my $x = $node->message || _tryload_ghost($srch, $mid);
881         my ($subj, $ts);
882         my $topic;
883         if ($x) {
884                 $x = $x->header_obj;
885                 $subj = $x->header('Subject') || '';
886                 $subj = $srch->subject_normalized($subj);
887                 $ts = $x->header('X-PI-TS');
888                 if ($level == 0) {
889                         $topic = [ $ts, 1, { $subj => $mid }, $subj ];
890                         $ctx->{-cur_topic} = $topic;
891                         push @{$ctx->{order}}, $topic;
892                         return;
893                 }
894
895                 $topic = $ctx->{-cur_topic}; # should never be undef
896                 $topic->[0] = $ts if $ts > $topic->[0];
897                 $topic->[1]++;
898                 my $seen = $topic->[2];
899                 if (scalar(@$topic) == 3) { # parent was a ghost
900                         push @$topic, $subj;
901                 } elsif (!$seen->{$subj}) {
902                         push @$topic, $level, $subj;
903                 }
904                 $seen->{$subj} = $mid; # latest for subject
905         } else { # ghost message
906                 return if $level != 0; # ignore child ghosts
907                 $topic = [ -666, 0, {} ];
908                 $ctx->{-cur_topic} = $topic;
909                 push @{$ctx->{order}}, $topic;
910         }
911 }
912
913 sub dump_topics {
914         my ($ctx) = @_;
915         my $order = delete $ctx->{order}; # [ ts, subj1, subj2, subj3, ... ]
916         if (!@$order) {
917                 $ctx->{-html_tip} = '<pre>[No topics in range]</pre>';
918                 return 404;
919         }
920
921         my @out;
922
923         # sort by recency, this allows new posts to "bump" old topics...
924         foreach my $topic (sort { $b->[0] <=> $a->[0] } @$order) {
925                 my ($ts, $n, $seen, $top, @ex) = @$topic;
926                 @$topic = ();
927                 next unless defined $top;  # ghost topic
928                 my $mid = delete $seen->{$top};
929                 my $href = mid_escape($mid);
930                 $top = PublicInbox::Hval->new($top)->as_html;
931                 $ts = fmt_ts($ts);
932
933                 # $n isn't the total number of posts on the topic,
934                 # just the number of posts in the current results window
935                 my $anchor;
936                 if ($n == 1) {
937                         $n = '';
938                         $anchor = '#u'; # top of only message
939                 } else {
940                         $n = " ($n+ messages)";
941                         $anchor = '#t'; # thread skeleton
942                 }
943
944                 my $mbox = qq(<a\nhref="$href/t.mbox.gz">mbox.gz</a>);
945                 my $atom = qq(<a\nhref="$href/t.atom">Atom</a>);
946                 my $s = "<a\nhref=\"$href/T/$anchor\"><b>$top</b></a>\n" .
947                         " $ts UTC $n - $mbox / $atom\n";
948                 for (my $i = 0; $i < scalar(@ex); $i += 2) {
949                         my $level = $ex[$i];
950                         my $sub = $ex[$i + 1];
951                         $mid = delete $seen->{$sub};
952                         $sub = PublicInbox::Hval->new($sub)->as_html;
953                         $href = mid_escape($mid);
954                         $s .= indent_for($level) . TCHILD;
955                         $s .= "<a\nhref=\"$href/T/#u\">$sub</a>\n";
956                 }
957                 push @out, $s;
958         }
959         $ctx->{-html_tip} = '<pre>' . join("\n", @out) . '</pre>';
960         200;
961 }
962
963 sub index_nav { # callback for WwwStream
964         my (undef, $ctx) = @_;
965         delete $ctx->{qp} or return;
966         my ($next, $prev);
967         $next = $prev = '    ';
968         my $latest = '';
969
970         my $next_o = $ctx->{-next_o};
971         if ($next_o) {
972                 $next = qq!<a\nhref="?o=$next_o"\nrel=next>next</a>!;
973         }
974         if (my $cur_o = $ctx->{-cur_o}) {
975                 $latest = qq! <a\nhref=.>latest</a>!;
976
977                 my $o = $cur_o - ($next_o - $cur_o);
978                 if ($o > 0) {
979                         $prev = qq!<a\nhref="?o=$o"\nrel=prev>prev</a>!;
980                 } elsif ($o == 0) {
981                         $prev = qq!<a\nhref=.\nrel=prev>prev</a>!;
982                 }
983         }
984         "<hr><pre>page: $next $prev$latest</pre>";
985 }
986
987 sub index_topics {
988         my ($ctx) = @_;
989         my ($off) = (($ctx->{qp}->{o} || '0') =~ /(\d+)/);
990         my $opts = { offset => $off, limit => 200 };
991
992         $ctx->{order} = [];
993         my $sres = $ctx->{srch}->query('', $opts);
994         my $nr = scalar @{$sres->{msgs}};
995         if ($nr) {
996                 $sres = load_results($sres);
997                 walk_thread(thread_results($sres), $ctx, *acc_topic);
998         }
999         $ctx->{-next_o} = $off+ $nr;
1000         $ctx->{-cur_o} = $off;
1001         PublicInbox::WwwStream->response($ctx, dump_topics($ctx), *index_nav);
1002 }
1003
1004 sub thread_adj_level {
1005         my ($ctx, $level) = @_;
1006
1007         my $max = $ctx->{cur_level};
1008         if ($level <= 0) {
1009                 return ('', '') if $max == 0; # flat output
1010
1011                 # reset existing lists
1012                 my $beg = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
1013                 $ctx->{cur_level} = 0;
1014                 ("$beg</ul>", '');
1015         } elsif ($level == $max) { # continue existing list
1016                 qw(<li> </li>);
1017         } elsif ($level < $max) {
1018                 my $beg = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
1019                 $ctx->{cur_level} = $level;
1020                 ("$beg<li>", '</li>');
1021         } else { # ($level > $max) # start a new level
1022                 $ctx->{cur_level} = $level;
1023                 my $beg = ($max ? '<li>' : '') . '<ul><li>';
1024                 ($beg, '</li>');
1025         }
1026 }
1027
1028 sub ghost_index_entry {
1029         my ($ctx, $level, $mid) = @_;
1030         my ($beg, $end) = thread_adj_level($ctx,  $level);
1031         $beg . '<pre>'. ghost_parent($ctx->{-upfx}, $mid) . '</pre>' . $end;
1032 }
1033
1034 1;