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 $LANG = 'english';
26 # SCHEMA_VERSION history
28 # 1 - subject_path is lower-cased
29 # 2 - subject_path is id_compress in the index, only
30 # 3 - message-ID is compressed if it includes '%' (hack!)
31 # 4 - change "Re: " normalization, avoid circular Reference ghosts
32 # 5 - subject_path drops trailing '.'
33 # 6 - preserve References: order in document data
34 # 7 - remove references and inreplyto terms
35 # 8 - remove redundant/unneeded document data
36 # 9 - disable Message-ID compression (SHA-1)
37 # 10 - optimize doc for NNTP overviews
38 # 11 - merge threads when vivifying ghosts
39 # 12 - change YYYYMMDD value column to numeric
40 # 13 - fix threading for empty References/In-Reply-To
41 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
42 # 14 - fix ghost root vivification
45 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
46 # as it could become a denial-of-service vector
47 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
50 my %bool_pfx_external = (
51 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
54 dfblob => 'XDFPRE XDFPOST',
57 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
59 # for mairix compatibility
61 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
68 b => $non_quoted_body . ' XQUOT',
69 bs => $non_quoted_body . ' XQUOT S',
73 nq => $non_quoted_body,
81 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
84 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
86 's:' => 'match within Subject e.g. s:"a quick brown fox"',
88 date range as YYYYMMDD e.g. d:19931002..20101002
89 Open-ended ranges such as d:19931002.. and d:..20101002
93 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
95 'b:' => 'match within message body, including text attachments',
96 'nq:' => 'match non-quoted text within message body',
97 'q:' => 'match quoted text within message body',
98 'n:' => 'match filename of attachment(s)',
99 't:' => 'match within the To header',
100 'c:' => 'match within the Cc header',
101 'f:' => 'match within the From header',
102 'a:' => 'match within the To, Cc, and From headers',
103 'tc:' => 'match within the To and Cc headers',
104 'bs:' => 'match within the Subject and body',
105 'dfn:' => 'match filename from diff',
106 'dfa:' => 'match diff removed (-) lines',
107 'dfb:' => 'match diff added (+) lines',
108 'dfhh:' => 'match diff hunk header context (usually a function name)',
109 'dfctx:' => 'match diff context lines',
110 'dfpre:' => 'match pre-image git blob ID',
111 'dfpost:' => 'match post-image git blob ID',
112 'dfblob:' => 'match either pre or post-image git blob ID',
118 if ($self->{version} == 1) {
119 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
121 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
122 my $part = $self->{partition};
123 defined $part or die "partition not given";
129 my ($class, $mainrepo, $altid) = @_;
133 $version = $ibx->{version} || 1;
134 $mainrepo = $ibx->{mainrepo};
137 mainrepo => $mainrepo,
143 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
146 foreach my $part (<$dir/*>) {
147 -d $part && $part =~ m!/\d+\z! or next;
149 my $sub = Search::Xapian::Database->new($part);
151 $xdb->add_database($sub);
159 $self->{xdb} = Search::Xapian::Database->new($dir);
161 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
167 $self->{xdb}->reopen;
168 $self; # make chaining easier
173 my ($self, $query_string, $opts) = @_;
175 if ($query_string eq '' && !$opts->{mset}) {
176 $self->{over_ro}->recent($opts);
178 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
179 $opts->{relevance} = 1 unless exists $opts->{relevance};
180 _do_enquire($self, $query, $opts);
185 my ($self, $cb) = @_;
189 eval { @ret = $cb->() };
190 return @ret unless $@;
193 eval { $ret = $cb->() };
194 return $ret unless $@;
196 # Exception: The revision being read has been discarded -
197 # you should call Xapian::Database::reopen()
198 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
199 warn "reopen try #$i on $@\n";
202 warn "ref: ", ref($@), "\n";
206 die "Too many Xapian database modifications in progress\n";
210 my ($self, $query, $opts) = @_;
211 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
215 my ($self, $query, $opts) = @_;
216 my $enquire = Search::Xapian::Enquire->new($self->{xdb});
217 $enquire->set_query($query);
219 my $desc = !$opts->{asc};
220 if (($opts->{mset} || 0) == 2) {
221 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
222 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
223 } elsif ($opts->{relevance}) {
224 $enquire->set_sort_by_relevance_then_value(TS, $desc);
226 $enquire->set_sort_by_value_then_relevance(TS, $desc);
228 my $offset = $opts->{offset} || 0;
229 my $limit = $opts->{limit} || 50;
230 my $mset = $enquire->get_mset($offset, $limit);
231 return $mset if $opts->{mset};
233 PublicInbox::SearchMsg->load_doc($_->get_document);
235 return \@msgs unless wantarray;
237 ($mset->get_matches_estimated, \@msgs)
241 sub stemmer { Search::Xapian::Stem->new($LANG) }
247 my $qp = $self->{query_parser};
251 $qp = Search::Xapian::QueryParser->new;
252 $qp->set_default_op(OP_AND);
253 $qp->set_database($self->{xdb});
254 $qp->set_stemmer($self->stemmer);
255 $qp->set_stemming_strategy(STEM_SOME);
256 $qp->set_max_wildcard_expansion(100);
257 $qp->add_valuerangeprocessor(
258 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
259 $qp->add_valuerangeprocessor(
260 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
262 while (my ($name, $prefix) = each %bool_pfx_external) {
263 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
266 # we do not actually create AltId objects,
267 # just parse the spec to avoid the extra DB handles for now.
268 if (my $altid = $self->{altid}) {
269 my $user_pfx = $self->{-user_pfx} ||= [];
271 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
272 /\Aserial:(\w+):/ or next;
274 push @$user_pfx, "$pfx:", <<EOF;
275 alternate serial number e.g. $pfx:12345 (boolean)
278 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
283 while (my ($name, $prefix) = each %prob_prefix) {
284 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
287 $self->{query_parser} = $qp;
291 my ($self, $num) = @_;
292 $self->{over_ro}->get_art($num);
297 $self->qp; # parse altids
299 if (my $user_pfx = $self->{-user_pfx}) {
300 push @ret, @$user_pfx;