]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: show To/Cc destinations in conversation view
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
7 use strict;
8 use warnings;
9 use URI::Escape qw/uri_escape_utf8/;
10 use Date::Parse qw/str2time/;
11 use Encode::MIME::Header;
12 use Plack::Util;
13 use PublicInbox::Hval qw/ascii_html/;
14 use PublicInbox::Linkify;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
16 use PublicInbox::MsgIter;
17 use PublicInbox::Address;
18 use PublicInbox::WwwStream;
19 require POSIX;
20
21 use constant INDENT => '  ';
22 use constant TCHILD => '` ';
23 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
24
25 # public functions: (unstable)
26 sub msg_html {
27         my ($ctx, $mime, $footer) = @_;
28         my $hdr = $mime->header_obj;
29         my $tip = _msg_html_prepare($hdr, $ctx);
30         PublicInbox::WwwStream->new($ctx, sub {
31                 my ($nr, undef) = @_;
32                 if ($nr == 1) {
33                         $tip . multipart_text_as_html($mime, '') .
34                                 '</pre><hr />'
35                 } elsif ($nr == 2) {
36                         # fake an EOF if generating the footer fails;
37                         # we want to at least show the message if something
38                         # here crashes:
39                         eval {
40                                 '<pre>' . html_footer($hdr, 1, $ctx) .
41                                 '</pre>' . msg_reply($ctx, $hdr)
42                         };
43                 } else {
44                         undef
45                 }
46         });
47 }
48
49 # /$INBOX/$MESSAGE_ID/#R
50 sub msg_reply {
51         my ($ctx, $hdr) = @_;
52         my $se_url = 'https://git-htmldocs.bogomips.org/git-send-email.html';
53
54         my ($arg, $link) = mailto_arg_link($hdr);
55         push @$arg, '/path/to/YOUR_REPLY';
56
57         "<pre\nid=R>".
58         "You may reply publically to <a\nhref=#t>this message</a> via\n".
59         "plain-text email using any one of the following methods:\n\n" .
60         "* Save the following mbox file, import it into your mail client,\n" .
61         "  and reply-to-all from there: <a\nhref=raw>mbox</a>\n\n" .
62         "* Reply to all the recipients using the <b>--to</b>, <b>--cc</b>,\n" .
63         "  and <b>--in-reply-to</b> switches of git-send-email(1):\n\n" .
64         "  git send-email \\\n    " .
65         join(" \\\n    ", @$arg ). "\n\n" .
66         qq(  <a\nhref="$se_url">$se_url</a>\n\n) .
67         "* If your mail client supports setting the <b>In-Reply-To</b>" .
68         " header\n  via mailto: links, try the " .
69         qq(<a\nhref="$link">mailto: link</a>\n) .
70         '</pre>';
71 }
72
73 sub in_reply_to {
74         my ($hdr) = @_;
75         my $irt = $hdr->header_raw('In-Reply-To');
76
77         return mid_clean($irt) if (defined $irt);
78
79         my $refs = $hdr->header_raw('References');
80         if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
81                 return $1;
82         }
83         undef;
84 }
85
86 sub _hdr_names ($$) {
87         my ($hdr, $field) = @_;
88         my $val = $hdr->header($field) or return '';
89         ascii_html(join(', ', PublicInbox::Address::names($val)));
90 }
91
92 # this is already inside a <pre>
93 sub index_entry {
94         my ($mime, $level, $state) = @_;
95         my $midx = $state->{anchor_idx}++;
96         my $ctx = $state->{ctx};
97         my $srch = $ctx->{srch};
98         my $hdr = $mime->header_obj;
99         my $subj = $hdr->header('Subject');
100
101         my $mid_raw = mid_clean(mid_mime($mime));
102         my $id = anchor_for($mid_raw);
103         my $seen = $state->{seen};
104         $seen->{$id} = "#$id"; # save the anchor for children, later
105
106         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
107
108         my $root_anchor = $state->{root_anchor} || '';
109         my $path = $root_anchor ? '../../' : '';
110         my $href = $mid->as_href;
111         my $irt = in_reply_to($hdr);
112         my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
113
114         $subj = ascii_html($subj);
115         $subj = "<a\nhref=\"${path}$href/\">$subj</a>";
116         $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id;
117
118         my $ts = _msg_date($hdr);
119         my $rv = "<pre\nid=s$midx>";
120         $rv .= "<b\nid=$id>$subj</b>\n";
121         my $txt = "${path}$href/raw";
122         my $fh = $state->{fh};
123         my $from = _hdr_names($hdr, 'From');
124         $rv .= "- $from @ $ts UTC (<a\nhref=\"$txt\">raw</a>)\n";
125         my @tocc;
126         foreach my $f (qw(To Cc)) {
127                 my $dst = _hdr_names($hdr, $f);
128                 push @tocc, "$f: $dst" if $dst ne '';
129         }
130         $rv .= '  '.join('; +', @tocc) . "\n" if @tocc;
131         $fh->write($rv .= "\n");
132
133         my $mhref = "${path}$href/";
134
135         # scan through all parts, looking for displayable text
136         msg_iter($mime, sub { index_walk($fh, $mhref, $_[0]) });
137         $rv = "\n" . html_footer($hdr, 0, $ctx, "$path$href/#R");
138
139         if (defined $irt) {
140                 unless (defined $parent_anchor) {
141                         my $v = PublicInbox::Hval->new_msgid($irt, 1);
142                         $v = $v->as_href;
143                         $parent_anchor = "${path}$v/";
144                 }
145                 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
146         }
147         if (my $pct = $state->{pct}) { # used by SearchView.pm
148                 $rv .= " [relevance $pct->{$mid_raw}%]";
149         } elsif ($srch) {
150                 my $threaded = 'threaded';
151                 my $flat = 'flat';
152                 my $end = '';
153                 if ($ctx->{flat}) {
154                         $flat = "<b>$flat</b>";
155                         $end = "\n"; # for lynx
156                 } else {
157                         $threaded = "<b>$threaded</b>";
158                 }
159                 $rv .= " [<a\nhref=\"${path}$href/t/#u\">$threaded</a>";
160                 $rv .= "|<a\nhref=\"${path}$href/T/#u\">$flat</a>]$end";
161         }
162         $fh->write($rv .= '</pre>');
163 }
164
165 sub thread_html {
166         my ($ctx, $foot, $srch) = @_;
167         # $_[0] in sub is the Plack callback
168         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
169 }
170
171 sub walk_thread {
172         my ($th, $state, $cb) = @_;
173         my @q = map { (0, $_) } $th->rootset;
174         while (@q) {
175                 my $level = shift @q;
176                 my $node = shift @q or next;
177                 $cb->($state, $level, $node);
178                 unshift @q, $level+1, $node->child, $level, $node->next;
179         }
180 }
181
182 # only private functions below.
183
184 sub emit_thread_html {
185         my ($res, $ctx, $foot, $srch) = @_;
186         my $mid = $ctx->{mid};
187         my $flat = $ctx->{flat};
188         my $msgs = load_results($srch->get_thread($mid, { asc => $flat }));
189         my $nr = scalar @$msgs;
190         return missing_thread($res, $ctx) if $nr == 0;
191         my $seen = {};
192         my $state = {
193                 res => $res,
194                 ctx => $ctx,
195                 seen => $seen,
196                 root_anchor => anchor_for($mid),
197                 anchor_idx => 0,
198                 cur_level => 0,
199         };
200
201         require PublicInbox::Git;
202         $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
203         if ($flat) {
204                 pre_anchor_entry($seen, $_) for (@$msgs);
205                 __thread_entry($state, $_, 0) for (@$msgs);
206         } else {
207                 walk_thread(thread_results($msgs), $state, *thread_entry);
208                 if (my $max = $state->{cur_level}) {
209                         $state->{fh}->write(
210                                 ('</ul></li>' x ($max - 1)) . '</ul>');
211                 }
212         }
213
214         # there could be a race due to a message being deleted in git
215         # but still being in the Xapian index:
216         my $fh = delete $state->{fh} or return missing_thread($res, $ctx);
217
218         my $final_anchor = $state->{anchor_idx};
219         my $next = "<a\nid=s$final_anchor>";
220         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
221         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
222         $next .= "\ndownload thread: ";
223         $next .= "<a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
224         $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
225         $fh->write('<hr /><pre>' . $next . "\n\n".
226                         $foot .  '</pre></body></html>');
227         $fh->close;
228 }
229
230 sub index_walk {
231         my ($fh, $upfx, $p) = @_;
232         my $s = add_text_body($upfx, $p);
233
234         return if $s eq '';
235
236         $fh->write($s);
237 }
238
239 sub multipart_text_as_html {
240         my ($mime, $upfx) = @_;
241         my $rv = "";
242
243         # scan through all parts, looking for displayable text
244         msg_iter($mime, sub {
245                 my ($p) = @_;
246                 $rv .= add_text_body($upfx, $p);
247         });
248         $rv;
249 }
250
251 sub flush_quote {
252         my ($s, $l, $quot) = @_;
253
254         # show everything in the full version with anchor from
255         # short version (see above)
256         my $rv = $l->linkify_1(join('', @$quot));
257         @$quot = ();
258
259         # we use a <span> here to allow users to specify their own
260         # color for quoted text
261         $rv = $l->linkify_2(ascii_html($rv));
262         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
263 }
264
265 sub attach_link ($$$$) {
266         my ($upfx, $ct, $p, $fn) = @_;
267         my ($part, $depth, @idx) = @$p;
268         my $nl = $idx[-1] > 1 ? "\n" : '';
269         my $idx = join('.', @idx);
270         my $size = bytes::length($part->body);
271         $ct ||= 'text/plain';
272         $ct =~ s/;.*//; # no attributes
273         $ct = ascii_html($ct);
274         my $desc = $part->header('Content-Description');
275         $desc = $fn unless defined $desc;
276         $desc = '' unless defined $desc;
277         my $sfn;
278         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
279                 $sfn = $fn;
280         } elsif ($ct eq 'text/plain') {
281                 $sfn = 'a.txt';
282         } else {
283                 $sfn = 'a.bin';
284         }
285         my @ret = qq($nl<a\nhref="$upfx$idx-$sfn">[-- Attachment #$idx: );
286         my $ts = "Type: $ct, Size: $size bytes";
287         push(@ret, ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]");
288         join('', @ret, "</a>\n");
289 }
290
291 sub add_text_body {
292         my ($upfx, $p) = @_; # from msg_iter: [ Email::MIME, depth, @idx ]
293         my ($part, $depth, @idx) = @$p;
294         my $ct = $part->content_type;
295         my $fn = $part->filename;
296
297         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
298                 return attach_link($upfx, $ct, $p, $fn);
299         }
300
301         my $s = eval { $part->body_str };
302
303         # badly-encoded message? tell the world about it!
304         return attach_link($upfx, $ct, $p, $fn) if $@;
305
306         my @lines = split(/^/m, $s);
307         $s = '';
308         if (defined($fn) || $depth > 0) {
309                 $s .= attach_link($upfx, $ct, $p, $fn);
310                 $s .= "\n";
311         }
312         my @quot;
313         my $l = PublicInbox::Linkify->new;
314         while (defined(my $cur = shift @lines)) {
315                 if ($cur !~ /^>/) {
316                         # show the previously buffered quote inline
317                         flush_quote(\$s, $l, \@quot) if @quot;
318
319                         # regular line, OK
320                         $cur = $l->linkify_1($cur);
321                         $cur = ascii_html($cur);
322                         $s .= $l->linkify_2($cur);
323                 } else {
324                         push @quot, $cur;
325                 }
326         }
327
328         my $end = "\n";
329         if (@quot) {
330                 $end = '';
331                 flush_quote(\$s, $l, \@quot);
332         }
333         $s =~ s/[ \t]+$//sgm; # kill per-line trailing whitespace
334         $s =~ s/\A\n+//s; # kill leading blank lines
335         $s =~ s/\s+\z//s; # kill all trailing spaces
336         $s .= $end;
337 }
338
339 sub _msg_html_prepare {
340         my ($hdr, $ctx) = @_;
341         my $srch = $ctx->{srch} if $ctx;
342         my $atom = '';
343         my $rv = "<pre\nid=b>"; # anchor for body start
344
345         if ($srch) {
346                 $ctx->{-upfx} = '../';
347         }
348         my @title;
349         my $mid = $hdr->header_raw('Message-ID');
350         $mid = PublicInbox::Hval->new_msgid($mid);
351         foreach my $h (qw(From To Cc Subject Date)) {
352                 my $v = $hdr->header($h);
353                 defined($v) && ($v ne '') or next;
354                 $v = PublicInbox::Hval->new($v);
355
356                 if ($h eq 'From') {
357                         my $n = PublicInbox::Address::from_name($v->raw);
358                         $title[1] = ascii_html($n);
359                 } elsif ($h eq 'Subject') {
360                         $title[0] = $v->as_html;
361                         if ($srch) {
362                                 $rv .= qq($h: <a\nhref="#r"\nid=t>);
363                                 $rv .= $v->as_html . "</a>\n";
364                                 next;
365                         }
366                 }
367                 $v = $v->as_html;
368                 $v =~ s/(\@[^,]+,) /$1\n\t/g if ($h eq 'Cc' || $h eq 'To');
369                 $rv .= "$h: $v\n";
370
371         }
372         $title[0] ||= '(no subject)';
373         $ctx->{-title_html} = join(' - ', @title);
374         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
375         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
376         $rv .= _parent_headers($hdr, $srch);
377         $rv .= "\n";
378 }
379
380 sub thread_skel {
381         my ($dst, $ctx, $hdr, $tpfx) = @_;
382         my $srch = $ctx->{srch};
383         my $mid = mid_clean($hdr->header_raw('Message-ID'));
384         my $sres = $srch->get_thread($mid);
385         my $nr = $sres->{total};
386         my $expand = qq(<a\nhref="${tpfx}t/#u">expand</a> ) .
387                         qq(/ <a\nhref="${tpfx}t.mbox.gz">mbox.gz</a> ) .
388                         qq(/ <a\nhref="${tpfx}t.atom">Atom feed</a>);
389
390         my $parent = in_reply_to($hdr);
391         if ($nr <= 1) {
392                 if (defined $parent) {
393                         $$dst .= "($expand)\n ";
394                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
395                 } else {
396                         $$dst .= "[no followups, yet] ($expand)\n";
397                 }
398                 $ctx->{next_msg} = undef;
399                 $ctx->{parent_msg} = $parent;
400                 return;
401         }
402
403         $$dst .= "$nr+ messages in thread ($expand";
404         $$dst .= qq! / <a\nhref="#b">[top]</a>)\n!;
405
406         my $subj = $srch->subject_path($hdr->header('Subject'));
407         my $state = {
408                 seen => { $subj => 1 },
409                 srch => $srch,
410                 cur => $mid,
411                 prev_attr => '',
412                 prev_level => 0,
413                 upfx => "$tpfx../",
414                 dst => $dst,
415         };
416         walk_thread(thread_results(load_results($sres)), $state, *skel_dump);
417         $ctx->{next_msg} = $state->{next_msg};
418         $ctx->{parent_msg} = $parent;
419 }
420
421 sub _parent_headers {
422         my ($hdr, $srch) = @_;
423         my $rv = '';
424
425         my $irt = in_reply_to($hdr);
426         if (defined $irt) {
427                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
428                 my $html = $v->as_html;
429                 my $href = $v->as_href;
430                 $rv .= "In-Reply-To: &lt;";
431                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
432         }
433
434         # do not display References: if search is present,
435         # we show the thread skeleton at the bottom, instead.
436         return $rv if $srch;
437
438         my $refs = $hdr->header_raw('References');
439         if ($refs) {
440                 # avoid redundant URLs wasting bandwidth
441                 my %seen;
442                 $seen{$irt} = 1 if defined $irt;
443                 my @refs;
444                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
445                 foreach my $ref (@raw_refs) {
446                         next if $seen{$ref};
447                         $seen{$ref} = 1;
448                         push @refs, linkify_ref_nosrch($ref);
449                 }
450
451                 if (@refs) {
452                         $rv .= 'References: '. join("\n\t", @refs) . "\n";
453                 }
454         }
455         $rv;
456 }
457
458 sub mailto_arg_link {
459         my ($hdr) = @_;
460         my %cc; # everyone else
461         my $to; # this is the From address
462
463         foreach my $h (qw(From To Cc)) {
464                 my $v = $hdr->header($h);
465                 defined($v) && ($v ne '') or next;
466                 my @addrs = PublicInbox::Address::emails($v);
467                 foreach my $address (@addrs) {
468                         my $dst = lc($address);
469                         $cc{$dst} ||= $address;
470                         $to ||= $dst;
471                 }
472         }
473         my @arg;
474
475         my $subj = $hdr->header('Subject') || '';
476         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
477         my $mid = $hdr->header_raw('Message-ID');
478         push @arg, "--in-reply-to='" . ascii_html($mid) . "'";
479         my $irt = uri_escape_utf8($mid);
480         delete $cc{$to};
481         push @arg, '--to=' . ascii_html($to);
482         $to = uri_escape_utf8($to);
483         $subj = uri_escape_utf8($subj);
484         my $cc = join(',', sort values %cc);
485         push @arg, '--cc=' . ascii_html($cc);
486         $cc = uri_escape_utf8($cc);
487         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
488         $href =~ s/%20/+/g;
489
490         (\@arg, $href);
491 }
492
493 sub html_footer {
494         my ($hdr, $standalone, $ctx, $rhref) = @_;
495
496         my $srch = $ctx->{srch} if $ctx;
497         my $upfx = '../';
498         my $tpfx = '';
499         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
500         my $irt = '';
501         if ($idx && $srch) {
502                 $idx .= "\n";
503                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
504                 my $p = $ctx->{parent_msg};
505                 my $next = $ctx->{next_msg};
506                 if ($p) {
507                         $p = PublicInbox::Hval->new_msgid($p);
508                         $p = $p->as_href;
509                         $irt = "<a\nhref=\"$upfx$p/\"rel=prev>parent</a> ";
510                 } else {
511                         $irt = ' ' x length('parent ');
512                 }
513                 if ($next) {
514                         my $n = PublicInbox::Hval->new_msgid($next)->as_href;
515                         $irt .= "<a\nhref=\"$upfx$n/\"\nrel=next>next</a> ";
516                 } else {
517                         $irt .= ' ' x length('next ');
518                 }
519         } else {
520                 $irt = '';
521         }
522         $rhref ||= '#R';
523         $irt .= qq(<a\nhref="$rhref">reply</a>);
524         $irt .= $idx;
525 }
526
527 sub linkify_ref_nosrch {
528         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
529         my $html = $v->as_html;
530         my $href = $v->as_href;
531         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
532 }
533
534 sub anchor_for {
535         my ($msgid) = @_;
536         my $id = $msgid;
537         if ($id !~ /\A[a-f0-9]{40}\z/) {
538                 $id = id_compress(mid_clean($id), 1);
539         }
540         'm' . $id;
541 }
542
543 sub thread_html_head {
544         my ($hdr, $state) = @_;
545         my $res = delete $state->{res} or die "BUG: no Plack callback in {res}";
546         my $fh = $res->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
547         $state->{fh} = $fh;
548
549         my $s = ascii_html($hdr->header('Subject'));
550         $fh->write("<html><head><title>$s</title>".
551                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
552                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
553                 PublicInbox::Hval::STYLE .
554                 "</head><body>");
555 }
556
557 sub pre_anchor_entry {
558         my ($seen, $mime) = @_;
559         my $id = anchor_for(mid_mime($mime));
560         $seen->{$id} = "#$id"; # save the anchor for children, later
561 }
562
563 sub ghost_parent {
564         my ($upfx, $mid) = @_;
565         # 'subject dummy' is used internally by Mail::Thread
566         return '[no common parent]' if ($mid eq 'subject dummy');
567
568         $mid = PublicInbox::Hval->new_msgid($mid);
569         my $href = $mid->as_href;
570         my $html = $mid->as_html;
571         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
572 }
573
574 sub thread_adj_level {
575         my ($state, $level) = @_;
576
577         my $max = $state->{cur_level};
578         if ($level <= 0) {
579                 return '' if $max == 0; # flat output
580
581                 # reset existing lists
582                 my $x = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
583                 $state->{fh}->write($x . '</ul>');
584                 $state->{cur_level} = 0;
585                 return '';
586         }
587         if ($level == $max) { # continue existing list
588                 $state->{fh}->write('<li>');
589         } elsif ($level < $max) {
590                 my $x = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
591                 $state->{fh}->write($x .= '<li>');
592                 $state->{cur_level} = $level;
593         } else { # ($level > $max) # start a new level
594                 $state->{cur_level} = $level;
595                 $state->{fh}->write(($max ? '<li>' : '') . '<ul><li>');
596         }
597         '</li>';
598 }
599
600 sub ghost_flush {
601         my ($state, $upfx, $mid, $level) = @_;
602         my $end = '<pre>'. ghost_parent($upfx, $mid) . '</pre>';
603         $state->{fh}->write($end .= thread_adj_level($state, $level));
604 }
605
606 sub __thread_entry {
607         my ($state, $mime, $level) = @_;
608
609         # lazy load the full message from mini_mime:
610         $mime = eval {
611                 my $mid = mid_clean(mid_mime($mime));
612                 $state->{ctx}->{-inbox}->msg_by_mid($mid);
613         } or return;
614         $mime = Email::MIME->new($mime);
615
616         thread_html_head($mime, $state) if $state->{anchor_idx} == 0;
617         if (my $ghost = delete $state->{ghost}) {
618                 # n.b. ghost messages may only be parents, not children
619                 foreach my $g (@$ghost) {
620                         ghost_flush($state, '../../', @$g);
621                 }
622         }
623         my $end = thread_adj_level($state, $level);
624         index_entry($mime, $level, $state);
625         $state->{fh}->write($end) if $end;
626
627         1;
628 }
629
630 sub indent_for {
631         my ($level) = @_;
632         INDENT x ($level - 1);
633 }
634
635 sub __ghost_prepare {
636         my ($state, $node, $level) = @_;
637         my $ghost = $state->{ghost} ||= [];
638         push @$ghost, [ $node->messageid, $level ];
639 }
640
641 sub thread_entry {
642         my ($state, $level, $node) = @_;
643         if (my $mime = $node->message) {
644                 unless (__thread_entry($state, $mime, $level)) {
645                         __ghost_prepare($state, $node, $level);
646                 }
647         } else {
648                 __ghost_prepare($state, $node, $level);
649         }
650 }
651
652 sub load_results {
653         my ($sres) = @_;
654
655         [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
656 }
657
658 sub msg_timestamp {
659         my ($hdr) = @_;
660         my $ts = eval { str2time($hdr->header('Date')) };
661         defined($ts) ? $ts : 0;
662 }
663
664 sub thread_results {
665         my ($msgs) = @_;
666         require PublicInbox::Thread;
667         my $th = PublicInbox::Thread->new(@$msgs);
668         $th->thread;
669         $th->order(*sort_ts);
670         $th
671 }
672
673 sub missing_thread {
674         my ($res, $ctx) = @_;
675         require PublicInbox::ExtMsg;
676
677         $res->(PublicInbox::ExtMsg::ext_msg($ctx))
678 }
679
680 sub _msg_date {
681         my ($hdr) = @_;
682         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
683         fmt_ts($ts);
684 }
685
686 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
687
688 sub _skel_header {
689         my ($state, $hdr, $level) = @_;
690
691         my $dst = $state->{dst};
692         my $cur = $state->{cur};
693         my $mid = mid_clean($hdr->header_raw('Message-ID'));
694         my $f = ascii_html($hdr->header('X-PI-From'));
695         my $d = _msg_date($hdr);
696         my $pfx = "$d " . indent_for($level) . th_pfx($level);
697         my $attr = $f;
698         $state->{first_level} ||= $level;
699
700         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
701                 $state->{prev_attr} = $attr;
702         } else {
703                 $attr = '';
704         }
705         $state->{prev_level} = $level;
706
707         if ($cur) {
708                 if ($cur eq $mid) {
709                         delete $state->{cur};
710                         $$dst .= "$pfx<b><a\nid=r\nhref=\"#t\">".
711                                  "$attr [this message]</a></b>\n";
712
713                         return;
714                 }
715         } else {
716                 $state->{next_msg} ||= $mid;
717         }
718
719         # Subject is never undef, this mail was loaded from
720         # our Xapian which would've resulted in '' if it were
721         # really missing (and Filter rejects empty subjects)
722         my $s = $hdr->header('Subject');
723         my $h = $state->{srch}->subject_path($s);
724         if ($state->{seen}->{$h}) {
725                 $s = undef;
726         } else {
727                 $state->{seen}->{$h} = 1;
728                 $s = PublicInbox::Hval->new($s);
729                 $s = $s->as_html;
730         }
731         my $m = PublicInbox::Hval->new_msgid($mid);
732         $m = $state->{upfx} . $m->as_href . '/';
733         $$dst .= "$pfx<a\nhref=\"$m\">";
734         $$dst .= defined($s) ? "$s</a> $f\n" : "$f</a>\n";
735 }
736
737 sub skel_dump {
738         my ($state, $level, $node) = @_;
739         if (my $mime = $node->message) {
740                 my $hdr = $mime->header_obj;
741                 my $mid = mid_clean($hdr->header_raw('Message-ID'));
742                 _skel_header($state, $hdr, $level);
743         } else {
744                 my $mid = $node->messageid;
745                 my $dst = $state->{dst};
746                 if ($mid eq 'subject dummy') {
747                         $$dst .= "\t[no common parent]\n";
748                 } else {
749                         $$dst .= '     [not found] ';
750                         $$dst .= indent_for($level) . th_pfx($level);
751                         $mid = PublicInbox::Hval->new_msgid($mid);
752                         my $href = $state->{upfx} . $mid->as_href . '/';
753                         my $html = $mid->as_html;
754                         $$dst .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
755                 }
756         }
757 }
758
759 sub sort_ts {
760         sort {
761                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
762                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
763         } @_;
764 }
765
766 sub _tryload_ghost ($$) {
767         my ($srch, $mid) = @_;
768         my $smsg = $srch->lookup_mail($mid) or return;
769         $smsg->mini_mime;
770 }
771
772 # accumulate recent topics if search is supported
773 # returns 1 if done, undef if not
774 sub add_topic {
775         my ($state, $level, $node) = @_;
776         my $srch = $state->{srch};
777         my $mid = $node->messageid;
778         my $x = $node->message || _tryload_ghost($srch, $mid);
779         my ($subj, $ts);
780         if ($x) {
781                 $x = $x->header_obj;
782                 $subj = $x->header('Subject');
783                 $subj = $srch->subject_normalized($subj);
784                 $ts = $x->header('X-PI-TS');
785         } else { # ghost message, do not bump level
786                 $ts = -666;
787                 $subj = "<$mid>";
788         }
789         if (++$state->{subjs}->{$subj} == 1) {
790                 push @{$state->{order}}, [ $level, $subj ];
791         }
792         my $exist = $state->{latest}->{$subj};
793         if (!$exist || $exist->[1] < $ts) {
794                 $state->{latest}->{$subj} = [ $mid, $ts ];
795         }
796 }
797
798 sub emit_topics {
799         my ($state) = @_;
800         my $order = $state->{order};
801         my $subjs = $state->{subjs};
802         my $latest = $state->{latest};
803         my $fh = $state->{fh};
804         return $fh->write("\n[No topics in range]</pre>") unless scalar @$order;
805         my $pfx;
806         my $prev = 0;
807         my $prev_attr = '';
808         my $cur;
809         my @recent;
810         while (defined(my $info = shift @$order)) {
811                 my ($level, $subj) = @$info;
812                 my $n = delete $subjs->{$subj};
813                 my ($mid, $ts) = @{delete $latest->{$subj}};
814                 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
815                 $pfx = indent_for($level);
816                 my $nl = $level == $prev ? "\n" : '';
817                 if ($nl && $cur) {
818                         push @recent, $cur;
819                         $cur = undef;
820                 }
821                 $cur ||= [ $ts, '' ];
822                 $cur->[0] = $ts if $ts > $cur->[0];
823                 $cur->[1] .= $nl . $pfx . th_pfx($level);
824                 if ($ts == -666) { # ghost
825                         $cur->[1] .= ghost_parent('', $mid) . "\n";
826                         next; # child will have mbox / atom link
827                 }
828
829                 $subj = PublicInbox::Hval->new($subj)->as_html;
830                 $cur->[1] .= "<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
831                 $ts = fmt_ts($ts);
832                 my $attr = " $ts UTC";
833
834                 # $n isn't the total number of posts on the topic,
835                 # just the number of posts in the current results window
836                 $n = $n == 1 ? '' : " ($n+ messages)";
837
838                 if ($level == 0 || $attr ne $prev_attr) {
839                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
840                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
841                         $pfx .= INDENT if $level > 0;
842                         $cur->[1] .= $pfx . $attr . $n . " - $mbox / $atom\n";
843                         $prev_attr = $attr;
844                 }
845         }
846         push @recent, $cur if $cur;
847         @recent = map { $_->[1] } sort { $b->[0] <=> $a->[0] } @recent;
848         $fh->write(join('', @recent) . '</pre>');
849 }
850
851 sub emit_index_topics {
852         my ($state) = @_;
853         my ($off) = (($state->{ctx}->{cgi}->param('o') || '0') =~ /(\d+)/);
854         $state->{order} = [];
855         $state->{subjs} = {};
856         $state->{latest} = {};
857         my $max = 25;
858         my %opts = ( offset => $off, limit => $max * 4 );
859         while (scalar @{$state->{order}} < $max) {
860                 my $sres = $state->{srch}->query('', \%opts);
861                 my $nr = scalar @{$sres->{msgs}} or last;
862                 $sres = load_results($sres);
863                 walk_thread(thread_results($sres), $state, *add_topic);
864                 $opts{offset} += $nr;
865         }
866
867         emit_topics($state);
868         $opts{offset};
869 }
870
871 1;