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