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