1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
10 # values for searching
11 use constant TS => 0; # Received: header in Unix time
12 use constant YYYYMMDD => 1; # Date: header for searching in the WWW UI
13 use constant DT => 2; # Date: YYYYMMDDHHMMSS
15 use Search::Xapian qw/:standard/;
16 use PublicInbox::SearchMsg;
17 use PublicInbox::MIME;
18 use PublicInbox::MID qw/id_compress/;
19 use PublicInbox::Over;
21 # This is English-only, everything else is non-standard and may be confused as
22 # a prefix common in patch emails
23 our $REPLY_RE = qr/^re:\s+/i;
24 our $LANG = 'english';
27 # SCHEMA_VERSION history
29 # 1 - subject_path is lower-cased
30 # 2 - subject_path is id_compress in the index, only
31 # 3 - message-ID is compressed if it includes '%' (hack!)
32 # 4 - change "Re: " normalization, avoid circular Reference ghosts
33 # 5 - subject_path drops trailing '.'
34 # 6 - preserve References: order in document data
35 # 7 - remove references and inreplyto terms
36 # 8 - remove redundant/unneeded document data
37 # 9 - disable Message-ID compression (SHA-1)
38 # 10 - optimize doc for NNTP overviews
39 # 11 - merge threads when vivifying ghosts
40 # 12 - change YYYYMMDD value column to numeric
41 # 13 - fix threading for empty References/In-Reply-To
42 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
43 # 14 - fix ghost root vivification
46 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
47 # as it could become a denial-of-service vector
49 # FLAG_PHRASE also seems to cause performance problems sometimes.
50 # TODO: make this an option, maybe?
51 # or make indexlevel=medium as default
52 QP_FLAGS => FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
55 my %bool_pfx_external = (
56 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
59 dfblob => 'XDFPRE XDFPOST',
62 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
64 # for mairix compatibility
66 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
73 b => $non_quoted_body . ' XQUOT',
74 bs => $non_quoted_body . ' XQUOT S',
78 nq => $non_quoted_body,
86 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
89 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
91 's:' => 'match within Subject e.g. s:"a quick brown fox"',
93 date range as YYYYMMDD e.g. d:19931002..20101002
94 Open-ended ranges such as d:19931002.. and d:..20101002
98 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
100 'b:' => 'match within message body, including text attachments',
101 'nq:' => 'match non-quoted text within message body',
102 'q:' => 'match quoted text within message body',
103 'n:' => 'match filename of attachment(s)',
104 't:' => 'match within the To header',
105 'c:' => 'match within the Cc header',
106 'f:' => 'match within the From header',
107 'a:' => 'match within the To, Cc, and From headers',
108 'tc:' => 'match within the To and Cc headers',
109 'bs:' => 'match within the Subject and body',
110 'dfn:' => 'match filename from diff',
111 'dfa:' => 'match diff removed (-) lines',
112 'dfb:' => 'match diff added (+) lines',
113 'dfhh:' => 'match diff hunk header context (usually a function name)',
114 'dfctx:' => 'match diff context lines',
115 'dfpre:' => 'match pre-image git blob ID',
116 'dfpost:' => 'match post-image git blob ID',
117 'dfblob:' => 'match either pre or post-image git blob ID',
123 if ($self->{version} == 1) {
124 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
126 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
127 my $part = $self->{partition};
128 defined $part or die "partition not given";
134 my ($class, $mainrepo, $altid) = @_;
138 $version = $ibx->{version} || 1;
139 $mainrepo = $ibx->{mainrepo};
142 mainrepo => $mainrepo,
148 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
151 foreach my $part (<$dir/*>) {
152 -d $part && $part =~ m!/\d+\z! or next;
154 my $sub = Search::Xapian::Database->new($part);
156 $xdb->add_database($sub);
164 $self->{xdb} = Search::Xapian::Database->new($dir);
166 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
172 $self->{xdb}->reopen;
173 $self; # make chaining easier
178 my ($self, $query_string, $opts) = @_;
180 if ($query_string eq '' && !$opts->{mset}) {
181 $self->{over_ro}->recent($opts);
183 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
184 $opts->{relevance} = 1 unless exists $opts->{relevance};
185 _do_enquire($self, $query, $opts);
190 my ($self, $mid, $prev) = @_;
191 $self->{over_ro}->get_thread($mid, $prev);
195 my ($self, $cb) = @_;
199 eval { @ret = $cb->() };
200 return @ret unless $@;
203 eval { $ret = $cb->() };
204 return $ret unless $@;
206 # Exception: The revision being read has been discarded -
207 # you should call Xapian::Database::reopen()
208 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
209 warn "reopen try #$i on $@\n";
212 warn "ref: ", ref($@), "\n";
216 die "Too many Xapian database modifications in progress\n";
220 my ($self, $query, $opts) = @_;
221 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
225 my ($self, $query, $opts) = @_;
226 my $enquire = Search::Xapian::Enquire->new($self->{xdb});
227 $enquire->set_query($query);
229 my $desc = !$opts->{asc};
230 if (($opts->{mset} || 0) == 2) {
231 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
232 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
233 } elsif ($opts->{relevance}) {
234 $enquire->set_sort_by_relevance_then_value(TS, $desc);
236 $enquire->set_sort_by_value_then_relevance(TS, $desc);
238 my $offset = $opts->{offset} || 0;
239 my $limit = $opts->{limit} || 50;
240 my $mset = $enquire->get_mset($offset, $limit);
241 return $mset if $opts->{mset};
243 PublicInbox::SearchMsg->load_doc($_->get_document);
245 return \@msgs unless wantarray;
247 ($mset->get_matches_estimated, \@msgs)
251 sub stemmer { Search::Xapian::Stem->new($LANG) }
257 my $qp = $self->{query_parser};
261 $qp = Search::Xapian::QueryParser->new;
262 $qp->set_default_op(OP_AND);
263 $qp->set_database($self->{xdb});
264 $qp->set_stemmer($self->stemmer);
265 $qp->set_stemming_strategy(STEM_SOME);
266 $qp->set_max_wildcard_expansion(100);
267 $qp->add_valuerangeprocessor(
268 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
269 $qp->add_valuerangeprocessor(
270 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
272 while (my ($name, $prefix) = each %bool_pfx_external) {
273 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
276 # we do not actually create AltId objects,
277 # just parse the spec to avoid the extra DB handles for now.
278 if (my $altid = $self->{altid}) {
279 my $user_pfx = $self->{-user_pfx} ||= [];
281 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
282 /\Aserial:(\w+):/ or next;
284 push @$user_pfx, "$pfx:", <<EOF;
285 alternate serial number e.g. $pfx:12345 (boolean)
288 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
293 while (my ($name, $prefix) = each %prob_prefix) {
294 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
297 $self->{query_parser} = $qp;
300 # only used for NNTP server
302 my ($self, $beg, $end, $offset) = @_;
303 $self->{over_ro}->query_xover($beg, $end, $offset);
307 my ($self, $ts, $prev) = @_;
308 $self->{over_ro}->query_ts($ts, $prev);
312 my ($self, $num) = @_;
313 $self->{over_ro}->get_art($num);
317 my ($self, $mid, $id, $prev) = @_;
318 $self->{over_ro}->next_by_mid($mid, $id, $prev);
321 # normalize subjects so they are suitable as pathnames for URLs
322 # XXX: consider for removal
325 $subj = subject_normalized($subj);
326 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
330 sub subject_normalized {
332 $subj =~ s/\A\s+//s; # no leading space
333 $subj =~ s/\s+\z//s; # no trailing space
334 $subj =~ s/\s+/ /gs; # no redundant spaces
335 $subj =~ s/\.+\z//; # no trailing '.'
336 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
342 $self->qp; # parse altids
344 if (my $user_pfx = $self->{-user_pfx}) {
345 push @ret, @$user_pfx;