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