1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (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;
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
43 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
44 # as it could become a denial-of-service vector
45 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
49 my %bool_pfx_internal = (
50 type => 'T', # "mail" or "ghost"
51 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
54 my %bool_pfx_external = (
55 # do we still need these? probably not..
57 mid => 'Q', # uniQue id (Message-ID)
61 # for mairix compatibility
63 m => 'Q', # 'mid' is exact, 'm' can do partial
72 # n.b.: leaving out "a:" alias for "tcf:" even though
73 # mairix supports it. It is only mentioned in passing in mairix(1)
74 # and the extra two letters are not significantly longer.
79 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
82 match within Subject only e.g. s:"a quick brown fox"
83 This is a probabilistic search with support for stemming
87 date range as YYYYMMDD e.g. d:19931002..20101002
88 Open-ended ranges such as d:19931002.. and d:..20101002
92 # TODO: (from mairix, some of these are maybe)
93 # b (body), f (From:), c (Cc:), n (attachment), t (To:)
94 # tc (To:+Cc:), bs (body + Subject), tcf (To: +Cc: +From:)
97 # df (filenames from diff)
98 # nq (non-quoted body)
99 # da (diff a/ removed lines)
100 # db (diff b/ added lines)
102 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
104 sub xpfx { $all_pfx{$_[0]} }
107 my %meta_pfx = (mid => 1, thread => 1, path => 1);
108 while (my ($k, $v) = each %all_pfx) {
109 $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
112 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
115 my (undef, $git_dir) = @_;
116 "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
120 my ($class, $git_dir, $altid) = @_;
121 my $dir = $class->xdir($git_dir);
122 my $db = Search::Xapian::Database->new($dir);
123 bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
126 sub reopen { $_[0]->{xdb}->reopen }
130 my ($self, $query_string, $opts) = @_;
134 unless ($query_string eq '') {
135 $query = $self->qp->parse_query($query_string, QP_FLAGS);
136 $opts->{relevance} = 1 unless exists $opts->{relevance};
139 _do_enquire($self, $query, $opts);
143 my ($self, $mid, $opts) = @_;
144 my $smsg = eval { $self->lookup_message($mid) };
146 return { total => 0, msgs => [] } unless $smsg;
147 my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
148 my $path = $smsg->path;
149 if (defined $path && $path ne '') {
150 my $path = id_compress($smsg->path);
151 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
152 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
155 $opts->{limit} ||= 1000;
156 _do_enquire($self, $qtid, $opts);
160 my ($self, $query, $opts) = @_;
163 eval { $ret = _enquire_once($self, $query, $opts) };
164 return $ret unless $@;
165 # Exception: The revision being read has been discarded -
166 # you should call Xapian::Database::reopen()
167 if (index($@, 'Xapian::Database::reopen') >= 0) {
176 my ($self, $query, $opts) = @_;
177 my $enquire = $self->enquire;
178 if (defined $query) {
179 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
181 $query = $mail_query;
183 $enquire->set_query($query);
185 my $desc = !$opts->{asc};
186 if ($opts->{relevance}) {
187 $enquire->set_sort_by_relevance_then_value(TS, $desc);
188 } elsif ($opts->{num}) {
189 $enquire->set_sort_by_value(NUM, 0);
191 $enquire->set_sort_by_value_then_relevance(TS, $desc);
193 my $offset = $opts->{offset} || 0;
194 my $limit = $opts->{limit} || 50;
195 my $mset = $enquire->get_mset($offset, $limit);
196 return $mset if $opts->{mset};
198 PublicInbox::SearchMsg->load_doc($_->get_document);
201 { total => $mset->get_matches_estimated, msgs => \@msgs }
205 sub stemmer { Search::Xapian::Stem->new($LANG) }
211 my $qp = $self->{query_parser};
215 $qp = Search::Xapian::QueryParser->new;
216 $qp->set_default_op(OP_AND);
217 $qp->set_database($self->{xdb});
218 $qp->set_stemmer($self->stemmer);
219 $qp->set_stemming_strategy(STEM_SOME);
220 $qp->add_valuerangeprocessor(
221 Search::Xapian::StringValueRangeProcessor->new(YYYYMMDD, 'd:'));
223 while (my ($name, $prefix) = each %bool_pfx_external) {
224 $qp->add_boolean_prefix($name, $prefix);
227 # we do not actually create AltId objects,
228 # just parse the spec to avoid the extra DB handles for now.
229 if (my $altid = $self->{altid}) {
230 my $user_pfx = $self->{-user_pfx} ||= [];
232 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
233 /\Aserial:(\w+):/ or next;
235 push @$user_pfx, "$pfx:", <<EOF;
236 alternate serial number e.g. $pfx:12345
239 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
243 while (my ($name, $prefix) = each %prob_prefix) {
244 $qp->add_prefix($name, $prefix);
247 $self->{query_parser} = $qp;
250 sub num_range_processor {
251 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
254 # only used for NNTP server
256 my ($self, $beg, $end, $offset) = @_;
257 my $qp = Search::Xapian::QueryParser->new;
258 $qp->set_database($self->{xdb});
259 $qp->add_valuerangeprocessor($self->num_range_processor);
260 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
262 _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
266 my ($self, $mid) = @_;
267 $mid = mid_clean($mid);
269 my $doc_id = $self->find_unique_doc_id('mid', $mid);
271 if (defined $doc_id) {
273 my $doc = $self->{xdb}->get_document($doc_id);
274 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
275 $smsg->doc_id($doc_id);
280 sub lookup_mail { # no ghosts!
281 my ($self, $mid) = @_;
282 my $smsg = lookup_message($self, $mid) or return;
283 PublicInbox::SearchMsg->load_doc($smsg->{doc});
286 sub find_unique_doc_id {
287 my ($self, $term, $value) = @_;
289 my ($begin, $end) = $self->find_doc_ids($term, $value);
291 return undef if $begin->equal($end); # not found
293 my $rv = $begin->get_docid;
297 $begin->equal($end) or die "Term '$term:$value' is not unique\n";
301 # returns begin and end PostingIterator
303 my ($self, $term, $value) = @_;
305 $self->find_doc_ids_for_term(xpfx($term) . $value);
308 # returns begin and end PostingIterator
309 sub find_doc_ids_for_term {
310 my ($self, $term) = @_;
311 my $db = $self->{xdb};
313 ($db->postlist_begin($term), $db->postlist_end($term));
316 # normalize subjects so they are suitable as pathnames for URLs
319 $subj = subject_normalized($subj);
320 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
324 sub subject_normalized {
326 $subj =~ s/\A\s+//s; # no leading space
327 $subj =~ s/\s+\z//s; # no trailing space
328 $subj =~ s/\s+/ /gs; # no redundant spaces
329 $subj =~ s/\.+\z//; # no trailing '.'
330 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
335 sub subject_summary {
338 if (length($subj) > $max) {
339 my @subj = split(/\s+/, $subj);
343 while ($l = shift @subj) {
344 my $new = $subj . $l . ' ';
345 last if length($new) >= $max;
349 my $r = scalar @subj ? ' ...' : '';
352 # subject has one REALLY long word, and NOT spam? wtf
353 @subj = ($l =~ /\A(.{1,72})/);
354 $subj = $subj[0] . ' ...';
362 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
367 $self->qp; # parse altids
369 if (my $user_pfx = $self->{-user_pfx}) {
370 push @ret, @$user_pfx;