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