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