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; # 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
17 use Search::Xapian qw/:standard/;
18 use PublicInbox::SearchMsg;
19 use PublicInbox::MIME;
20 use PublicInbox::MID qw/mid_clean id_compress/;
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';
28 # SCHEMA_VERSION history
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 # 13 - fix threading for empty References/In-Reply-To
43 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
44 # 14 - fix ghost root vivification
47 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
48 # as it could become a denial-of-service vector
49 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
53 my %bool_pfx_internal = (
54 type => 'T', # "mail" or "ghost"
55 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
58 my %bool_pfx_external = (
59 mid => 'XMID', # Message-ID (full/exact)
63 # for mairix compatibility
65 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
85 dfblob => 'XDFPRE XDFPOST',
88 '' => 'XM S A XNQ XQUOT XFN',
91 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
93 's:' => 'match within Subject e.g. s:"a quick brown fox"',
95 date range as YYYYMMDD e.g. d:19931002..20101002
96 Open-ended ranges such as d:19931002.. and d:..20101002
99 'b:' => 'match within message body, including text attachments',
100 'nq:' => 'match non-quoted text within message body',
101 'q:' => 'match quoted text within message body',
102 'n:' => 'match filename of attachment(s)',
103 't:' => 'match within the To header',
104 'c:' => 'match within the Cc header',
105 'f:' => 'match within the From header',
106 'a:' => 'match within the To, Cc, and From headers',
107 'tc:' => 'match within the To and Cc headers',
108 'bs:' => 'match within the Subject and body',
109 'dfn:' => 'match filename from diff',
110 'dfa:' => 'match diff removed (-) lines',
111 'dfb:' => 'match diff added (+) lines',
112 'dfhh:' => 'match diff hunk header context (usually a function name)',
113 'dfctx:' => 'match diff context lines',
114 'dfpre:' => 'match pre-image git blob ID',
115 'dfpost:' => 'match post-image git blob ID',
116 'dfblob:' => 'match either pre or post-image git blob ID',
120 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
124 if ($self->{version} == 1) {
125 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
127 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
128 my $part = $self->{partition};
129 defined $part or die "partition not given";
135 my ($class, $mainrepo, $altid) = @_;
139 $version = $ibx->{version} || 1;
140 $mainrepo = $ibx->{mainrepo};
143 mainrepo => $mainrepo,
148 my $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);
162 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
164 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
171 $self->{xdb}->reopen;
172 if (my $skel = $self->{skel}) {
179 my ($self, $query_string, $opts) = @_;
183 unless ($query_string eq '') {
184 $query = $self->qp->parse_query($query_string, QP_FLAGS);
185 $opts->{relevance} = 1 unless exists $opts->{relevance};
188 _do_enquire($self, $query, $opts);
192 my ($self, $mid, $opts) = @_;
193 my $smsg = retry_reopen($self, sub { lookup_skeleton($self, $mid) });
195 return { total => 0, msgs => [] } unless $smsg;
196 my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
197 my $path = $smsg->path;
198 if (defined $path && $path ne '') {
199 my $path = id_compress($smsg->path);
200 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
201 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
204 $opts->{limit} ||= 1000;
206 # always sort threads by timestamp, this makes life easier
207 # for the threading algorithm (in SearchThread.pm)
209 $opts->{enquire} = enquire_skel($self);
210 _do_enquire($self, $qtid, $opts);
214 my ($self, $cb) = @_;
217 eval { $ret = $cb->() };
218 return $ret unless $@;
219 # Exception: The revision being read has been discarded -
220 # you should call Xapian::Database::reopen()
221 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
224 warn "ref: ", ref($@), "\n";
231 my ($self, $query, $opts) = @_;
232 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
236 my ($self, $query, $opts) = @_;
237 my $enquire = $opts->{enquire} || enquire($self);
238 if (defined $query) {
239 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
241 $query = $mail_query;
243 $enquire->set_query($query);
245 my $desc = !$opts->{asc};
246 if ($opts->{relevance}) {
247 $enquire->set_sort_by_relevance_then_value(TS, $desc);
248 } elsif ($opts->{num}) {
249 $enquire->set_sort_by_value(NUM, 0);
251 $enquire->set_sort_by_value_then_relevance(TS, $desc);
253 my $offset = $opts->{offset} || 0;
254 my $limit = $opts->{limit} || 50;
255 my $mset = $enquire->get_mset($offset, $limit);
256 return $mset if $opts->{mset};
258 PublicInbox::SearchMsg->load_doc($_->get_document);
261 { total => $mset->get_matches_estimated, msgs => \@msgs }
265 sub stemmer { Search::Xapian::Stem->new($LANG) }
271 my $qp = $self->{query_parser};
275 $qp = Search::Xapian::QueryParser->new;
276 $qp->set_default_op(OP_AND);
277 $qp->set_database($self->{xdb});
278 $qp->set_stemmer($self->stemmer);
279 $qp->set_stemming_strategy(STEM_SOME);
280 $qp->add_valuerangeprocessor(
281 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
283 while (my ($name, $prefix) = each %bool_pfx_external) {
284 $qp->add_boolean_prefix($name, $prefix);
287 # we do not actually create AltId objects,
288 # just parse the spec to avoid the extra DB handles for now.
289 if (my $altid = $self->{altid}) {
290 my $user_pfx = $self->{-user_pfx} ||= [];
292 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
293 /\Aserial:(\w+):/ or next;
295 push @$user_pfx, "$pfx:", <<EOF;
296 alternate serial number e.g. $pfx:12345 (boolean)
299 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
304 while (my ($name, $prefix) = each %prob_prefix) {
305 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
308 $self->{query_parser} = $qp;
311 sub num_range_processor {
312 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
315 # only used for NNTP server
317 my ($self, $beg, $end, $offset) = @_;
318 my $qp = Search::Xapian::QueryParser->new;
319 $qp->set_database($self->{skel} || $self->{xdb});
320 $qp->add_valuerangeprocessor($self->num_range_processor);
321 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
324 enquire => enquire_skel($self),
329 _do_enquire($self, $query, $opts);
332 sub lookup_skeleton {
333 my ($self, $mid) = @_;
334 my $skel = $self->{skel} or return lookup_message($self, $mid);
335 $mid = mid_clean($mid);
336 my $term = 'XMID' . $mid;
338 my $beg = $skel->postlist_begin($term);
339 if ($beg != $skel->postlist_end($term)) {
340 my $doc_id = $beg->get_docid;
341 if (defined $doc_id) {
343 my $doc = $skel->get_document($doc_id);
344 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
345 $smsg->{doc_id} = $doc_id;
352 my ($self, $mid) = @_;
353 $mid = mid_clean($mid);
355 my $doc_id = $self->find_first_doc_id('XMID' . $mid);
357 if (defined $doc_id) {
359 my $doc = $self->{xdb}->get_document($doc_id);
360 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
361 $smsg->{doc_id} = $doc_id;
366 sub lookup_mail { # no ghosts!
367 my ($self, $mid) = @_;
368 retry_reopen($self, sub {
369 my $smsg = lookup_message($self, $mid) or return;
374 sub find_unique_doc_id {
375 my ($self, $termval) = @_;
377 my ($begin, $end) = $self->find_doc_ids($termval);
379 return undef if $begin->equal($end); # not found
381 my $rv = $begin->get_docid;
385 $begin->equal($end) or die "Term '$termval' is not unique\n";
389 # returns begin and end PostingIterator
391 my ($self, $termval) = @_;
392 my $db = $self->{xdb};
394 ($db->postlist_begin($termval), $db->postlist_end($termval));
397 sub find_first_doc_id {
398 my ($self, $termval) = @_;
400 my ($begin, $end) = $self->find_doc_ids($termval);
402 return undef if $begin->equal($end); # not found
407 # normalize subjects so they are suitable as pathnames for URLs
408 # XXX: consider for removal
411 $subj = subject_normalized($subj);
412 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
416 sub subject_normalized {
418 $subj =~ s/\A\s+//s; # no leading space
419 $subj =~ s/\s+\z//s; # no trailing space
420 $subj =~ s/\s+/ /gs; # no redundant spaces
421 $subj =~ s/\.+\z//; # no trailing '.'
422 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
428 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
433 if (my $skel = $self->{skel}) {
434 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
442 $self->qp; # parse altids
444 if (my $user_pfx = $self->{-user_pfx}) {
445 push @ret, @$user_pfx;