]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: fix help message for searching within quotes
[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 PublicInbox::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         # 12 - change YYYYMMDD value column to numeric
42         # 13 - fix threading for empty References/In-Reply-To
43         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
44         SCHEMA_VERSION => 13,
45
46         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
47         # as it could become a denial-of-service vector
48         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
49 };
50
51 # setup prefixes
52 my %bool_pfx_internal = (
53         type => 'T', # "mail" or "ghost"
54         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
55 );
56
57 my %bool_pfx_external = (
58         # do we still need these? probably not..
59         path => 'XPATH',
60         mid => 'Q', # uniQue id (Message-ID)
61 );
62
63 my %prob_prefix = (
64         # for mairix compatibility
65         s => 'S',
66         m => 'XMID', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
67         f => 'A',
68         t => 'XTO',
69         tc => 'XTO XCC',
70         c => 'XCC',
71         tcf => 'XTO XCC A',
72         a => 'XTO XCC A',
73         b => 'XNQ XQUOT',
74         bs => 'XNQ XQUOT S',
75         n => 'XFN',
76
77         q => 'XQUOT',
78         nq => 'XNQ',
79
80         # default:
81         '' => 'XMID S A XNQ XQUOT XFN',
82 );
83
84 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
85 our @HELP = (
86         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
87         'd:' => <<EOF,
88 date range as YYYYMMDD  e.g. d:19931002..20101002
89 Open-ended ranges such as d:19931002.. and d:..20101002
90 are also supported
91 EOF
92         'b:' => 'match within message body, including text attachments',
93         'nq:' => 'match non-quoted text within message body',
94         'q:' => 'match quoted text within message body',
95         'n:' => 'match filename of attachment(s)',
96         't:' => 'match within the To header',
97         'c:' => 'match within the Cc header',
98         'f:' => 'match within the From header',
99         'a:' => 'match within the To, Cc, and From headers',
100         'tc:' => 'match within the To and Cc headers',
101         'bs:' => 'match within the Subject and body',
102 );
103 chomp @HELP;
104 # TODO:
105 # df (filenames from diff)
106 # da (diff a/ removed lines)
107 # db (diff b/ added lines)
108
109 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
110
111 sub xpfx { $all_pfx{$_[0]} }
112
113 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
114
115 sub xdir {
116         my (undef, $git_dir) = @_;
117         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
118 }
119
120 sub new {
121         my ($class, $git_dir, $altid) = @_;
122         my $dir = $class->xdir($git_dir);
123         my $db = Search::Xapian::Database->new($dir);
124         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
125 }
126
127 sub reopen { $_[0]->{xdb}->reopen }
128
129 # read-only
130 sub query {
131         my ($self, $query_string, $opts) = @_;
132         my $query;
133
134         $opts ||= {};
135         unless ($query_string eq '') {
136                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
137                 $opts->{relevance} = 1 unless exists $opts->{relevance};
138         }
139
140         _do_enquire($self, $query, $opts);
141 }
142
143 sub get_thread {
144         my ($self, $mid, $opts) = @_;
145         my $smsg = eval { $self->lookup_message($mid) };
146
147         return { total => 0, msgs => [] } unless $smsg;
148         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
149         my $path = $smsg->path;
150         if (defined $path && $path ne '') {
151                 my $path = id_compress($smsg->path);
152                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
153                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
154         }
155         $opts ||= {};
156         $opts->{limit} ||= 1000;
157
158         # always sort threads by timestamp, this makes life easier
159         # for the threading algorithm (in SearchThread.pm)
160         $opts->{asc} = 1;
161
162         _do_enquire($self, $qtid, $opts);
163 }
164
165 sub retry_reopen {
166         my ($self, $cb) = @_;
167         my $ret;
168         for (1..10) {
169                 eval { $ret = $cb->() };
170                 return $ret unless $@;
171                 # Exception: The revision being read has been discarded -
172                 # you should call Xapian::Database::reopen()
173                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
174                         reopen($self);
175                 } else {
176                         die;
177                 }
178         }
179 }
180
181 sub _do_enquire {
182         my ($self, $query, $opts) = @_;
183         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
184 }
185
186 sub _enquire_once {
187         my ($self, $query, $opts) = @_;
188         my $enquire = $self->enquire;
189         if (defined $query) {
190                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
191         } else {
192                 $query = $mail_query;
193         }
194         $enquire->set_query($query);
195         $opts ||= {};
196         my $desc = !$opts->{asc};
197         if ($opts->{relevance}) {
198                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
199         } elsif ($opts->{num}) {
200                 $enquire->set_sort_by_value(NUM, 0);
201         } else {
202                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
203         }
204         my $offset = $opts->{offset} || 0;
205         my $limit = $opts->{limit} || 50;
206         my $mset = $enquire->get_mset($offset, $limit);
207         return $mset if $opts->{mset};
208         my @msgs = map {
209                 PublicInbox::SearchMsg->load_doc($_->get_document);
210         } $mset->items;
211
212         { total => $mset->get_matches_estimated, msgs => \@msgs }
213 }
214
215 # read-write
216 sub stemmer { Search::Xapian::Stem->new($LANG) }
217
218 # read-only
219 sub qp {
220         my ($self) = @_;
221
222         my $qp = $self->{query_parser};
223         return $qp if $qp;
224
225         # new parser
226         $qp = Search::Xapian::QueryParser->new;
227         $qp->set_default_op(OP_AND);
228         $qp->set_database($self->{xdb});
229         $qp->set_stemmer($self->stemmer);
230         $qp->set_stemming_strategy(STEM_SOME);
231         $qp->add_valuerangeprocessor(
232                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
233
234         while (my ($name, $prefix) = each %bool_pfx_external) {
235                 $qp->add_boolean_prefix($name, $prefix);
236         }
237
238         # we do not actually create AltId objects,
239         # just parse the spec to avoid the extra DB handles for now.
240         if (my $altid = $self->{altid}) {
241                 my $user_pfx = $self->{-user_pfx} ||= [];
242                 for (@$altid) {
243                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
244                         /\Aserial:(\w+):/ or next;
245                         my $pfx = $1;
246                         push @$user_pfx, "$pfx:", <<EOF;
247 alternate serial number  e.g. $pfx:12345 (boolean)
248 EOF
249                         # gmane => XGMANE
250                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
251                 }
252                 chomp @$user_pfx;
253         }
254
255         while (my ($name, $prefix) = each %prob_prefix) {
256                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
257         }
258
259         $self->{query_parser} = $qp;
260 }
261
262 sub num_range_processor {
263         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
264 }
265
266 # only used for NNTP server
267 sub query_xover {
268         my ($self, $beg, $end, $offset) = @_;
269         my $qp = Search::Xapian::QueryParser->new;
270         $qp->set_database($self->{xdb});
271         $qp->add_valuerangeprocessor($self->num_range_processor);
272         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
273
274         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
275 }
276
277 sub lookup_message {
278         my ($self, $mid) = @_;
279         $mid = mid_clean($mid);
280
281         my $doc_id = $self->find_unique_doc_id('mid', $mid);
282         my $smsg;
283         if (defined $doc_id) {
284                 # raises on error:
285                 my $doc = $self->{xdb}->get_document($doc_id);
286                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
287                 $smsg->{doc_id} = $doc_id;
288         }
289         $smsg;
290 }
291
292 sub lookup_mail { # no ghosts!
293         my ($self, $mid) = @_;
294         retry_reopen($self, sub {
295                 my $smsg = lookup_message($self, $mid) or return;
296                 PublicInbox::SearchMsg->load_doc($smsg->{doc});
297         });
298 }
299
300 sub find_unique_doc_id {
301         my ($self, $term, $value) = @_;
302
303         my ($begin, $end) = $self->find_doc_ids($term, $value);
304
305         return undef if $begin->equal($end); # not found
306
307         my $rv = $begin->get_docid;
308
309         # sanity check
310         $begin->inc;
311         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
312         $rv;
313 }
314
315 # returns begin and end PostingIterator
316 sub find_doc_ids {
317         my ($self, $term, $value) = @_;
318
319         $self->find_doc_ids_for_term(xpfx($term) . $value);
320 }
321
322 # returns begin and end PostingIterator
323 sub find_doc_ids_for_term {
324         my ($self, $term) = @_;
325         my $db = $self->{xdb};
326
327         ($db->postlist_begin($term), $db->postlist_end($term));
328 }
329
330 # normalize subjects so they are suitable as pathnames for URLs
331 # XXX: consider for removal
332 sub subject_path {
333         my $subj = pop;
334         $subj = subject_normalized($subj);
335         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
336         lc($subj);
337 }
338
339 sub subject_normalized {
340         my $subj = pop;
341         $subj =~ s/\A\s+//s; # no leading space
342         $subj =~ s/\s+\z//s; # no trailing space
343         $subj =~ s/\s+/ /gs; # no redundant spaces
344         $subj =~ s/\.+\z//; # no trailing '.'
345         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
346         $subj;
347 }
348
349 sub enquire {
350         my ($self) = @_;
351         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
352 }
353
354 sub help {
355         my ($self) = @_;
356         $self->qp; # parse altids
357         my @ret = @HELP;
358         if (my $user_pfx = $self->{-user_pfx}) {
359                 push @ret, @$user_pfx;
360         }
361         \@ret;
362 }
363
364 1;