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