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