]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
www: implement generic help text
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8 use warnings;
9
10 # values for searching
11 use constant TS => 0; # timestamp
12 use constant NUM => 1; # NNTP article number
13 use constant BYTES => 2; # :bytes as defined in RFC 3977
14 use constant LINES => 3; # :lines as defined in RFC 3977
15 use constant YYYYMMDD => 4; # for searching in the WWW UI
16
17 use Search::Xapian qw/:standard/;
18 use PublicInbox::SearchMsg;
19 use Email::MIME;
20 use PublicInbox::MID qw/mid_clean id_compress/;
21
22 # This is English-only, everything else is non-standard and may be confused as
23 # a prefix common in patch emails
24 our $REPLY_RE = qr/^re:\s+/i;
25 our $LANG = 'english';
26
27 use constant {
28         # SCHEMA_VERSION history
29         # 0 - initial
30         # 1 - subject_path is lower-cased
31         # 2 - subject_path is id_compress in the index, only
32         # 3 - message-ID is compressed if it includes '%' (hack!)
33         # 4 - change "Re: " normalization, avoid circular Reference ghosts
34         # 5 - subject_path drops trailing '.'
35         # 6 - preserve References: order in document data
36         # 7 - remove references and inreplyto terms
37         # 8 - remove redundant/unneeded document data
38         # 9 - disable Message-ID compression (SHA-1)
39         # 10 - optimize doc for NNTP overviews
40         # 11 - merge threads when vivifying ghosts
41         SCHEMA_VERSION => 11,
42
43         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
44         # as it could become a denial-of-service vector
45         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
46 };
47
48 # setup prefixes
49 my %bool_pfx_internal = (
50         type => 'T', # "mail" or "ghost"
51         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
52 );
53
54 # do we still need these? probably not..
55 my %bool_pfx_external = (
56         path => 'XPATH',
57         mid => 'Q', # uniQue id (Message-ID)
58 );
59
60 my %prob_prefix = (
61         subject => 'S',
62         s => 'S', # for mairix compatibility
63         m => 'Q', # 'mid' is exact, 'm' can do partial
64 );
65
66 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
67 our @HELP = (
68         's:' => <<EOF,
69 match within Subject only  e.g. s:"a quick brown fox"
70 This is a probabilistic search with support for stemming
71 and wildcards '*'
72 EOF
73         'd:' => <<EOF,
74 date range as YYYYMMDD  e.g. d:19931002..20101002
75 Open-ended ranges such as d:19931002.. and d:..20101002
76 are also supported.
77 EOF
78 );
79 # TODO: (from mairix, some of these are maybe)
80 # b (body), f (From:), c (Cc:), n (attachment), t (To:)
81 # tc (To:+Cc:), bs (body + Subject), tcf (To: +Cc: +From:)
82 #
83 # Non-mairix:
84 # df (filenames from diff)
85 # nq (non-quoted body)
86 # da (diff a/ removed lines)
87 # db (diff b/ added lines)
88
89 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
90
91 sub xpfx { $all_pfx{$_[0]} }
92
93 our %PFX2TERM_RMAP;
94 my %meta_pfx = (mid => 1, thread => 1, path => 1);
95 while (my ($k, $v) = each %all_pfx) {
96         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
97 }
98
99 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
100
101 sub xdir {
102         my (undef, $git_dir) = @_;
103         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
104 }
105
106 sub new {
107         my ($class, $git_dir, $altid) = @_;
108         my $dir = $class->xdir($git_dir);
109         my $db = Search::Xapian::Database->new($dir);
110         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
111 }
112
113 sub reopen { $_[0]->{xdb}->reopen }
114
115 # read-only
116 sub query {
117         my ($self, $query_string, $opts) = @_;
118         my $query;
119
120         $opts ||= {};
121         unless ($query_string eq '') {
122                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
123                 $opts->{relevance} = 1 unless exists $opts->{relevance};
124         }
125
126         _do_enquire($self, $query, $opts);
127 }
128
129 sub get_thread {
130         my ($self, $mid, $opts) = @_;
131         my $smsg = eval { $self->lookup_message($mid) };
132
133         return { total => 0, msgs => [] } unless $smsg;
134         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
135         my $path = $smsg->path;
136         if (defined $path && $path ne '') {
137                 my $path = id_compress($smsg->path);
138                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
139                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
140         }
141         $opts ||= {};
142         $opts->{limit} ||= 1000;
143         _do_enquire($self, $qtid, $opts);
144 }
145
146 sub _do_enquire {
147         my ($self, $query, $opts) = @_;
148         my $ret;
149         for (1..10) {
150                 eval { $ret = _enquire_once($self, $query, $opts) };
151                 return $ret unless $@;
152                 # Exception: The revision being read has been discarded -
153                 # you should call Xapian::Database::reopen()
154                 if (index($@, 'Xapian::Database::reopen') >= 0) {
155                         reopen($self);
156                 } else {
157                         die $@;
158                 }
159         }
160 }
161
162 sub _enquire_once {
163         my ($self, $query, $opts) = @_;
164         my $enquire = $self->enquire;
165         if (defined $query) {
166                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
167         } else {
168                 $query = $mail_query;
169         }
170         $enquire->set_query($query);
171         $opts ||= {};
172         my $desc = !$opts->{asc};
173         if ($opts->{relevance}) {
174                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
175         } elsif ($opts->{num}) {
176                 $enquire->set_sort_by_value(NUM, 0);
177         } else {
178                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
179         }
180         my $offset = $opts->{offset} || 0;
181         my $limit = $opts->{limit} || 50;
182         my $mset = $enquire->get_mset($offset, $limit);
183         return $mset if $opts->{mset};
184         my @msgs = map {
185                 PublicInbox::SearchMsg->load_doc($_->get_document);
186         } $mset->items;
187
188         { total => $mset->get_matches_estimated, msgs => \@msgs }
189 }
190
191 # read-write
192 sub stemmer { Search::Xapian::Stem->new($LANG) }
193
194 # read-only
195 sub qp {
196         my ($self) = @_;
197
198         my $qp = $self->{query_parser};
199         return $qp if $qp;
200
201         # new parser
202         $qp = Search::Xapian::QueryParser->new;
203         $qp->set_default_op(OP_AND);
204         $qp->set_database($self->{xdb});
205         $qp->set_stemmer($self->stemmer);
206         $qp->set_stemming_strategy(STEM_SOME);
207         $qp->add_valuerangeprocessor(
208                 Search::Xapian::StringValueRangeProcessor->new(YYYYMMDD, 'd:'));
209
210         while (my ($name, $prefix) = each %bool_pfx_external) {
211                 $qp->add_boolean_prefix($name, $prefix);
212         }
213
214         # we do not actually create AltId objects,
215         # just parse the spec to avoid the extra DB handles for now.
216         if (my $altid = $self->{altid}) {
217                 my $user_pfx = $self->{-user_pfx} ||= [];
218                 for (@$altid) {
219                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
220                         /\Aserial:(\w+):/ or next;
221                         my $pfx = $1;
222                         push @$user_pfx, "$pfx:", <<EOF;
223 alternate serial number  e.g. $pfx:12345
224 EOF
225                         # gmane => XGMANE
226                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
227                 }
228         }
229
230         while (my ($name, $prefix) = each %prob_prefix) {
231                 $qp->add_prefix($name, $prefix);
232         }
233
234         $self->{query_parser} = $qp;
235 }
236
237 sub num_range_processor {
238         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
239 }
240
241 # only used for NNTP server
242 sub query_xover {
243         my ($self, $beg, $end, $offset) = @_;
244         my $qp = Search::Xapian::QueryParser->new;
245         $qp->set_database($self->{xdb});
246         $qp->add_valuerangeprocessor($self->num_range_processor);
247         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
248
249         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
250 }
251
252 sub lookup_message {
253         my ($self, $mid) = @_;
254         $mid = mid_clean($mid);
255
256         my $doc_id = $self->find_unique_doc_id('mid', $mid);
257         my $smsg;
258         if (defined $doc_id) {
259                 # raises on error:
260                 my $doc = $self->{xdb}->get_document($doc_id);
261                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
262                 $smsg->doc_id($doc_id);
263         }
264         $smsg;
265 }
266
267 sub lookup_mail { # no ghosts!
268         my ($self, $mid) = @_;
269         my $smsg = lookup_message($self, $mid) or return;
270         PublicInbox::SearchMsg->load_doc($smsg->{doc});
271 }
272
273 sub find_unique_doc_id {
274         my ($self, $term, $value) = @_;
275
276         my ($begin, $end) = $self->find_doc_ids($term, $value);
277
278         return undef if $begin->equal($end); # not found
279
280         my $rv = $begin->get_docid;
281
282         # sanity check
283         $begin->inc;
284         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
285         $rv;
286 }
287
288 # returns begin and end PostingIterator
289 sub find_doc_ids {
290         my ($self, $term, $value) = @_;
291
292         $self->find_doc_ids_for_term(xpfx($term) . $value);
293 }
294
295 # returns begin and end PostingIterator
296 sub find_doc_ids_for_term {
297         my ($self, $term) = @_;
298         my $db = $self->{xdb};
299
300         ($db->postlist_begin($term), $db->postlist_end($term));
301 }
302
303 # normalize subjects so they are suitable as pathnames for URLs
304 sub subject_path {
305         my $subj = pop;
306         $subj = subject_normalized($subj);
307         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
308         lc($subj);
309 }
310
311 sub subject_normalized {
312         my $subj = pop;
313         $subj =~ s/\A\s+//s; # no leading space
314         $subj =~ s/\s+\z//s; # no trailing space
315         $subj =~ s/\s+/ /gs; # no redundant spaces
316         $subj =~ s/\.+\z//; # no trailing '.'
317         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
318         $subj;
319 }
320
321 # for doc data
322 sub subject_summary {
323         my $subj = pop;
324         my $max = 68;
325         if (length($subj) > $max) {
326                 my @subj = split(/\s+/, $subj);
327                 $subj = '';
328                 my $l;
329
330                 while ($l = shift @subj) {
331                         my $new = $subj . $l . ' ';
332                         last if length($new) >= $max;
333                         $subj = $new;
334                 }
335                 if ($subj ne '') {
336                         my $r = scalar @subj ? ' ...' : '';
337                         $subj =~ s/ \z/$r/s;
338                 } else {
339                         # subject has one REALLY long word, and NOT spam? wtf
340                         @subj = ($l =~ /\A(.{1,72})/);
341                         $subj = $subj[0] . ' ...';
342                 }
343         }
344         $subj;
345 }
346
347 sub enquire {
348         my ($self) = @_;
349         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
350 }
351
352 sub help {
353         my ($self) = @_;
354         $self->qp; # parse altids
355         my @ret = @HELP;
356         if (my $user_pfx = $self->{-user_pfx}) {
357                 push @ret, @$user_pfx;
358         }
359         \@ret;
360 }
361
362 1;