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