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
41 # 12 - change YYYYMMDD value column to numeric
44 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
45 # as it could become a denial-of-service vector
46 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
50 my %bool_pfx_internal = (
51 type => 'T', # "mail" or "ghost"
52 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
55 my %bool_pfx_external = (
56 # do we still need these? probably not..
58 mid => 'Q', # uniQue id (Message-ID)
62 # for mairix compatibility
64 m => 'XMID', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
79 '' => 'XMID S A XNQ XQUOT XFN',
82 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
84 's:' => 'match within Subject e.g. s:"a quick brown fox"',
86 date range as YYYYMMDD e.g. d:19931002..20101002
87 Open-ended ranges such as d:19931002.. and d:..20101002
90 'b:' => 'match within message body, including text attachments',
91 'nq:' => 'match non-quoted text within message body',
92 'quot:' => 'match quoted text within message body',
93 'n:' => 'match filename of attachment(s)',
94 't:' => 'match within the To header',
95 'c:' => 'match within the Cc header',
96 'f:' => 'match within the From header',
97 'a:' => 'match within the To, Cc, and From headers',
98 'tc:' => 'match within the To and Cc headers',
99 'bs:' => 'match within the Subject and body',
103 # df (filenames from diff)
104 # da (diff a/ removed lines)
105 # db (diff b/ added lines)
107 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
109 sub xpfx { $all_pfx{$_[0]} }
112 my %meta_pfx = (mid => 1, thread => 1, path => 1);
113 while (my ($k, $v) = each %all_pfx) {
114 $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
117 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
120 my (undef, $git_dir) = @_;
121 "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
125 my ($class, $git_dir, $altid) = @_;
126 my $dir = $class->xdir($git_dir);
127 my $db = Search::Xapian::Database->new($dir);
128 bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
131 sub reopen { $_[0]->{xdb}->reopen }
135 my ($self, $query_string, $opts) = @_;
139 unless ($query_string eq '') {
140 $query = $self->qp->parse_query($query_string, QP_FLAGS);
141 $opts->{relevance} = 1 unless exists $opts->{relevance};
144 _do_enquire($self, $query, $opts);
148 my ($self, $mid, $opts) = @_;
149 my $smsg = eval { $self->lookup_message($mid) };
151 return { total => 0, msgs => [] } unless $smsg;
152 my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
153 my $path = $smsg->path;
154 if (defined $path && $path ne '') {
155 my $path = id_compress($smsg->path);
156 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
157 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
160 $opts->{limit} ||= 1000;
162 # always sort threads by timestamp, this makes life easier
163 # for the threading algorithm (in SearchThread.pm)
166 _do_enquire($self, $qtid, $opts);
170 my ($self, $query, $opts) = @_;
173 eval { $ret = _enquire_once($self, $query, $opts) };
174 return $ret unless $@;
175 # Exception: The revision being read has been discarded -
176 # you should call Xapian::Database::reopen()
177 if (index($@, 'Xapian::Database::reopen') >= 0) {
186 my ($self, $query, $opts) = @_;
187 my $enquire = $self->enquire;
188 if (defined $query) {
189 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
191 $query = $mail_query;
193 $enquire->set_query($query);
195 my $desc = !$opts->{asc};
196 if ($opts->{relevance}) {
197 $enquire->set_sort_by_relevance_then_value(TS, $desc);
198 } elsif ($opts->{num}) {
199 $enquire->set_sort_by_value(NUM, 0);
201 $enquire->set_sort_by_value_then_relevance(TS, $desc);
203 my $offset = $opts->{offset} || 0;
204 my $limit = $opts->{limit} || 50;
205 my $mset = $enquire->get_mset($offset, $limit);
206 return $mset if $opts->{mset};
208 PublicInbox::SearchMsg->load_doc($_->get_document);
211 { total => $mset->get_matches_estimated, msgs => \@msgs }
215 sub stemmer { Search::Xapian::Stem->new($LANG) }
221 my $qp = $self->{query_parser};
225 $qp = Search::Xapian::QueryParser->new;
226 $qp->set_default_op(OP_AND);
227 $qp->set_database($self->{xdb});
228 $qp->set_stemmer($self->stemmer);
229 $qp->set_stemming_strategy(STEM_SOME);
230 $qp->add_valuerangeprocessor(
231 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
233 while (my ($name, $prefix) = each %bool_pfx_external) {
234 $qp->add_boolean_prefix($name, $prefix);
237 # we do not actually create AltId objects,
238 # just parse the spec to avoid the extra DB handles for now.
239 if (my $altid = $self->{altid}) {
240 my $user_pfx = $self->{-user_pfx} ||= [];
242 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
243 /\Aserial:(\w+):/ or next;
245 push @$user_pfx, "$pfx:", <<EOF;
246 alternate serial number e.g. $pfx:12345 (boolean)
249 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
254 while (my ($name, $prefix) = each %prob_prefix) {
255 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
258 $self->{query_parser} = $qp;
261 sub num_range_processor {
262 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
265 # only used for NNTP server
267 my ($self, $beg, $end, $offset) = @_;
268 my $qp = Search::Xapian::QueryParser->new;
269 $qp->set_database($self->{xdb});
270 $qp->add_valuerangeprocessor($self->num_range_processor);
271 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
273 _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
277 my ($self, $mid) = @_;
278 $mid = mid_clean($mid);
280 my $doc_id = $self->find_unique_doc_id('mid', $mid);
282 if (defined $doc_id) {
284 my $doc = $self->{xdb}->get_document($doc_id);
285 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
286 $smsg->doc_id($doc_id);
291 sub lookup_mail { # no ghosts!
292 my ($self, $mid) = @_;
293 my $smsg = lookup_message($self, $mid) or return;
294 PublicInbox::SearchMsg->load_doc($smsg->{doc});
297 sub find_unique_doc_id {
298 my ($self, $term, $value) = @_;
300 my ($begin, $end) = $self->find_doc_ids($term, $value);
302 return undef if $begin->equal($end); # not found
304 my $rv = $begin->get_docid;
308 $begin->equal($end) or die "Term '$term:$value' is not unique\n";
312 # returns begin and end PostingIterator
314 my ($self, $term, $value) = @_;
316 $self->find_doc_ids_for_term(xpfx($term) . $value);
319 # returns begin and end PostingIterator
320 sub find_doc_ids_for_term {
321 my ($self, $term) = @_;
322 my $db = $self->{xdb};
324 ($db->postlist_begin($term), $db->postlist_end($term));
327 # normalize subjects so they are suitable as pathnames for URLs
330 $subj = subject_normalized($subj);
331 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
335 sub subject_normalized {
337 $subj =~ s/\A\s+//s; # no leading space
338 $subj =~ s/\s+\z//s; # no trailing space
339 $subj =~ s/\s+/ /gs; # no redundant spaces
340 $subj =~ s/\.+\z//; # no trailing '.'
341 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
346 sub subject_summary {
349 if (length($subj) > $max) {
350 my @subj = split(/\s+/, $subj);
354 while ($l = shift @subj) {
355 my $new = $subj . $l . ' ';
356 last if length($new) >= $max;
360 my $r = scalar @subj ? ' ...' : '';
363 # subject has one REALLY long word, and NOT spam? wtf
364 @subj = ($l =~ /\A(.{1,72})/);
365 $subj = $subj[0] . ' ...';
373 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
378 $self->qp; # parse altids
380 if (my $user_pfx = $self->{-user_pfx}) {
381 push @ret, @$user_pfx;