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