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