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 DS => 0; # Date: header in Unix time
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 TS => 4; # Received: header in Unix time
16 use constant YYYYMMDD => 5; # for searching in the WWW UI
18 use Search::Xapian qw/:standard/;
19 use PublicInbox::SearchMsg;
20 use PublicInbox::MIME;
21 use PublicInbox::MID qw/id_compress/;
23 # This is English-only, everything else is non-standard and may be confused as
24 # a prefix common in patch emails
25 our $REPLY_RE = qr/^re:\s+/i;
26 our $LANG = 'english';
29 # SCHEMA_VERSION history
31 # 1 - subject_path is lower-cased
32 # 2 - subject_path is id_compress in the index, only
33 # 3 - message-ID is compressed if it includes '%' (hack!)
34 # 4 - change "Re: " normalization, avoid circular Reference ghosts
35 # 5 - subject_path drops trailing '.'
36 # 6 - preserve References: order in document data
37 # 7 - remove references and inreplyto terms
38 # 8 - remove redundant/unneeded document data
39 # 9 - disable Message-ID compression (SHA-1)
40 # 10 - optimize doc for NNTP overviews
41 # 11 - merge threads when vivifying ghosts
42 # 12 - change YYYYMMDD value column to numeric
43 # 13 - fix threading for empty References/In-Reply-To
44 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
45 # 14 - fix ghost root vivification
48 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
49 # as it could become a denial-of-service vector
50 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
54 my %bool_pfx_internal = (
55 type => 'T', # "mail" or "ghost"
56 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
59 my %bool_pfx_external = (
60 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
63 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
65 # for mairix compatibility
67 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
74 b => $non_quoted_body . ' XQUOT',
75 bs => $non_quoted_body . ' XQUOT S',
79 nq => $non_quoted_body,
87 dfblob => 'XDFPRE XDFPOST',
90 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
93 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
95 's:' => 'match within Subject e.g. s:"a quick brown fox"',
97 date range as YYYYMMDD e.g. d:19931002..20101002
98 Open-ended ranges such as d:19931002.. and d:..20101002
101 'b:' => 'match within message body, including text attachments',
102 'nq:' => 'match non-quoted text within message body',
103 'q:' => 'match quoted text within message body',
104 'n:' => 'match filename of attachment(s)',
105 't:' => 'match within the To header',
106 'c:' => 'match within the Cc header',
107 'f:' => 'match within the From header',
108 'a:' => 'match within the To, Cc, and From headers',
109 'tc:' => 'match within the To and Cc headers',
110 'bs:' => 'match within the Subject and body',
111 'dfn:' => 'match filename from diff',
112 'dfa:' => 'match diff removed (-) lines',
113 'dfb:' => 'match diff added (+) lines',
114 'dfhh:' => 'match diff hunk header context (usually a function name)',
115 'dfctx:' => 'match diff context lines',
116 'dfpre:' => 'match pre-image git blob ID',
117 'dfpost:' => 'match post-image git blob ID',
118 'dfblob:' => 'match either pre or post-image git blob ID',
122 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
126 if ($self->{version} == 1) {
127 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
129 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
130 my $part = $self->{partition};
131 defined $part or die "partition not given";
137 my ($class, $mainrepo, $altid) = @_;
141 $version = $ibx->{version} || 1;
142 $mainrepo = $ibx->{mainrepo};
145 mainrepo => $mainrepo,
150 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
153 foreach my $part (<$dir/*>) {
154 -d $part && $part =~ m!/\d+\z! or next;
156 my $sub = Search::Xapian::Database->new($part);
158 $xdb->add_database($sub);
164 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
166 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
173 $self->{xdb}->reopen;
174 if (my $skel = $self->{skel}) {
177 $self; # make chaining easier
182 my ($self, $query_string, $opts) = @_;
186 unless ($query_string eq '') {
187 $query = $self->qp->parse_query($query_string, QP_FLAGS);
188 $opts->{relevance} = 1 unless exists $opts->{relevance};
191 _do_enquire($self, $query, $opts);
195 my ($self, $mid, $opts) = @_;
196 my $smsg = first_smsg_by_mid($self, $mid) or
197 return { total => 0, msgs => [] };
198 my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
199 my $path = $smsg->path;
200 if (defined $path && $path ne '') {
201 my $path = id_compress($smsg->path);
202 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
203 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
206 $opts->{limit} ||= 1000;
208 # always sort threads by timestamp, this makes life easier
209 # for the threading algorithm (in SearchThread.pm)
211 $opts->{enquire} = enquire_skel($self);
212 _do_enquire($self, $qtid, $opts);
216 my ($self, $cb) = @_;
219 eval { $ret = $cb->() };
220 return $ret unless $@;
221 # Exception: The revision being read has been discarded -
222 # you should call Xapian::Database::reopen()
223 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
226 warn "ref: ", ref($@), "\n";
233 my ($self, $query, $opts) = @_;
234 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
238 my ($self, $query, $opts) = @_;
239 my $enquire = $opts->{enquire} || enquire($self);
240 if (defined $query) {
241 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
243 $query = $mail_query;
245 $enquire->set_query($query);
247 my $desc = !$opts->{asc};
248 if ($opts->{relevance}) {
249 $enquire->set_sort_by_relevance_then_value(TS, $desc);
250 } elsif ($opts->{num}) {
251 $enquire->set_sort_by_value(NUM, 0);
253 $enquire->set_sort_by_value_then_relevance(TS, $desc);
255 my $offset = $opts->{offset} || 0;
256 my $limit = $opts->{limit} || 50;
257 my $mset = $enquire->get_mset($offset, $limit);
258 return $mset if $opts->{mset};
260 PublicInbox::SearchMsg->load_doc($_->get_document);
263 { total => $mset->get_matches_estimated, msgs => \@msgs }
267 sub stemmer { Search::Xapian::Stem->new($LANG) }
273 my $qp = $self->{query_parser};
277 $qp = Search::Xapian::QueryParser->new;
278 $qp->set_default_op(OP_AND);
279 $qp->set_database($self->{xdb});
280 $qp->set_stemmer($self->stemmer);
281 $qp->set_stemming_strategy(STEM_SOME);
282 $qp->add_valuerangeprocessor(
283 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
285 while (my ($name, $prefix) = each %bool_pfx_external) {
286 $qp->add_boolean_prefix($name, $prefix);
289 # we do not actually create AltId objects,
290 # just parse the spec to avoid the extra DB handles for now.
291 if (my $altid = $self->{altid}) {
292 my $user_pfx = $self->{-user_pfx} ||= [];
294 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
295 /\Aserial:(\w+):/ or next;
297 push @$user_pfx, "$pfx:", <<EOF;
298 alternate serial number e.g. $pfx:12345 (boolean)
301 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
306 while (my ($name, $prefix) = each %prob_prefix) {
307 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
310 $self->{query_parser} = $qp;
313 sub num_range_processor {
314 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
317 # only used for NNTP server
319 my ($self, $beg, $end, $offset) = @_;
320 my $qp = Search::Xapian::QueryParser->new;
321 $qp->set_database($self->{skel} || $self->{xdb});
322 $qp->add_valuerangeprocessor($self->num_range_processor);
323 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
326 enquire => enquire_skel($self),
331 _do_enquire($self, $query, $opts);
335 my ($self, $ts, $opts) = @_;
336 my $qp = $self->{qp_ts} ||= eval {
337 my $q = Search::Xapian::QueryParser->new;
338 $q->set_database($self->{skel} || $self->{xdb});
339 $q->add_valuerangeprocessor(
340 Search::Xapian::NumberValueRangeProcessor->new(TS));
343 my $query = $qp->parse_query($ts, QP_FLAGS);
344 $opts->{enquire} = enquire_skel($self);
345 _do_enquire($self, $query, $opts);
348 sub first_smsg_by_mid {
349 my ($self, $mid) = @_;
351 retry_reopen($self, sub {
352 each_smsg_by_mid($self, $mid, sub { $smsg = $_[0]; undef });
358 my ($self, $num) = @_;
359 my $term = 'XNUM'.$num;
360 my $db = $self->{skel} || $self->{xdb};
361 retry_reopen($self, sub {
362 my $head = $db->postlist_begin($term);
363 my $tail = $db->postlist_end($term);
364 return if $head->equal($tail);
365 my $doc_id = $head->get_docid;
366 return unless defined $doc_id;
368 if ($head->nequal($tail)) {
369 my $loc= $self->{mainrepo} .
370 ($self->{skel} ? 'skel' : 'xdb');
371 warn "article #$num is not unique in $loc\n";
374 my $doc = $db->get_document($doc_id);
375 my $smsg = PublicInbox::SearchMsg->wrap($doc);
376 $smsg->{doc_id} = $doc_id;
381 sub each_smsg_by_mid {
382 my ($self, $mid, $cb) = @_;
383 # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
384 # interface will need it...
385 my $db = $self->{skel} || $self->{xdb};
386 my $term = 'Q' . $mid;
387 my $head = $db->postlist_begin($term);
388 my $tail = $db->postlist_end($term);
389 if ($head == $tail) {
391 $head = $db->postlist_begin($term);
392 $tail = $db->postlist_end($term);
394 return ($head, $tail, $db) if wantarray;
395 for (; $head->nequal($tail); $head->inc) {
396 my $doc_id = $head->get_docid;
397 my $doc = $db->get_document($doc_id);
398 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
399 $smsg->{doc_id} = $doc_id;
400 $cb->($smsg) or return;
404 # normalize subjects so they are suitable as pathnames for URLs
405 # XXX: consider for removal
408 $subj = subject_normalized($subj);
409 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
413 sub subject_normalized {
415 $subj =~ s/\A\s+//s; # no leading space
416 $subj =~ s/\s+\z//s; # no trailing space
417 $subj =~ s/\s+/ /gs; # no redundant spaces
418 $subj =~ s/\.+\z//; # no trailing '.'
419 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
425 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
430 if (my $skel = $self->{skel}) {
431 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
439 $self->qp; # parse altids
441 if (my $user_pfx = $self->{-user_pfx}) {
442 push @ret, @$user_pfx;