]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: fixup indentation nesting in search
[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 qw/find_encoding/;
12 use Encode::MIME::Header;
13 use Email::MIME::ContentType qw/parse_content_type/;
14 use PublicInbox::Hval;
15 use PublicInbox::MID qw/mid_clean id_compress mid2path/;
16 use Digest::SHA qw/sha1_hex/;
17 my $SALT = rand;
18 require POSIX;
19
20 # TODO: make these constants tunable
21 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
22 use constant MAX_TRUNC_LEN => 72;
23 use constant T_ANCHOR => '#u';
24 use constant INDENT => '  ';
25
26 *ascii_html = *PublicInbox::Hval::ascii_html;
27
28 my $enc_utf8 = find_encoding('UTF-8');
29
30 # public functions:
31 sub msg_html {
32         my ($ctx, $mime, $full_pfx, $footer) = @_;
33         if (defined $footer) {
34                 $footer = "\n" . $footer;
35         } else {
36                 $footer = '';
37         }
38         headers_to_html_header($mime, $full_pfx, $ctx) .
39                 multipart_text_as_html($mime, $full_pfx) .
40                 '</pre><hr /><pre>' .
41                 html_footer($mime, 1, $full_pfx, $ctx) .
42                 $footer .
43                 '</pre></body></html>';
44 }
45
46 sub feed_entry {
47         my ($class, $mime, $full_pfx) = @_;
48
49         # no <head> here for <style>...
50         PublicInbox::Hval::PRE .
51                 multipart_text_as_html($mime, $full_pfx) . '</pre>';
52 }
53
54 sub in_reply_to {
55         my ($header_obj) = @_;
56         my $irt = $header_obj->header('In-Reply-To');
57
58         return mid_clean($irt) if (defined $irt);
59
60         my $refs = $header_obj->header('References');
61         if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
62                 return $1;
63         }
64         undef;
65 }
66
67 # this is already inside a <pre>
68 sub index_entry {
69         my ($fh, $mime, $level, $state) = @_;
70         my $midx = $state->{anchor_idx}++;
71         my $ctx = $state->{ctx};
72         my $srch = $ctx->{srch};
73         my ($prev, $next) = ($midx - 1, $midx + 1);
74         my $part_nr = 0;
75         my $enc = enc_for($mime->header("Content-Type"));
76         my $subj = $mime->header('Subject');
77         my $header_obj = $mime->header_obj;
78
79         my $mid_raw = mid_clean($header_obj->header('Message-ID'));
80         my $id = anchor_for($mid_raw);
81         my $seen = $state->{seen};
82         $seen->{$id} = "#$id"; # save the anchor for children, later
83
84         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
85         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
86         my @from = Email::Address->parse($from);
87         $from = $from[0]->name;
88
89         $from = PublicInbox::Hval->new_oneline($from)->as_html;
90         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
91         my $root_anchor = $state->{root_anchor} || '';
92         my $path = $root_anchor ? '../../' : '';
93         my $href = $mid->as_href;
94         my $irt = in_reply_to($header_obj);
95         my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
96
97         if ($srch) {
98                 my $t = $ctx->{flat} ? 'T' : 't';
99                 $subj = "<a\nhref=\"${path}$href/$t/#u\">$subj</a>";
100         }
101         if ($root_anchor eq $id) {
102                 $subj = "<u\nid=u>$subj</u>";
103         }
104
105         my $ts = _msg_date($mime);
106         my $rv = "<pre\nid=s$midx>";
107         $rv .= "<b\nid=$id>$subj</b>\n";
108         $rv .= "- $from @ $ts UTC - ";
109         $rv .= "<a\nhref=\"#s$next\">next</a>";
110         if ($prev >= 0) {
111                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
112         }
113         $fh->write($rv .= "\n\n");
114
115         my ($fhref, $more_ref);
116         my $mhref = "${path}$href/";
117         my $more = 'permalink';
118
119         # show full message if it's our root message
120         my $neq = $root_anchor ne $id;
121         if ($neq || ($neq && $level != 0 && !$ctx->{flat})) {
122                 $fhref = "${path}$href/f/";
123                 $more_ref = \$more;
124         }
125         # scan through all parts, looking for displayable text
126         $mime->walk_parts(sub {
127                 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
128         });
129         $mime->body_set('');
130
131         my $txt = "${path}$href/raw";
132         $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
133         $rv .= html_footer($mime, 0, undef, $ctx);
134
135         if (defined $irt) {
136                 unless (defined $parent_anchor) {
137                         my $v = PublicInbox::Hval->new_msgid($irt, 1);
138                         $v = $v->as_href;
139                         $parent_anchor = "${path}$v/";
140                 }
141                 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
142         }
143         if (my $pct = $state->{pct}) {
144                 $rv .= " [$pct->{$mid_raw}%]";
145         } elsif ($srch) {
146                 if ($ctx->{flat}) {
147                         $rv .= " [<a\nhref=\"${path}$href/t/#u\">threaded</a>" .
148                                 "|<b>flat</b>]";
149                 } else {
150                         $rv .= " [<b>threaded</b>|" .
151                                 "<a\nhref=\"${path}$href/T/#u\">flat</a>]";
152                 }
153         }
154         $fh->write($rv .= '</pre>');
155 }
156
157 sub thread_html {
158         my ($ctx, $foot, $srch) = @_;
159         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
160 }
161
162 # only private functions below.
163
164 sub emit_thread_html {
165         my ($cb, $ctx, $foot, $srch) = @_;
166         my $mid = $ctx->{mid};
167         my $res = $srch->get_thread($mid);
168         my $msgs = load_results($res);
169         my $nr = scalar @$msgs;
170         return missing_thread($cb, $ctx) if $nr == 0;
171         my $flat = $ctx->{flat};
172         my $orig_cb = $cb;
173         my $seen = {};
174         my $state = {
175                 ctx => $ctx,
176                 seen => $seen,
177                 root_anchor => anchor_for($mid),
178                 anchor_idx => 0,
179                 cur_level => 0,
180         };
181
182         require PublicInbox::Git;
183         my $git = $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
184         if ($flat) {
185                 pre_anchor_entry($seen, $_) for (@$msgs);
186                 __thread_entry(\$cb, $git, $state, $_, 0) for (@$msgs);
187         } else {
188                 my $th = thread_results($msgs);
189                 thread_entry(\$cb, $git, $state, $_, 0) for $th->rootset;
190                 if (my $max = $state->{cur_level}) {
191                         $cb->write(('</ul></li>' x ($max - 1)) . '</ul>');
192                 }
193         }
194         $git = undef;
195         Email::Address->purge_cache;
196
197         # there could be a race due to a message being deleted in git
198         # but still being in the Xapian index:
199         return missing_thread($cb, $ctx) if ($orig_cb eq $cb);
200
201         my $final_anchor = $state->{anchor_idx};
202         my $next = "<a\nid=s$final_anchor>";
203         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
204         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
205         $next .= "\ndownload thread: ";
206         $next .= "<a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
207         $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
208         $cb->write('<hr /><pre>' . $next . "\n\n".
209                         $foot .  '</pre></body></html>');
210         $cb->close;
211 }
212
213 sub index_walk {
214         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
215         my $s = add_text_body($enc, $part, $part_nr, $fhref);
216
217         if ($more) {
218                 my $m = 0;
219                 # drop the remainder of git patches, they're usually better
220                 # to review when the full message is viewed
221                 $s =~ s!^---+\n.*\z!!ms and $m = 1;
222
223                 # Drop signatures
224                 $s =~ s/^-- \n.*\z//ms and $m = 1;
225                 $$more = "<b>More...</b>\n\n$$more" if $m;
226         }
227
228         # kill any leading or trailing whitespace lines
229         $s =~ s/^\s*$//sgm;
230         $s =~ s/\s+\z//s;
231
232         if ($s ne '') {
233                 # kill per-line trailing whitespace
234                 $s =~ s/[ \t]+$//sgm;
235                 $s .= "\n" unless $s =~ /\n\z/s;
236         }
237         $fh->write($s);
238 }
239
240 sub enc_for {
241         my ($ct, $default) = @_;
242         $default ||= $enc_utf8;
243         defined $ct or return $default;
244         my $ct_parsed = parse_content_type($ct);
245         if ($ct_parsed) {
246                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
247                         my $enc = find_encoding($charset);
248                         return $enc if $enc;
249                 }
250         }
251         $default;
252 }
253
254 sub multipart_text_as_html {
255         my ($mime, $full_pfx, $srch) = @_;
256         my $rv = "";
257         my $part_nr = 0;
258         my $enc = enc_for($mime->header("Content-Type"));
259
260         # scan through all parts, looking for displayable text
261         $mime->walk_parts(sub {
262                 my ($part) = @_;
263                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx, 1);
264         });
265         $mime->body_set('');
266         $rv;
267 }
268
269 sub add_filename_line {
270         my ($enc, $fn) = @_;
271         my $len = 72;
272         my $pad = "-";
273         $fn = $enc->decode($fn);
274         $len -= length($fn);
275         $pad x= ($len/2) if ($len > 0);
276         "$pad " . ascii_html($fn) . " $pad\n";
277 }
278
279 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
280                  [\@:\w\.-]+/
281                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
282
283 sub linkify_1 {
284         my ($link_map, $s) = @_;
285         $s =~ s!$LINK_RE!
286                 my $url = $1;
287                 # salt this, as this could be exploited to show
288                 # links in the HTML which don't show up in the raw mail.
289                 my $key = sha1_hex($url . $SALT);
290                 $link_map->{$key} = $url;
291                 'PI-LINK-'. $key;
292         !ge;
293         $s;
294 }
295
296 sub linkify_2 {
297         my ($link_map, $s) = @_;
298
299         # Added "PI-LINK-" prefix to avoid false-positives on git commits
300         $s =~ s!\bPI-LINK-([a-f0-9]{40})\b!
301                 my $key = $1;
302                 my $url = $link_map->{$key};
303                 if (defined $url) {
304                         $url = ascii_html($url);
305                         "<a\nhref=\"$url\">$url</a>";
306                 } else {
307                         # false positive or somebody tried to mess with us
308                         $key;
309                 }
310         !ge;
311         $s;
312 }
313
314 sub flush_quote {
315         my ($quot, $n, $part_nr, $full_pfx, $final, $do_anchor) = @_;
316
317         if ($full_pfx) {
318                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
319                         # show quote inline
320                         my %l;
321                         my $rv = join('', map { linkify_1(\%l, $_) } @$quot);
322                         @$quot = ();
323                         $rv = ascii_html($rv);
324                         return linkify_2(\%l, $rv);
325                 }
326
327                 # show a short snippet of quoted text and link to full version:
328                 @$quot = map { s/^(?:>\s*)+//gm; $_ } @$quot;
329                 my $cur = join(' ', @$quot);
330                 @$quot = split(/\s+/, $cur);
331                 $cur = '';
332                 do {
333                         my $tmp = shift(@$quot);
334                         my $len = length($tmp) + length($cur);
335                         if ($len > MAX_TRUNC_LEN) {
336                                 @$quot = ();
337                         } else {
338                                 $cur .= $tmp . ' ';
339                         }
340                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
341                 @$quot = ();
342                 $cur =~ s/ \z/ .../s;
343                 $cur = ascii_html($cur);
344                 my $nr = ++$$n;
345                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
346         } else {
347                 # show everything in the full version with anchor from
348                 # short version (see above)
349                 my %l;
350                 my $rv .= join('', map { linkify_1(\%l, $_) } @$quot);
351                 @$quot = ();
352                 $rv = ascii_html($rv);
353                 return linkify_2(\%l, $rv) unless $do_anchor;
354                 my $nr = ++$$n;
355                 "<a\nid=q${part_nr}_$nr></a>" . linkify_2(\%l, $rv);
356         }
357 }
358
359 sub add_text_body {
360         my ($enc_msg, $part, $part_nr, $full_pfx, $do_anchor) = @_;
361         return '' if $part->subparts;
362
363         my $ct = $part->content_type;
364         # account for filter bugs...
365         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
366                 $part->body_set('');
367                 return '';
368         }
369         my $enc = enc_for($ct, $enc_msg);
370         my $n = 0;
371         my $nr = 0;
372         my $s = $part->body;
373         $part->body_set('');
374         $s = $enc->decode($s);
375         my @lines = split(/^/m, $s);
376         $s = '';
377
378         if ($$part_nr > 0) {
379                 my $fn = $part->filename;
380                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
381                 $s .= add_filename_line($enc, $fn);
382         }
383
384         my @quot;
385         while (defined(my $cur = shift @lines)) {
386                 if ($cur !~ /^>/) {
387                         # show the previously buffered quote inline
388                         if (scalar @quot) {
389                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
390                                                   $full_pfx, 0, $do_anchor);
391                         }
392
393                         # regular line, OK
394                         my %l;
395                         $cur = linkify_1(\%l, $cur);
396                         $cur = ascii_html($cur);
397                         $s .= linkify_2(\%l, $cur);
398                 } else {
399                         push @quot, $cur;
400                 }
401         }
402         if (scalar @quot) {
403                 $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1,
404                                   $do_anchor);
405         }
406         $s .= "\n" unless $s =~ /\n\z/s;
407         ++$$part_nr;
408         $s;
409 }
410
411 sub headers_to_html_header {
412         my ($mime, $full_pfx, $ctx) = @_;
413         my $srch = $ctx->{srch} if $ctx;
414         my $rv = "";
415         my @title;
416         my $header_obj = $mime->header_obj;
417         my $mid = $header_obj->header('Message-ID');
418         $mid = PublicInbox::Hval->new_msgid($mid);
419         foreach my $h (qw(From To Cc Subject Date)) {
420                 my $v = $header_obj->header($h);
421                 defined($v) && ($v ne '') or next;
422                 $v = PublicInbox::Hval->new_oneline($v);
423
424                 if ($h eq 'From') {
425                         my @from = Email::Address->parse($v->raw);
426                         $title[1] = ascii_html($from[0]->name);
427                 } elsif ($h eq 'Subject') {
428                         $title[0] = $v->as_html;
429                         if ($srch) {
430                                 $rv .= "$h: <b\nid=t>";
431                                 $rv .= $v->as_html . "</b>\n";
432                                 next;
433                         }
434                 }
435                 $rv .= "$h: " . $v->as_html . "\n";
436
437         }
438         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
439         my $upfx = $full_pfx ? '' : '../';
440         $rv .= "(<a\nhref=\"${upfx}raw\">raw</a>)\n";
441         my $atom;
442         if ($srch) {
443                 thread_inline(\$rv, $ctx, $mime, $upfx);
444
445                 $atom = qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
446                         qq!href="${upfx}t.atom"\ntype="application/atom+xml"/>!;
447         } else {
448                 $rv .= _parent_headers_nosrch($header_obj);
449                 $atom = '';
450         }
451         $rv .= "\n";
452
453         ("<html><head><title>".  join(' - ', @title) . "</title>$atom".
454          PublicInbox::Hval::STYLE . "</head><body><pre>" . $rv);
455 }
456
457 sub thread_inline {
458         my ($dst, $ctx, $cur, $upfx) = @_;
459         my $srch = $ctx->{srch};
460         my $mid = mid_clean($cur->header('Message-ID'));
461         my $res = $srch->get_thread($mid);
462         my $nr = $res->{total};
463         my $expand = "<a\nhref=\"${upfx}t/#u\">expand</a> " .
464                         "/ <a\nhref=\"${upfx}t.mbox.gz\">mbox.gz</a>";
465
466         $$dst .= 'Thread: ';
467         my $parent = in_reply_to($cur);
468         if ($nr <= 1) {
469                 $$dst .= "[no followups, yet] ($expand)\n";
470                 $ctx->{next_msg} = undef;
471                 $ctx->{parent_msg} = $parent;
472                 return;
473         }
474
475         $$dst .= "~$nr messages (<a\nhref=\"#b\">skip</a> / " .
476                  $expand . ")\n";
477
478         my $subj = $srch->subject_path($cur->header('Subject'));
479         my $state = {
480                 seen => { $subj => 1 },
481                 srch => $srch,
482                 cur => $mid,
483                 parent_cmp => defined $parent ? $parent : '',
484                 parent => $parent,
485                 prev_attr => '',
486                 prev_level => 0,
487         };
488         for (thread_results(load_results($res))->rootset) {
489                 inline_dump($dst, $state, $upfx, $_, 0);
490         }
491         $$dst .= "<a\nid=b></a>"; # anchor for body start
492         $ctx->{next_msg} = $state->{next_msg};
493         $ctx->{parent_msg} = $state->{parent};
494 }
495
496 sub _parent_headers_nosrch {
497         my ($header_obj) = @_;
498         my $rv = '';
499
500         my $irt = in_reply_to($header_obj);
501         if (defined $irt) {
502                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
503                 my $html = $v->as_html;
504                 my $href = $v->as_href;
505                 $rv .= "In-Reply-To: &lt;";
506                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
507         }
508
509         my $refs = $header_obj->header('References');
510         if ($refs) {
511                 # avoid redundant URLs wasting bandwidth
512                 my %seen;
513                 $seen{$irt} = 1 if defined $irt;
514                 my @refs;
515                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
516                 foreach my $ref (@raw_refs) {
517                         next if $seen{$ref};
518                         $seen{$ref} = 1;
519                         push @refs, linkify_ref_nosrch($ref);
520                 }
521
522                 if (@refs) {
523                         $rv .= 'References: '. join(' ', @refs) . "\n";
524                 }
525         }
526         $rv;
527 }
528
529 sub html_footer {
530         my ($mime, $standalone, $full_pfx, $ctx) = @_;
531         my %cc; # everyone else
532         my $to; # this is the From address
533
534         foreach my $h (qw(From To Cc)) {
535                 my $v = $mime->header($h);
536                 defined($v) && ($v ne '') or next;
537                 my @addrs = Email::Address->parse($v);
538                 foreach my $recip (@addrs) {
539                         my $address = $recip->address;
540                         my $dst = lc($address);
541                         $cc{$dst} ||= $address;
542                         $to ||= $dst;
543                 }
544         }
545         Email::Address->purge_cache if $standalone;
546
547         my $subj = $mime->header('Subject') || '';
548         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
549         my $mid = $mime->header('Message-ID');
550         my $irt = uri_escape_utf8($mid);
551         delete $cc{$to};
552         $to = uri_escape_utf8($to);
553         $subj = uri_escape_utf8($subj);
554
555         my $cc = uri_escape_utf8(join(',', sort values %cc));
556         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
557         $href =~ s/%20/+/g;
558
559         my $srch = $ctx->{srch} if $ctx;
560         my $upfx = $full_pfx ? '../' : '../../';
561         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
562
563         if ($srch && $standalone) {
564                 $idx .= qq{ / follow: <a\nhref="t.atom">Atom feed</a>\n};
565         }
566         if ($idx && $srch) {
567                 my $p = $ctx->{parent_msg};
568                 my $next = $ctx->{next_msg};
569                 if ($p) {
570                         $p = PublicInbox::Hval->new_oneline($p);
571                         $p = $p->as_href;
572                         $irt = "<a\nhref=\"$upfx$p/\">parent</a> ";
573                 } else {
574                         $irt = ' ' x length('parent ');
575                 }
576                 if ($next) {
577                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
578                 } else {
579                         $irt .= ' ' x length('next ');
580                 }
581                 if ($p || $next) {
582                         my $tpfx = $full_pfx ? '' : '../';
583                         $irt .= "<a\nhref=\"${tpfx}t/#u\">thread</a> ";
584                 } else {
585                         $irt .= ' ' x length('thread ');
586                 }
587         } else {
588                 $irt = '';
589         }
590
591         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
592 }
593
594 sub linkify_ref_nosrch {
595         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
596         my $html = $v->as_html;
597         my $href = $v->as_href;
598         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
599 }
600
601 sub anchor_for {
602         my ($msgid) = @_;
603         my $id = $msgid;
604         if ($id !~ /\A[a-f0-9]{40}\z/) {
605                 $id = id_compress(mid_clean($id), 1);
606         }
607         'm' . $id;
608 }
609
610 sub thread_html_head {
611         my ($cb, $header, $state) = @_;
612         $$cb = $$cb->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
613
614         my $s = PublicInbox::Hval->new_oneline($header->header('Subject'));
615         $s = $s->as_html;
616         $$cb->write("<html><head><title>$s</title>".
617                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
618                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
619                 PublicInbox::Hval::STYLE .
620                 "</head><body>");
621 }
622
623 sub pre_anchor_entry {
624         my ($seen, $mime) = @_;
625         my $id = anchor_for($mime->header('Message-ID'));
626         $seen->{$id} = "#$id"; # save the anchor for children, later
627 }
628
629 sub ghost_parent {
630         my ($upfx, $mid) = @_;
631         # 'subject dummy' is used internally by Mail::Thread
632         return '[no common parent]' if ($mid eq 'subject dummy');
633
634         $mid = PublicInbox::Hval->new_msgid($mid);
635         my $href = $mid->as_href;
636         my $html = $mid->as_html;
637         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
638 }
639
640 sub thread_adj_level {
641         my ($fh, $state, $level) = @_;
642
643         my $max = $state->{cur_level};
644         if ($level <= 0) {
645                 return '' if $max == 0; # flat output
646
647                 # reset existing lists
648                 my $x = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
649                 $fh->write($x . '</ul>');
650                 $state->{cur_level} = 0;
651                 return '';
652         }
653         if ($level == $max) { # continue existing list
654                 $fh->write('<li>');
655         } elsif ($level < $max) {
656                 my $x = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
657                 $fh->write($x .= '<li>');
658                 $state->{cur_level} = $level;
659         } else { # ($level > $max) # start a new level
660                 $state->{cur_level} = $level;
661                 $fh->write(($max ? '<li>' : '') . '<ul><li>');
662         }
663         '</li>';
664 }
665
666 sub ghost_flush {
667         my ($fh, $state, $upfx, $mid, $level) = @_;
668
669         my $end = thread_adj_level($fh, $state, $level);
670         $fh->write('<pre>'. ghost_parent($upfx, $mid) .  '</pre>' . $end);
671 }
672
673 sub __thread_entry {
674         my ($cb, $git, $state, $mime, $level) = @_;
675
676         # lazy load the full message from mini_mime:
677         $mime = eval {
678                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
679                 Email::MIME->new($git->cat_file('HEAD:'.$path));
680         } or return;
681
682         if ($state->{anchor_idx} == 0) {
683                 thread_html_head($cb, $mime, $state, $level);
684         }
685         my $fh = $$cb;
686         if (my $ghost = delete $state->{ghost}) {
687                 # n.b. ghost messages may only be parents, not children
688                 foreach my $g (@$ghost) {
689                         ghost_flush($fh, $state, '../../', @$g);
690                 }
691         }
692         my $end = thread_adj_level($fh, $state, $level);
693         index_entry($fh, $mime, $level, $state);
694         $fh->write($end) if $end;
695
696         1;
697 }
698
699 sub indent_for {
700         my ($level) = @_;
701         INDENT x ($level - 1);
702 }
703
704 sub __ghost_prepare {
705         my ($state, $node, $level) = @_;
706         my $ghost = $state->{ghost} ||= [];
707         push @$ghost, [ $node->messageid, $level ];
708 }
709
710 sub thread_entry {
711         my ($cb, $git, $state, $node, $level) = @_;
712         return unless $node;
713         if (my $mime = $node->message) {
714                 unless (__thread_entry($cb, $git, $state, $mime, $level)) {
715                         __ghost_prepare($state, $node, $level);
716                 }
717         } else {
718                 __ghost_prepare($state, $node, $level);
719         }
720
721         thread_entry($cb, $git, $state, $node->child, $level + 1);
722         thread_entry($cb, $git, $state, $node->next, $level);
723 }
724
725 sub load_results {
726         my ($res) = @_;
727
728         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
729 }
730
731 sub msg_timestamp {
732         my ($mime) = @_;
733         my $ts = eval { str2time($mime->header('Date')) };
734         defined($ts) ? $ts : 0;
735 }
736
737 sub thread_results {
738         my ($msgs, $nosubject) = @_;
739         require PublicInbox::Thread;
740         my $th = PublicInbox::Thread->new(@$msgs);
741         no warnings 'once';
742         $Mail::Thread::nosubject = $nosubject;
743         $th->thread;
744         $th->order(*sort_ts);
745         $th
746 }
747
748 sub missing_thread {
749         my ($cb, $ctx) = @_;
750         require PublicInbox::ExtMsg;
751
752         $cb->(PublicInbox::ExtMsg::ext_msg($ctx))
753 }
754
755 sub _msg_date {
756         my ($mime) = @_;
757         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
758         fmt_ts($ts);
759 }
760
761 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
762
763 sub _inline_header {
764         my ($dst, $state, $upfx, $mime, $level) = @_;
765         my $dot = $level == 0 ? '' : '` ';
766
767         my $cur = $state->{cur};
768         my $mid = mid_clean($mime->header('Message-ID'));
769         my $f = $mime->header('X-PI-From');
770         my $d = _msg_date($mime);
771         $f = PublicInbox::Hval->new($f)->as_html;
772         $d = PublicInbox::Hval->new($d)->as_html;
773         my $pfx = ' ' . $d . ' ' . indent_for($level);
774         my $attr = $f;
775         $state->{first_level} ||= $level;
776
777         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
778                 $state->{prev_attr} = $attr;
779         } else {
780                 $attr = '';
781         }
782         $state->{prev_level} = $level;
783
784         if ($cur) {
785                 if ($cur eq $mid) {
786                         delete $state->{cur};
787                         $$dst .= "$pfx$dot<b><a\nid=r\nhref=\"#b\">".
788                                  "$attr [this message]</a></b>\n";
789
790                         return;
791                 }
792         } else {
793                 $state->{next_msg} ||= $mid;
794         }
795
796         # Subject is never undef, this mail was loaded from
797         # our Xapian which would've resulted in '' if it were
798         # really missing (and Filter rejects empty subjects)
799         my $s = $mime->header('Subject');
800         my $h = $state->{srch}->subject_path($s);
801         if ($state->{seen}->{$h}) {
802                 $s = undef;
803         } else {
804                 $state->{seen}->{$h} = 1;
805                 $s = PublicInbox::Hval->new($s);
806                 $s = $s->as_html;
807         }
808         my $m = PublicInbox::Hval->new_msgid($mid);
809         $m = $upfx . '../' . $m->as_href . '/';
810         if (defined $s) {
811                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$s</a> $attr\n";
812         } else {
813                 $$dst .= "$pfx$dot<a\nhref=\"$m\">$f</a>\n";
814         }
815 }
816
817 sub inline_dump {
818         my ($dst, $state, $upfx, $node, $level) = @_;
819         return unless $node;
820         if (my $mime = $node->message) {
821                 my $mid = mid_clean($mime->header('Message-ID'));
822                 if ($mid eq $state->{parent_cmp}) {
823                         $state->{parent} = $mid;
824                 }
825                 _inline_header($dst, $state, $upfx, $mime, $level);
826         } else {
827                 my $dot = $level == 0 ? '' : '` ';
828                 my $pfx = (' ' x length(' 1970-01-01 13:37 ')).
829                         indent_for($level) . $dot;
830                 $$dst .= $pfx;
831                 $$dst .= ghost_parent("$upfx../", $node->messageid) . "\n";
832         }
833         inline_dump($dst, $state, $upfx, $node->child, $level+1);
834         inline_dump($dst, $state, $upfx, $node->next, $level);
835 }
836
837 sub sort_ts {
838         sort {
839                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
840                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
841         } @_;
842 }
843
844 sub rsort_ts {
845         sort {
846                 (eval { $b->topmost->message->header('X-PI-TS') } || 0) <=>
847                 (eval { $a->topmost->message->header('X-PI-TS') } || 0)
848         } @_;
849 }
850
851 # accumulate recent topics if search is supported
852 # returns 1 if done, undef if not
853 sub add_topic {
854         my ($state, $node, $level) = @_;
855         return unless $node;
856         my $child_adjust = 1;
857
858         if (my $x = $node->message) {
859                 $x = $x->header_obj;
860                 my ($topic, $subj);
861
862                 $subj = $x->header('Subject');
863                 $subj = $state->{srch}->subject_normalized($subj);
864                 $topic = $subj;
865
866                 # kill "[PATCH v2]" etc. for summarization
867                 unless ($level == 0) {
868                         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
869                 }
870
871                 if (++$state->{subjs}->{$topic} == 1) {
872                         push @{$state->{order}}, [ $level, $subj, $topic ];
873                 }
874
875                 my $mid = mid_clean($x->header('Message-ID'));
876
877                 my $ts = $x->header('X-PI-TS');
878                 my $exist = $state->{latest}->{$topic};
879                 if (!$exist || $exist->[1] < $ts) {
880                         $state->{latest}->{$topic} = [ $mid, $ts ];
881                 }
882         } else {
883                 # ghost message, do not bump level
884                 $child_adjust = 0;
885         }
886
887         add_topic($state, $node->child, $level + $child_adjust);
888         add_topic($state, $node->next, $level);
889 }
890
891 sub dump_topics {
892         my ($state) = @_;
893         my $order = $state->{order};
894         my $subjs = $state->{subjs};
895         my $latest = $state->{latest};
896         return "\n[No topics in range]</pre>" unless (scalar @$order);
897         my $dst = '';
898         my $pfx;
899         my $prev = 0;
900         my $prev_attr = '';
901         while (defined(my $info = shift @$order)) {
902                 my ($level, $subj, $topic) = @$info;
903                 my $n = delete $subjs->{$topic};
904                 my ($mid, $ts) = @{delete $latest->{$topic}};
905                 $mid = PublicInbox::Hval->new($mid)->as_href;
906                 $subj = PublicInbox::Hval->new($subj)->as_html;
907                 $pfx = indent_for($level);
908                 my $nl = $level == $prev ? "\n" : '';
909                 my $dot = $level == 0 ? '' : '` ';
910                 $dst .= "$nl$pfx$dot<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
911
912                 my $attr;
913                 $ts = fmt_ts($ts);
914                 $attr = " $ts UTC";
915
916                 # $n isn't the total number of posts on the topic,
917                 # just the number of posts in the current results
918                 # window, so leave it unlabeled
919                 $n = $n == 1 ? '' : " ($n+ messages)";
920
921                 if ($level == 0 || $attr ne $prev_attr) {
922                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
923                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
924                         $pfx .= INDENT if $level > 0;
925                         $dst .= $pfx . $attr . $n . " - $mbox / $atom\n";
926                         $prev_attr = $attr;
927                 }
928         }
929         $dst .= '</pre>';
930 }
931
932 sub emit_index_topics {
933         my ($state, $fh) = @_;
934         my $off = $state->{ctx}->{cgi}->param('o');
935         $off = 0 unless defined $off;
936         $state->{order} = [];
937         $state->{subjs} = {};
938         $state->{latest} = {};
939         my $max = 25;
940         my %opts = ( offset => int $off, limit => $max * 4 );
941         while (scalar @{$state->{order}} < $max) {
942                 my $res = $state->{srch}->query('', \%opts);
943                 my $nr = scalar @{$res->{msgs}} or last;
944
945                 for (rsort_ts(thread_results(load_results($res), 1)->rootset)) {
946                         add_topic($state, $_, 0);
947                 }
948                 $opts{offset} += $nr;
949         }
950
951         $fh->write(dump_topics($state));
952         $opts{offset};
953 }
954
955 1;