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