]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
534f85ef9b8110ca86e992d18118be2499786309
[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 mid2path mid_mime/;
16 use PublicInbox::MsgIter;
17 use PublicInbox::Address;
18 require POSIX;
19
20 use constant INDENT => '  ';
21 use constant TCHILD => '` ';
22 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
23
24 # public functions: (unstable)
25 # TODO: stream this, since threading is expensive but also oh-so-important
26 sub msg_html {
27         my ($ctx, $mime, $footer) = @_;
28         $footer = defined($footer) ? "\n$footer" : '';
29         my $hdr = $mime->header_obj;
30         my $n = 0;
31         Plack::Util::inline_object(
32                 close => sub {}, # noop
33                 getline => sub {
34                         my $nr = $n++;
35                         if ($nr == 0) {
36                                 headers_to_html_header($hdr, $ctx) .
37                                         multipart_text_as_html($mime, '') .
38                                         '</pre><hr />'
39                         } elsif ($nr == 1) {
40                                 '<pre>' .
41                                         html_footer($hdr, 1, $ctx) .
42                                         '</pre>' . msg_reply($ctx, $hdr) .
43                                         '<hr /><pre>'.  $footer .
44                                         '</pre></body></html>'
45                         } else {
46                                 undef
47                         }
48                 }
49         )
50 }
51
52 # /$INBOX/$MESSAGE_ID/#R
53 sub msg_reply {
54         my ($ctx, $hdr) = @_;
55         my $se_url =
56          'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
57
58         my ($arg, $link) = mailto_arg_link($hdr);
59         push @$arg, '/path/to/YOUR_REPLY';
60
61         "<hr /><pre\nid=R>".
62         "You may reply publically to <a\nhref=#t>this message</a> via\n".
63         "plain-text email using any one of the following methods:\n\n" .
64         "* Save the following mbox file, import it into your mail client,\n" .
65         "  and reply-to-all from there: <a\nhref=raw>mbox</a>\n\n" .
66         "* Reply to all the recipients using the <b>--to</b>, <b>--cc</b>,\n" .
67         "  and <b>--in-reply-to</b> switches of git-send-email(1):\n\n" .
68         "\tgit send-email \\\n\t\t" .
69         join(" \\\n\t\t", @$arg ). "\n\n" .
70         qq(  <a\nhref="$se_url">$se_url</a>\n\n) .
71         "* If your mail client supports setting the <b>In-Reply-To</b>" .
72         " header\n  via mailto: links, try the " .
73         qq(<a\nhref="$link">mailto: link</a>\n) .
74         '</pre>';
75 }
76
77 sub in_reply_to {
78         my ($hdr) = @_;
79         my $irt = $hdr->header_raw('In-Reply-To');
80
81         return mid_clean($irt) if (defined $irt);
82
83         my $refs = $hdr->header_raw('References');
84         if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
85                 return $1;
86         }
87         undef;
88 }
89
90 # this is already inside a <pre>
91 sub index_entry {
92         my ($mime, $level, $state) = @_;
93         my $midx = $state->{anchor_idx}++;
94         my $ctx = $state->{ctx};
95         my $srch = $ctx->{srch};
96         my $hdr = $mime->header_obj;
97         my $subj = $hdr->header('Subject');
98
99         my $mid_raw = mid_clean(mid_mime($mime));
100         my $id = anchor_for($mid_raw);
101         my $seen = $state->{seen};
102         $seen->{$id} = "#$id"; # save the anchor for children, later
103
104         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
105         my $from = PublicInbox::Address::from_name($hdr->header('From'));
106
107         my $root_anchor = $state->{root_anchor} || '';
108         my $path = $root_anchor ? '../../' : '';
109         my $href = $mid->as_href;
110         my $irt = in_reply_to($hdr);
111         my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
112
113         $from = ascii_html($from);
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         $fh->write($rv .= "- $from @ $ts UTC (<a\nhref=\"$txt\">raw</a>)\n\n");
124
125         my $mhref = "${path}$href/";
126
127         # scan through all parts, looking for displayable text
128         msg_iter($mime, sub { index_walk($fh, $mhref, $_[0]) });
129         $rv = "\n" . html_footer($hdr, 0, $ctx, "$path$href/#R");
130
131         if (defined $irt) {
132                 unless (defined $parent_anchor) {
133                         my $v = PublicInbox::Hval->new_msgid($irt, 1);
134                         $v = $v->as_href;
135                         $parent_anchor = "${path}$v/";
136                 }
137                 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
138         }
139         if (my $pct = $state->{pct}) { # used by SearchView.pm
140                 $rv .= " [relevance $pct->{$mid_raw}%]";
141         } elsif ($srch) {
142                 my $threaded = 'threaded';
143                 my $flat = 'flat';
144                 my $end = '';
145                 if ($ctx->{flat}) {
146                         $flat = "<b>$flat</b>";
147                         $end = "\n"; # for lynx
148                 } else {
149                         $threaded = "<b>$threaded</b>";
150                 }
151                 $rv .= " [<a\nhref=\"${path}$href/t/#u\">$threaded</a>";
152                 $rv .= "|<a\nhref=\"${path}$href/T/#u\">$flat</a>]$end";
153         }
154         $fh->write($rv .= '</pre>');
155 }
156
157 sub thread_html {
158         my ($ctx, $foot, $srch) = @_;
159         # $_[0] in sub is the Plack callback
160         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
161 }
162
163 # only private functions below.
164
165 sub emit_thread_html {
166         my ($res, $ctx, $foot, $srch) = @_;
167         my $mid = $ctx->{mid};
168         my $flat = $ctx->{flat};
169         my $msgs = load_results($srch->get_thread($mid, { asc => $flat }));
170         my $nr = scalar @$msgs;
171         return missing_thread($res, $ctx) if $nr == 0;
172         my $seen = {};
173         my $state = {
174                 res => $res,
175                 ctx => $ctx,
176                 seen => $seen,
177                 root_anchor => anchor_for($mid),
178                 anchor_idx => 0,
179                 cur_level => 0,
180         };
181
182         require PublicInbox::Git;
183         $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
184         if ($flat) {
185                 pre_anchor_entry($seen, $_) for (@$msgs);
186                 __thread_entry($state, $_, 0) for (@$msgs);
187         } else {
188                 my $th = thread_results($msgs);
189                 thread_entry($state, $_, 0) for $th->rootset;
190                 if (my $max = $state->{cur_level}) {
191                         $state->{fh}->write(
192                                 ('</ul></li>' x ($max - 1)) . '</ul>');
193                 }
194         }
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 $n = PublicInbox::Address::from_name($v->raw);
343                         $title[1] = ascii_html($n);
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 = PublicInbox::Address::emails($v);
453                 foreach my $address (@addrs) {
454                         my $dst = lc($address);
455                         $cc{$dst} ||= $address;
456                         $to ||= $dst;
457                 }
458         }
459         my @arg;
460
461         my $subj = $hdr->header('Subject') || '';
462         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
463         my $mid = $hdr->header_raw('Message-ID');
464         push @arg, "--in-reply-to='" . ascii_html($mid) . "'";
465         my $irt = uri_escape_utf8($mid);
466         delete $cc{$to};
467         push @arg, '--to=' . ascii_html($to);
468         $to = uri_escape_utf8($to);
469         $subj = uri_escape_utf8($subj);
470         my $cc = join(',', sort values %cc);
471         push @arg, '--cc=' . ascii_html($cc);
472         $cc = uri_escape_utf8($cc);
473         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
474         $href =~ s/%20/+/g;
475
476         (\@arg, $href);
477 }
478
479 sub html_footer {
480         my ($hdr, $standalone, $ctx, $rhref) = @_;
481
482         my $srch = $ctx->{srch} if $ctx;
483         my $upfx = '../';
484         my $tpfx = '';
485         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
486         my $irt = '';
487         if ($idx && $srch) {
488                 $idx .= "\n";
489                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
490                 my $p = $ctx->{parent_msg};
491                 my $next = $ctx->{next_msg};
492                 if ($p) {
493                         $p = PublicInbox::Hval->new_msgid($p);
494                         $p = $p->as_href;
495                         $irt = "<a\nhref=\"$upfx$p/\"rel=prev>parent</a> ";
496                 } else {
497                         $irt = ' ' x length('parent ');
498                 }
499                 if ($next) {
500                         my $n = PublicInbox::Hval->new_msgid($next)->as_href;
501                         $irt .= "<a\nhref=\"$upfx$n/\"\nrel=next>next</a> ";
502                 } else {
503                         $irt .= ' ' x length('next ');
504                 }
505         } else {
506                 $irt = '';
507         }
508         $rhref ||= '#R';
509         $irt .= qq(<a\nhref="$rhref">reply</a>);
510         $irt .= $idx;
511 }
512
513 sub linkify_ref_nosrch {
514         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
515         my $html = $v->as_html;
516         my $href = $v->as_href;
517         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
518 }
519
520 sub anchor_for {
521         my ($msgid) = @_;
522         my $id = $msgid;
523         if ($id !~ /\A[a-f0-9]{40}\z/) {
524                 $id = id_compress(mid_clean($id), 1);
525         }
526         'm' . $id;
527 }
528
529 sub thread_html_head {
530         my ($hdr, $state) = @_;
531         my $res = delete $state->{res} or die "BUG: no Plack callback in {res}";
532         my $fh = $res->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
533         $state->{fh} = $fh;
534
535         my $s = ascii_html($hdr->header('Subject'));
536         $fh->write("<html><head><title>$s</title>".
537                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
538                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
539                 PublicInbox::Hval::STYLE .
540                 "</head><body>");
541 }
542
543 sub pre_anchor_entry {
544         my ($seen, $mime) = @_;
545         my $id = anchor_for(mid_mime($mime));
546         $seen->{$id} = "#$id"; # save the anchor for children, later
547 }
548
549 sub ghost_parent {
550         my ($upfx, $mid) = @_;
551         # 'subject dummy' is used internally by Mail::Thread
552         return '[no common parent]' if ($mid eq 'subject dummy');
553
554         $mid = PublicInbox::Hval->new_msgid($mid);
555         my $href = $mid->as_href;
556         my $html = $mid->as_html;
557         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
558 }
559
560 sub thread_adj_level {
561         my ($state, $level) = @_;
562
563         my $max = $state->{cur_level};
564         if ($level <= 0) {
565                 return '' if $max == 0; # flat output
566
567                 # reset existing lists
568                 my $x = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
569                 $state->{fh}->write($x . '</ul>');
570                 $state->{cur_level} = 0;
571                 return '';
572         }
573         if ($level == $max) { # continue existing list
574                 $state->{fh}->write('<li>');
575         } elsif ($level < $max) {
576                 my $x = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
577                 $state->{fh}->write($x .= '<li>');
578                 $state->{cur_level} = $level;
579         } else { # ($level > $max) # start a new level
580                 $state->{cur_level} = $level;
581                 $state->{fh}->write(($max ? '<li>' : '') . '<ul><li>');
582         }
583         '</li>';
584 }
585
586 sub ghost_flush {
587         my ($state, $upfx, $mid, $level) = @_;
588         my $end = '<pre>'. ghost_parent($upfx, $mid) . '</pre>';
589         $state->{fh}->write($end .= thread_adj_level($state, $level));
590 }
591
592 sub __thread_entry {
593         my ($state, $mime, $level) = @_;
594
595         # lazy load the full message from mini_mime:
596         $mime = eval {
597                 my $path = mid2path(mid_clean(mid_mime($mime)));
598                 Email::MIME->new($state->{ctx}->{git}->cat_file('HEAD:'.$path));
599         } or return;
600
601         thread_html_head($mime, $state) if $state->{anchor_idx} == 0;
602         if (my $ghost = delete $state->{ghost}) {
603                 # n.b. ghost messages may only be parents, not children
604                 foreach my $g (@$ghost) {
605                         ghost_flush($state, '../../', @$g);
606                 }
607         }
608         my $end = thread_adj_level($state, $level);
609         index_entry($mime, $level, $state);
610         $state->{fh}->write($end) if $end;
611
612         1;
613 }
614
615 sub indent_for {
616         my ($level) = @_;
617         INDENT x ($level - 1);
618 }
619
620 sub __ghost_prepare {
621         my ($state, $node, $level) = @_;
622         my $ghost = $state->{ghost} ||= [];
623         push @$ghost, [ $node->messageid, $level ];
624 }
625
626 sub thread_entry {
627         my ($state, $node, $level) = @_;
628         return unless $node;
629         if (my $mime = $node->message) {
630                 unless (__thread_entry($state, $mime, $level)) {
631                         __ghost_prepare($state, $node, $level);
632                 }
633         } else {
634                 __ghost_prepare($state, $node, $level);
635         }
636
637         thread_entry($state, $node->child, $level + 1);
638         thread_entry($state, $node->next, $level);
639 }
640
641 sub load_results {
642         my ($sres) = @_;
643
644         [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
645 }
646
647 sub msg_timestamp {
648         my ($hdr) = @_;
649         my $ts = eval { str2time($hdr->header('Date')) };
650         defined($ts) ? $ts : 0;
651 }
652
653 sub thread_results {
654         my ($msgs) = @_;
655         require PublicInbox::Thread;
656         my $th = PublicInbox::Thread->new(@$msgs);
657         $th->thread;
658         $th->order(*sort_ts);
659         $th
660 }
661
662 sub missing_thread {
663         my ($res, $ctx) = @_;
664         require PublicInbox::ExtMsg;
665
666         $res->(PublicInbox::ExtMsg::ext_msg($ctx))
667 }
668
669 sub _msg_date {
670         my ($hdr) = @_;
671         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
672         fmt_ts($ts);
673 }
674
675 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
676
677 sub _skel_header {
678         my ($dst, $state, $upfx, $hdr, $level) = @_;
679
680         my $cur = $state->{cur};
681         my $mid = mid_clean($hdr->header_raw('Message-ID'));
682         my $f = ascii_html($hdr->header('X-PI-From'));
683         my $d = _msg_date($hdr);
684         my $pfx = "$d " . indent_for($level) . th_pfx($level);
685         my $attr = $f;
686         $state->{first_level} ||= $level;
687
688         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
689                 $state->{prev_attr} = $attr;
690         } else {
691                 $attr = '';
692         }
693         $state->{prev_level} = $level;
694
695         if ($cur) {
696                 if ($cur eq $mid) {
697                         delete $state->{cur};
698                         $$dst .= "$pfx<b><a\nid=r\nhref=\"#t\">".
699                                  "$attr [this message]</a></b>\n";
700
701                         return;
702                 }
703         } else {
704                 $state->{next_msg} ||= $mid;
705         }
706
707         # Subject is never undef, this mail was loaded from
708         # our Xapian which would've resulted in '' if it were
709         # really missing (and Filter rejects empty subjects)
710         my $s = $hdr->header('Subject');
711         my $h = $state->{srch}->subject_path($s);
712         if ($state->{seen}->{$h}) {
713                 $s = undef;
714         } else {
715                 $state->{seen}->{$h} = 1;
716                 $s = PublicInbox::Hval->new($s);
717                 $s = $s->as_html;
718         }
719         my $m = PublicInbox::Hval->new_msgid($mid);
720         $m = $upfx . '../' . $m->as_href . '/';
721         $$dst .= "$pfx<a\nhref=\"$m\">";
722         $$dst .= defined($s) ? "$s</a> $f\n" : "$f</a>\n";
723 }
724
725 sub skel_dump {
726         my ($dst, $state, $upfx, $node, $level) = @_;
727         return unless $node;
728         if (my $mime = $node->message) {
729                 my $hdr = $mime->header_obj;
730                 my $mid = mid_clean($hdr->header_raw('Message-ID'));
731                 _skel_header($dst, $state, $upfx, $hdr, $level);
732         } else {
733                 my $mid = $node->messageid;
734                 if ($mid eq 'subject dummy') {
735                         $$dst .= "\t[no common parent]\n";
736                 } else {
737                         $$dst .= '     [not found] ';
738                         $$dst .= indent_for($level) . th_pfx($level);
739                         $mid = PublicInbox::Hval->new_msgid($mid);
740                         my $href = "$upfx../" . $mid->as_href . '/';
741                         my $html = $mid->as_html;
742                         $$dst .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
743                 }
744         }
745         skel_dump($dst, $state, $upfx, $node->child, $level+1);
746         skel_dump($dst, $state, $upfx, $node->next, $level);
747 }
748
749 sub sort_ts {
750         sort {
751                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
752                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
753         } @_;
754 }
755
756 # accumulate recent topics if search is supported
757 # returns 1 if done, undef if not
758 sub add_topic {
759         my ($state, $node, $level) = @_;
760         return unless $node;
761         my $child_adjust = 1;
762
763         if (my $x = $node->message) {
764                 $x = $x->header_obj;
765                 my $subj;
766
767                 $subj = $x->header('Subject');
768                 $subj = $state->{srch}->subject_normalized($subj);
769
770                 if (++$state->{subjs}->{$subj} == 1) {
771                         push @{$state->{order}}, [ $level, $subj ];
772                 }
773
774                 my $mid = mid_clean($x->header_raw('Message-ID'));
775
776                 my $ts = $x->header('X-PI-TS');
777                 my $exist = $state->{latest}->{$subj};
778                 if (!$exist || $exist->[1] < $ts) {
779                         $state->{latest}->{$subj} = [ $mid, $ts ];
780                 }
781         } else {
782                 # ghost message, do not bump level
783                 $child_adjust = 0;
784         }
785
786         add_topic($state, $node->child, $level + $child_adjust);
787         add_topic($state, $node->next, $level);
788 }
789
790 sub emit_topics {
791         my ($state) = @_;
792         my $order = $state->{order};
793         my $subjs = $state->{subjs};
794         my $latest = $state->{latest};
795         my $fh = $state->{fh};
796         return $fh->write("\n[No topics in range]</pre>") unless scalar @$order;
797         my $pfx;
798         my $prev = 0;
799         my $prev_attr = '';
800         my $cur;
801         my @recent;
802         while (defined(my $info = shift @$order)) {
803                 my ($level, $subj) = @$info;
804                 my $n = delete $subjs->{$subj};
805                 my ($mid, $ts) = @{delete $latest->{$subj}};
806                 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
807                 $subj = PublicInbox::Hval->new($subj)->as_html;
808                 $pfx = indent_for($level);
809                 my $nl = $level == $prev ? "\n" : '';
810                 if ($nl && $cur) {
811                         push @recent, $cur;
812                         $cur = undef;
813                 }
814                 $cur ||= [ $ts, '' ];
815                 $cur->[0] = $ts if $ts > $cur->[0];
816                 $cur->[1] .= $nl . $pfx . th_pfx($level) .
817                                 "<a\nhref=\"$mid/t/#u\"><b>" .
818                                 $subj . "</b></a>\n";
819
820                 $ts = fmt_ts($ts);
821                 my $attr = " $ts UTC";
822
823                 # $n isn't the total number of posts on the topic,
824                 # just the number of posts in the current results window
825                 $n = $n == 1 ? '' : " ($n+ messages)";
826
827                 if ($level == 0 || $attr ne $prev_attr) {
828                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
829                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
830                         $pfx .= INDENT if $level > 0;
831                         $cur->[1] .= $pfx . $attr . $n . " - $mbox / $atom\n";
832                         $prev_attr = $attr;
833                 }
834         }
835         push @recent, $cur if $cur;
836         @recent = map { $_->[1] } sort { $b->[0] <=> $a->[0] } @recent;
837         $fh->write(join('', @recent) . '</pre>');
838 }
839
840 sub emit_index_topics {
841         my ($state) = @_;
842         my ($off) = (($state->{ctx}->{cgi}->param('o') || '0') =~ /(\d+)/);
843         $state->{order} = [];
844         $state->{subjs} = {};
845         $state->{latest} = {};
846         my $max = 25;
847         my %opts = ( offset => $off, limit => $max * 4 );
848         while (scalar @{$state->{order}} < $max) {
849                 my $sres = $state->{srch}->query('', \%opts);
850                 my $nr = scalar @{$sres->{msgs}} or last;
851
852                 for (thread_results(load_results($sres))->rootset) {
853                         add_topic($state, $_, 0);
854                 }
855                 $opts{offset} += $nr;
856         }
857
858         emit_topics($state);
859         $opts{offset};
860 }
861
862 1;