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
48 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
51 my %bool_pfx_external = (
52 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
55 dfblob => 'XDFPRE XDFPOST',
58 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
60 # for mairix compatibility
62 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
69 b => $non_quoted_body . ' XQUOT',
70 bs => $non_quoted_body . ' XQUOT S',
74 nq => $non_quoted_body,
82 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
85 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
87 's:' => 'match within Subject e.g. s:"a quick brown fox"',
89 date range as YYYYMMDD e.g. d:19931002..20101002
90 Open-ended ranges such as d:19931002.. and d:..20101002
94 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
96 'b:' => 'match within message body, including text attachments',
97 'nq:' => 'match non-quoted text within message body',
98 'q:' => 'match quoted text within message body',
99 'n:' => 'match filename of attachment(s)',
100 't:' => 'match within the To header',
101 'c:' => 'match within the Cc header',
102 'f:' => 'match within the From header',
103 'a:' => 'match within the To, Cc, and From headers',
104 'tc:' => 'match within the To and Cc headers',
105 'bs:' => 'match within the Subject and body',
106 'dfn:' => 'match filename from diff',
107 'dfa:' => 'match diff removed (-) lines',
108 'dfb:' => 'match diff added (+) lines',
109 'dfhh:' => 'match diff hunk header context (usually a function name)',
110 'dfctx:' => 'match diff context lines',
111 'dfpre:' => 'match pre-image git blob ID',
112 'dfpost:' => 'match post-image git blob ID',
113 'dfblob:' => 'match either pre or post-image git blob ID',
119 if ($self->{version} == 1) {
120 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
122 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
123 my $part = $self->{partition};
124 defined $part or die "partition not given";
130 my ($class, $mainrepo, $altid) = @_;
134 $version = $ibx->{version} || 1;
135 $mainrepo = $ibx->{mainrepo};
138 mainrepo => $mainrepo,
144 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
147 foreach my $part (<$dir/*>) {
148 -d $part && $part =~ m!/\d+\z! or next;
150 my $sub = Search::Xapian::Database->new($part);
152 $xdb->add_database($sub);
160 $self->{xdb} = Search::Xapian::Database->new($dir);
162 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
168 $self->{xdb}->reopen;
169 $self; # make chaining easier
174 my ($self, $query_string, $opts) = @_;
176 if ($query_string eq '' && !$opts->{mset}) {
177 $self->{over_ro}->recent($opts);
179 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
180 $opts->{relevance} = 1 unless exists $opts->{relevance};
181 _do_enquire($self, $query, $opts);
186 my ($self, $mid, $prev) = @_;
187 $self->{over_ro}->get_thread($mid, $prev);
191 my ($self, $cb) = @_;
195 eval { @ret = $cb->() };
196 return @ret unless $@;
199 eval { $ret = $cb->() };
200 return $ret unless $@;
202 # Exception: The revision being read has been discarded -
203 # you should call Xapian::Database::reopen()
204 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
205 warn "reopen try #$i on $@\n";
208 warn "ref: ", ref($@), "\n";
212 die "Too many Xapian database modifications in progress\n";
216 my ($self, $query, $opts) = @_;
217 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
221 my ($self, $query, $opts) = @_;
222 my $enquire = Search::Xapian::Enquire->new($self->{xdb});
223 $enquire->set_query($query);
225 my $desc = !$opts->{asc};
226 if (($opts->{mset} || 0) == 2) {
227 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
228 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
229 } elsif ($opts->{relevance}) {
230 $enquire->set_sort_by_relevance_then_value(TS, $desc);
232 $enquire->set_sort_by_value_then_relevance(TS, $desc);
234 my $offset = $opts->{offset} || 0;
235 my $limit = $opts->{limit} || 50;
236 my $mset = $enquire->get_mset($offset, $limit);
237 return $mset if $opts->{mset};
239 PublicInbox::SearchMsg->load_doc($_->get_document);
241 return \@msgs unless wantarray;
243 ($mset->get_matches_estimated, \@msgs)
247 sub stemmer { Search::Xapian::Stem->new($LANG) }
253 my $qp = $self->{query_parser};
257 $qp = Search::Xapian::QueryParser->new;
258 $qp->set_default_op(OP_AND);
259 $qp->set_database($self->{xdb});
260 $qp->set_stemmer($self->stemmer);
261 $qp->set_stemming_strategy(STEM_SOME);
262 $qp->set_max_wildcard_expansion(100);
263 $qp->add_valuerangeprocessor(
264 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
265 $qp->add_valuerangeprocessor(
266 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
268 while (my ($name, $prefix) = each %bool_pfx_external) {
269 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
272 # we do not actually create AltId objects,
273 # just parse the spec to avoid the extra DB handles for now.
274 if (my $altid = $self->{altid}) {
275 my $user_pfx = $self->{-user_pfx} ||= [];
277 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
278 /\Aserial:(\w+):/ or next;
280 push @$user_pfx, "$pfx:", <<EOF;
281 alternate serial number e.g. $pfx:12345 (boolean)
284 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
289 while (my ($name, $prefix) = each %prob_prefix) {
290 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
293 $self->{query_parser} = $qp;
296 # only used for NNTP server
298 my ($self, $beg, $end, $offset) = @_;
299 $self->{over_ro}->query_xover($beg, $end, $offset);
303 my ($self, $ts, $prev) = @_;
304 $self->{over_ro}->query_ts($ts, $prev);
308 my ($self, $num) = @_;
309 $self->{over_ro}->get_art($num);
313 my ($self, $mid, $id, $prev) = @_;
314 $self->{over_ro}->next_by_mid($mid, $id, $prev);
317 # normalize subjects so they are suitable as pathnames for URLs
318 # XXX: consider for removal
321 $subj = subject_normalized($subj);
322 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
326 sub subject_normalized {
328 $subj =~ s/\A\s+//s; # no leading space
329 $subj =~ s/\s+\z//s; # no trailing space
330 $subj =~ s/\s+/ /gs; # no redundant spaces
331 $subj =~ s/\.+\z//; # no trailing '.'
332 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
338 $self->qp; # parse altids
340 if (my $user_pfx = $self->{-user_pfx}) {
341 push @ret, @$user_pfx;