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