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