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 => 'Q', # Message-ID (full/exact), this is mostly uniQue
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 dfblob => 'XDFPRE XDFPOST',
89 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
92 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
94 's:' => 'match within Subject e.g. s:"a quick brown fox"',
96 date range as YYYYMMDD e.g. d:19931002..20101002
97 Open-ended ranges such as d:19931002.. and d:..20101002
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',
121 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
125 if ($self->{version} == 1) {
126 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
128 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
129 my $part = $self->{partition};
130 defined $part or die "partition not given";
136 my ($class, $mainrepo, $altid) = @_;
140 $version = $ibx->{version} || 1;
141 $mainrepo = $ibx->{mainrepo};
144 mainrepo => $mainrepo,
149 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
152 foreach my $part (<$dir/*>) {
153 -d $part && $part =~ m!/\d+\z! or next;
155 my $sub = Search::Xapian::Database->new($part);
157 $xdb->add_database($sub);
163 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
165 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
172 $self->{xdb}->reopen;
173 if (my $skel = $self->{skel}) {
180 my ($self, $query_string, $opts) = @_;
184 unless ($query_string eq '') {
185 $query = $self->qp->parse_query($query_string, QP_FLAGS);
186 $opts->{relevance} = 1 unless exists $opts->{relevance};
189 _do_enquire($self, $query, $opts);
193 my ($self, $mid, $opts) = @_;
194 my $smsg = retry_reopen($self, sub { lookup_skeleton($self, $mid) });
196 return { total => 0, msgs => [] } unless $smsg;
197 my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
198 my $path = $smsg->path;
199 if (defined $path && $path ne '') {
200 my $path = id_compress($smsg->path);
201 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
202 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
205 $opts->{limit} ||= 1000;
207 # always sort threads by timestamp, this makes life easier
208 # for the threading algorithm (in SearchThread.pm)
210 $opts->{enquire} = enquire_skel($self);
211 _do_enquire($self, $qtid, $opts);
215 my ($self, $cb) = @_;
218 eval { $ret = $cb->() };
219 return $ret unless $@;
220 # Exception: The revision being read has been discarded -
221 # you should call Xapian::Database::reopen()
222 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
225 warn "ref: ", ref($@), "\n";
232 my ($self, $query, $opts) = @_;
233 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
237 my ($self, $query, $opts) = @_;
238 my $enquire = $opts->{enquire} || enquire($self);
239 if (defined $query) {
240 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
242 $query = $mail_query;
244 $enquire->set_query($query);
246 my $desc = !$opts->{asc};
247 if ($opts->{relevance}) {
248 $enquire->set_sort_by_relevance_then_value(TS, $desc);
249 } elsif ($opts->{num}) {
250 $enquire->set_sort_by_value(NUM, 0);
252 $enquire->set_sort_by_value_then_relevance(TS, $desc);
254 my $offset = $opts->{offset} || 0;
255 my $limit = $opts->{limit} || 50;
256 my $mset = $enquire->get_mset($offset, $limit);
257 return $mset if $opts->{mset};
259 PublicInbox::SearchMsg->load_doc($_->get_document);
262 { total => $mset->get_matches_estimated, msgs => \@msgs }
266 sub stemmer { Search::Xapian::Stem->new($LANG) }
272 my $qp = $self->{query_parser};
276 $qp = Search::Xapian::QueryParser->new;
277 $qp->set_default_op(OP_AND);
278 $qp->set_database($self->{xdb});
279 $qp->set_stemmer($self->stemmer);
280 $qp->set_stemming_strategy(STEM_SOME);
281 $qp->add_valuerangeprocessor(
282 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
284 while (my ($name, $prefix) = each %bool_pfx_external) {
285 $qp->add_boolean_prefix($name, $prefix);
288 # we do not actually create AltId objects,
289 # just parse the spec to avoid the extra DB handles for now.
290 if (my $altid = $self->{altid}) {
291 my $user_pfx = $self->{-user_pfx} ||= [];
293 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
294 /\Aserial:(\w+):/ or next;
296 push @$user_pfx, "$pfx:", <<EOF;
297 alternate serial number e.g. $pfx:12345 (boolean)
300 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
305 while (my ($name, $prefix) = each %prob_prefix) {
306 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
309 $self->{query_parser} = $qp;
312 sub num_range_processor {
313 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
316 # only used for NNTP server
318 my ($self, $beg, $end, $offset) = @_;
319 my $qp = Search::Xapian::QueryParser->new;
320 $qp->set_database($self->{skel} || $self->{xdb});
321 $qp->add_valuerangeprocessor($self->num_range_processor);
322 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
325 enquire => enquire_skel($self),
330 _do_enquire($self, $query, $opts);
334 my ($self, $ts, $opts) = @_;
335 my $qp = $self->{qp_ts} ||= eval {
336 my $q = Search::Xapian::QueryParser->new;
337 $q->set_database($self->{skel} || $self->{xdb});
338 $q->add_valuerangeprocessor(
339 Search::Xapian::NumberValueRangeProcessor->new(TS));
342 my $query = $qp->parse_query($ts, QP_FLAGS);
343 $opts->{enquire} = enquire_skel($self);
344 _do_enquire($self, $query, $opts);
347 sub lookup_skeleton {
348 my ($self, $mid) = @_;
349 my $skel = $self->{skel} or return lookup_message($self, $mid);
350 $mid = mid_clean($mid);
351 my $term = 'Q' . $mid;
353 my $beg = $skel->postlist_begin($term);
354 if ($beg != $skel->postlist_end($term)) {
355 my $doc_id = $beg->get_docid;
356 if (defined $doc_id) {
358 my $doc = $skel->get_document($doc_id);
359 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
360 $smsg->{doc_id} = $doc_id;
367 my ($self, $mid) = @_;
368 $mid = mid_clean($mid);
370 my $doc_id = $self->find_first_doc_id('Q' . $mid);
372 if (defined $doc_id) {
374 my $doc = $self->{xdb}->get_document($doc_id);
375 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
376 $smsg->{doc_id} = $doc_id;
381 sub lookup_mail { # no ghosts!
382 my ($self, $mid) = @_;
383 retry_reopen($self, sub {
384 my $smsg = lookup_skeleton($self, $mid) or return;
390 my ($self, $num) = @_;
391 my $term = 'XNUM'.$num;
394 retry_reopen($self, sub {
395 my $db = $self->{skel} || $self->{xdb};
396 my $head = $db->postlist_begin($term);
397 return if $head == $db->postlist_end($term);
398 my $doc_id = $head->get_docid;
399 return unless defined $doc_id;
401 my $doc = $db->get_document($doc_id);
402 $smsg = PublicInbox::SearchMsg->wrap($doc);
404 $smsg->{doc_id} = $doc_id;
410 sub each_smsg_by_mid {
411 my ($self, $mid, $cb) = @_;
412 # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
413 # interface will need it...
414 my $db = $self->{skel} || $self->{xdb};
415 my $term = 'Q' . $mid;
416 my $head = $db->postlist_begin($term);
417 my $tail = $db->postlist_end($term);
418 for (; $head->nequal($tail); $head->inc) {
419 my $doc_id = $head->get_docid;
420 my $doc = $db->get_document($doc_id);
421 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
422 $smsg->{doc_id} = $doc_id;
423 $cb->($smsg) or return;
427 sub find_unique_doc_id {
428 my ($self, $termval) = @_;
430 my ($begin, $end) = $self->find_doc_ids($termval);
432 return undef if $begin->equal($end); # not found
434 my $rv = $begin->get_docid;
438 $begin->equal($end) or die "Term '$termval' is not unique\n";
442 # returns begin and end PostingIterator
444 my ($self, $termval) = @_;
445 my $db = $self->{xdb};
447 ($db->postlist_begin($termval), $db->postlist_end($termval));
450 sub find_first_doc_id {
451 my ($self, $termval) = @_;
453 my ($begin, $end) = $self->find_doc_ids($termval);
455 return undef if $begin->equal($end); # not found
460 # normalize subjects so they are suitable as pathnames for URLs
461 # XXX: consider for removal
464 $subj = subject_normalized($subj);
465 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
469 sub subject_normalized {
471 $subj =~ s/\A\s+//s; # no leading space
472 $subj =~ s/\s+\z//s; # no trailing space
473 $subj =~ s/\s+/ /gs; # no redundant spaces
474 $subj =~ s/\.+\z//; # no trailing '.'
475 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
481 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
486 if (my $skel = $self->{skel}) {
487 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
495 $self->qp; # parse altids
497 if (my $user_pfx = $self->{-user_pfx}) {
498 push @ret, @$user_pfx;