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