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