]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchView.pm
isearch: emulate per-inbox search with ->ALL
[public-inbox.git] / lib / PublicInbox / SearchView.pm
1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Displays search results for the web interface
5 package PublicInbox::SearchView;
6 use strict;
7 use v5.10.1;
8 use List::Util qw(min max);
9 use URI::Escape qw(uri_unescape);
10 use PublicInbox::Smsg;
11 use PublicInbox::Hval qw(ascii_html obfuscate_addrs mid_href fmt_ts);
12 use PublicInbox::View;
13 use PublicInbox::WwwAtomStream;
14 use PublicInbox::WwwStream qw(html_oneshot);
15 use PublicInbox::SearchThread;
16 use PublicInbox::SearchQuery;
17 use PublicInbox::Search;
18 my %rmap_inc;
19
20 sub mbox_results {
21         my ($ctx) = @_;
22         my $q = PublicInbox::SearchQuery->new($ctx->{qp});
23         if ($ctx->{env}->{'psgi.input'}->read(my $buf, 3)) {
24                 $q->{t} = 1 if $buf =~ /\Ax=[^0]/;
25         }
26         require PublicInbox::Mbox;
27         $q->{x} eq 'm' ? PublicInbox::Mbox::mbox_all($ctx, $q) :
28                         sres_top_html($ctx);
29 }
30
31 sub sres_top_html {
32         my ($ctx) = @_;
33         my $srch = $ctx->{-inbox}->isrch or
34                 return PublicInbox::WWW::need($ctx, 'Search');
35         my $q = PublicInbox::SearchQuery->new($ctx->{qp});
36         my $x = $q->{x};
37         my $query = $q->{'q'};
38         my $o = $q->{o};
39         my $asc;
40         if ($o < 0) {
41                 $asc = 1;
42                 $o = -($o + 1); # so [-1] is the last element, like Perl lists
43         }
44
45         my $code = 200;
46         # double the limit for expanded views:
47         my $opts = {
48                 limit => $q->{l},
49                 offset => $o,
50                 relevance => $q->{r},
51                 thread => $q->{t},
52                 asc => $asc,
53         };
54         my ($mset, $total, $err, $html);
55 retry:
56         eval {
57                 $mset = $srch->mset($query, $opts);
58                 $total = $mset->get_matches_estimated;
59         };
60         $err = $@;
61         ctx_prepare($q, $ctx);
62         if ($err) {
63                 $code = 400;
64                 $html = '<pre>'.err_txt($ctx, $err).'</pre><hr>';
65         } elsif ($total == 0) {
66                 if (defined($ctx->{-uxs_retried})) {
67                         # undo retry damage:
68                         $q->{'q'} = $ctx->{-uxs_retried};
69                 } elsif (index($q->{'q'}, '%') >= 0) {
70                         $ctx->{-uxs_retried} = $q->{'q'};
71                         $q->{'q'} = uri_unescape($q->{'q'});
72                         goto retry;
73                 }
74                 $code = 404;
75                 $html = "<pre>\n[No results found]</pre><hr>";
76         } else {
77                 return adump($_[0], $mset, $q, $ctx) if $x eq 'A';
78
79                 $ctx->{-html_tip} = search_nav_top($mset, $q, $ctx);
80                 return mset_thread($ctx, $mset, $q) if $x eq 't';
81                 mset_summary($ctx, $mset, $q); # appends to {-html_tip}
82                 $html = '';
83         }
84         html_oneshot($ctx, $code);
85 }
86
87 # display non-nested search results similar to what users expect from
88 # regular WWW search engines:
89 sub mset_summary {
90         my ($ctx, $mset, $q) = @_;
91
92         my $total = $mset->get_matches_estimated;
93         my $pad = length("$total");
94         my $pfx = ' ' x $pad;
95         my $res = \($ctx->{-html_tip});
96         my $ibx = $ctx->{-inbox};
97         my $obfs_ibx = $ibx->{obfuscate} ? $ibx : undef;
98         my @nums = @{$ibx->isrch->mset_to_artnums($mset)};
99         my %num2msg = map { $_->{num} => $_ } @{$ibx->over->get_all(@nums)};
100         my ($min, $max);
101
102         foreach my $m ($mset->items) {
103                 my $rank = sprintf("%${pad}d", $m->get_rank + 1);
104                 my $pct = get_pct($m);
105                 my $num = shift @nums;
106                 my $smsg = delete($num2msg{$num}) or do {
107                         eval {
108                                 $m = "$m $num expired\n";
109                                 $ctx->{env}->{'psgi.errors'}->print($m);
110                         };
111                         next;
112                 };
113                 $ctx->{-t_max} //= $smsg->{ts};
114
115                 # only when sorting by relevance, ->items is always
116                 # ordered descending:
117                 $max //= $pct;
118                 $min = $pct;
119
120                 my $s = ascii_html($smsg->{subject});
121                 my $f = ascii_html($smsg->{from_name});
122                 if ($obfs_ibx) {
123                         obfuscate_addrs($obfs_ibx, $s);
124                         obfuscate_addrs($obfs_ibx, $f);
125                 }
126                 my $date = fmt_ts($smsg->{ds});
127                 my $mid = mid_href($smsg->{mid});
128                 $s = '(no subject)' if $s eq '';
129                 $$res .= qq{$rank. <b><a\nhref="$mid/">}.
130                         $s . "</a></b>\n";
131                 $$res .= "$pfx  - by $f @ $date UTC [$pct%]\n\n";
132         }
133         if ($q->{r}) { # for descriptions in search_nav_bot
134                 $q->{-min_pct} = $min;
135                 $q->{-max_pct} = $max;
136         }
137         $$res .= search_nav_bot($mset, $q);
138         undef;
139 }
140
141 # shorten "/full/path/to/Foo/Bar.pm" to "Foo/Bar.pm" so error
142 # messages don't reveal FS layout info in case people use non-standard
143 # installation paths
144 sub path2inc ($) {
145         my $full = $_[0];
146         if (my $short = $rmap_inc{$full}) {
147                 return $short;
148         } elsif (!scalar(keys %rmap_inc) && -e $full) {
149                 %rmap_inc = map {; "$INC{$_}" => $_ } keys %INC;
150                 # fall back to basename as last resort
151                 $rmap_inc{$full} // (split('/', $full))[-1];
152         } else {
153                 $full;
154         }
155 }
156
157 sub err_txt {
158         my ($ctx, $err) = @_;
159         my $u = $ctx->{-inbox}->base_url($ctx->{env}) . '_/text/help/';
160         $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
161         $err =~ s!(\S+)!path2inc($1)!sge;
162         $err = ascii_html($err);
163         "\nBad query: <b>$err</b>\n" .
164                 qq{See <a\nhref="$u">$u</a> for help on using search};
165 }
166
167 sub search_nav_top {
168         my ($mset, $q, $ctx) = @_;
169         my $m = $q->qs_html(x => 'm', r => undef, t => undef);
170         my $rv = qq{<form\naction="?$m"\nmethod="post"><pre>};
171         my $initial_q = $ctx->{-uxs_retried};
172         if (defined $initial_q) {
173                 my $rewritten = $q->{'q'};
174                 utf8::decode($initial_q);
175                 utf8::decode($rewritten);
176                 $initial_q = ascii_html($initial_q);
177                 $rewritten = ascii_html($rewritten);
178                 $rv .= " Warning: Initial query:\n <b>$initial_q</b>\n";
179                 $rv .= " returned no results, used:\n";
180                 $rv .= " <b>$rewritten</b>\n instead\n\n";
181         }
182
183         $rv .= 'Search results ordered by [';
184         if ($q->{r}) {
185                 my $d = $q->qs_html(r => 0);
186                 $rv .= qq{<a\nhref="?$d">date</a>|<b>relevance</b>};
187         } else {
188                 my $d = $q->qs_html(r => 1);
189                 $rv .= qq{<b>date</b>|<a\nhref="?$d">relevance</a>};
190         }
191
192         $rv .= ']  view[';
193
194         my $x = $q->{x};
195         if ($x eq '') {
196                 my $t = $q->qs_html(x => 't');
197                 $rv .= qq{<b>summary</b>|<a\nhref="?$t">nested</a>}
198         } elsif ($q->{x} eq 't') {
199                 my $s = $q->qs_html(x => '');
200                 $rv .= qq{<a\nhref="?$s">summary</a>|<b>nested</b>};
201         }
202         my $A = $q->qs_html(x => 'A', r => undef);
203         $rv .= qq{|<a\nhref="?$A">Atom feed</a>]};
204         if ($ctx->{-inbox}->isrch->has_threadid) {
205                 $rv .= qq{\n\t\t\tdownload mbox.gz: } .
206                         # we set name=z w/o using it since it seems required for
207                         # lynx (but works fine for w3m).
208                         qq{<input\ntype=submit\nname=z\n} .
209                                 q{value="results only"/>} .
210                         qq{|<input\ntype=submit\nname=x\n} .
211                                 q{value="full threads"/>};
212         } else { # BOFH needs to --reindex
213                 $rv .= qq{\n\t\t\t\t\t\tdownload: } .
214                         qq{<input\ntype=submit\nname=z\nvalue="mbox.gz"/>}
215         }
216         $rv .= qq{</pre></form><pre>};
217 }
218
219 sub search_nav_bot {
220         my ($mset, $q) = @_;
221         my $total = $mset->get_matches_estimated;
222         my $l = $q->{l};
223         my $rv = '</pre><hr><pre id=t>';
224         my $o = $q->{o};
225         my $off = $o < 0 ? -($o + 1) : $o;
226         my $end = $off + $mset->size;
227         my $beg = $off + 1;
228
229         if ($beg <= $end) {
230                 my $approx = $end == $total ? '' : '~';
231                 $rv .= "Results $beg-$end of $approx$total";
232         } else {
233                 $rv .= "No more results, only $total";
234         }
235         my ($next, $join, $prev, $nd, $pd);
236
237         if ($o >= 0) { # sort descending
238                 my $n = $o + $l;
239                 if ($n < $total) {
240                         $next = $q->qs_html(o => $n, l => $l);
241                         $nd = $q->{r} ? "[&lt;= $q->{-min_pct}%]" : '(older)';
242                 }
243                 if ($o > 0) {
244                         $join = $n < $total ? ' | ' : "\t";
245                         my $p = $o - $l;
246                         $prev = $q->qs_html(o => ($p > 0 ? $p : 0));
247                         $pd = $q->{r} ? "[&gt;= $q->{-max_pct}%]" : '(newer)';
248                 }
249         } else { # o < 0, sort ascending
250                 my $n = $o - $l;
251
252                 if (-$n < $total) {
253                         $next = $q->qs_html(o => $n, l => $l);
254                         $nd = $q->{r} ? "[&lt;= $q->{-min_pct}%]" : '(newer)';
255                 }
256                 if ($o < -1) {
257                         $join = -$n < $total ? ' | ' : "\t";
258                         my $p = $o + $l;
259                         $prev = $q->qs_html(o => ($p < 0 ? $p : 0));
260                         $pd = $q->{r} ? "[&gt;= $q->{-max_pct}%]" : '(older)';
261                 }
262         }
263
264         $rv .= qq{  <a\nhref="?$next"\nrel=next>next $nd</a>} if $next;
265         $rv .= $join if $join;
266         $rv .= qq{<a\nhref="?$prev"\nrel=prev>prev $pd</a>} if $prev;
267
268         my $rev = $q->qs_html(o => $o < 0 ? 0 : -1);
269         $rv .= qq{ | <a\nhref="?$rev">reverse</a></pre>};
270 }
271
272 sub sort_relevance {
273         [ sort {
274                 (eval { $b->topmost->{pct} } // 0) <=>
275                 (eval { $a->topmost->{pct} } // 0)
276         } @{$_[0]} ]
277 }
278
279 sub get_pct ($) {
280         # Capped at "99%" since "100%" takes an extra column in the
281         # thread skeleton view.  <xapian/mset.h> says the value isn't
282         # very meaningful, anyways.
283         my $n = $_[0]->get_percent;
284         $n > 99 ? 99 : $n;
285 }
286
287 sub mset_thread {
288         my ($ctx, $mset, $q) = @_;
289         my $ibx = $ctx->{-inbox};
290         my @pct = map { get_pct($_) } $mset->items;
291         my $msgs = $ibx->isrch->mset_to_smsg($ibx, $mset);
292         my $i = 0;
293         $_->{pct} = $pct[$i++] for @$msgs;
294         my $r = $q->{r};
295         if ($r) { # for descriptions in search_nav_bot
296                 $q->{-min_pct} = min(@pct);
297                 $q->{-max_pct} = max(@pct);
298         }
299         my $rootset = PublicInbox::SearchThread::thread($msgs,
300                 $r ? \&sort_relevance : \&PublicInbox::View::sort_ds,
301                 $ctx);
302         my $skel = search_nav_bot($mset, $q). "<pre>";
303         $ctx->{-upfx} = '';
304         $ctx->{anchor_idx} = 1;
305         $ctx->{cur_level} = 0;
306         $ctx->{skel} = \$skel;
307         $ctx->{mapping} = {};
308         $ctx->{searchview} = 1;
309         $ctx->{prev_attr} = '';
310         $ctx->{prev_level} = 0;
311         $ctx->{s_nr} = scalar(@$msgs).'+ results';
312
313         # reduce hash lookups in skel_dump
314         $ctx->{-obfs_ibx} = $ibx->{obfuscate} ? $ibx : undef;
315         PublicInbox::View::walk_thread($rootset, $ctx,
316                 \&PublicInbox::View::pre_thread);
317
318         # link $INBOX_DIR/description text to "recent" view around
319         # the newest message in this result set:
320         $ctx->{-t_max} = max(map { delete $_->{ts} } @$msgs);
321
322         @$msgs = reverse @$msgs if $r;
323         $ctx->{msgs} = $msgs;
324         PublicInbox::WwwStream::aresponse($ctx, 200, \&mset_thread_i);
325 }
326
327 # callback for PublicInbox::WwwStream::getline
328 sub mset_thread_i {
329         my ($ctx, $eml) = @_;
330         $ctx->zmore($ctx->html_top) if exists $ctx->{-html_tip};
331         $eml and return PublicInbox::View::eml_entry($ctx, $eml);
332         my $smsg = shift @{$ctx->{msgs}} or
333                 $ctx->zmore(${delete($ctx->{skel})});
334         $smsg;
335 }
336
337 sub ctx_prepare {
338         my ($q, $ctx) = @_;
339         my $qh = $q->{'q'};
340         utf8::decode($qh);
341         $qh = ascii_html($qh);
342         $ctx->{-q_value_html} = $qh;
343         $ctx->{-atom} = '?'.$q->qs_html(x => 'A', r => undef);
344         $ctx->{-title_html} = "$qh - search results";
345         my $extra = '';
346         $extra .= qq{<input\ntype=hidden\nname=r />} if $q->{r};
347         if (my $x = $q->{x}) {
348                 $x = ascii_html($x);
349                 $extra .= qq{<input\ntype=hidden\nname=x\nvalue="$x" />};
350         }
351         $ctx->{-extra_form_html} = $extra;
352 }
353
354 sub adump {
355         my ($cb, $mset, $q, $ctx) = @_;
356         $ctx->{ids} = $ctx->{-inbox}->isrch->mset_to_artnums($mset);
357         $ctx->{search_query} = $q; # used by WwwAtomStream::atom_header
358         PublicInbox::WwwAtomStream->response($ctx, 200, \&adump_i);
359 }
360
361 # callback for PublicInbox::WwwAtomStream::getline
362 sub adump_i {
363         my ($ctx) = @_;
364         while (my $num = shift @{$ctx->{ids}}) {
365                 my $smsg = eval { $ctx->{-inbox}->over->get_art($num) } or next;
366                 return $smsg;
367         }
368 }
369
370 1;