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