]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: allow searching user fields (To/Cc/From)
[public-inbox.git] / lib / PublicInbox / Search.pm
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
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8 use warnings;
9
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
16
17 use Search::Xapian qw/:standard/;
18 use PublicInbox::SearchMsg;
19 use Email::MIME;
20 use PublicInbox::MID qw/mid_clean id_compress/;
21
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';
26
27 use constant {
28         # SCHEMA_VERSION history
29         # 0 - initial
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         SCHEMA_VERSION => 11,
42
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,
46 };
47
48 # setup prefixes
49 my %bool_pfx_internal = (
50         type => 'T', # "mail" or "ghost"
51         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
52 );
53
54 my %bool_pfx_external = (
55         # do we still need these? probably not..
56         path => 'XPATH',
57         mid => 'Q', # uniQue id (Message-ID)
58 );
59
60 my %prob_prefix = (
61         subject => 'S',
62         s => 'S', # for mairix compatibility
63         m => 'Q', # 'mid' is exact, 'm' can do partial
64         f => 'A', # for mairix compatibility
65         t => 'XTO', # for mairix compatibility
66         tc => 'XTC', # for mairix compatibility
67         c => 'XCC', # for mairix compatibility
68         tcf => 'XTCF', # for mairix compatibility
69         # n.b.: leaving out "a:" alias for "tcf:" even though
70         # mairix supports it.  It is only mentioned in passing in mairix(1)
71         # and the extra two letters are not significantly longer.
72 );
73
74 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
75 our @HELP = (
76         's:' => <<EOF,
77 match within Subject only  e.g. s:"a quick brown fox"
78 This is a probabilistic search with support for stemming
79 and wildcards '*'
80 EOF
81         'd:' => <<EOF,
82 date range as YYYYMMDD  e.g. d:19931002..20101002
83 Open-ended ranges such as d:19931002.. and d:..20101002
84 are also supported.
85 EOF
86 );
87 # TODO: (from mairix, some of these are maybe)
88 # b (body), f (From:), c (Cc:), n (attachment), t (To:)
89 # tc (To:+Cc:), bs (body + Subject), tcf (To: +Cc: +From:)
90 #
91 # Non-mairix:
92 # df (filenames from diff)
93 # nq (non-quoted body)
94 # da (diff a/ removed lines)
95 # db (diff b/ added lines)
96
97 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
98
99 sub xpfx { $all_pfx{$_[0]} }
100
101 our %PFX2TERM_RMAP;
102 my %meta_pfx = (mid => 1, thread => 1, path => 1);
103 while (my ($k, $v) = each %all_pfx) {
104         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
105 }
106
107 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
108
109 sub xdir {
110         my (undef, $git_dir) = @_;
111         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
112 }
113
114 sub new {
115         my ($class, $git_dir, $altid) = @_;
116         my $dir = $class->xdir($git_dir);
117         my $db = Search::Xapian::Database->new($dir);
118         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
119 }
120
121 sub reopen { $_[0]->{xdb}->reopen }
122
123 # read-only
124 sub query {
125         my ($self, $query_string, $opts) = @_;
126         my $query;
127
128         $opts ||= {};
129         unless ($query_string eq '') {
130                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
131                 $opts->{relevance} = 1 unless exists $opts->{relevance};
132         }
133
134         _do_enquire($self, $query, $opts);
135 }
136
137 sub get_thread {
138         my ($self, $mid, $opts) = @_;
139         my $smsg = eval { $self->lookup_message($mid) };
140
141         return { total => 0, msgs => [] } unless $smsg;
142         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
143         my $path = $smsg->path;
144         if (defined $path && $path ne '') {
145                 my $path = id_compress($smsg->path);
146                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
147                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
148         }
149         $opts ||= {};
150         $opts->{limit} ||= 1000;
151         _do_enquire($self, $qtid, $opts);
152 }
153
154 sub _do_enquire {
155         my ($self, $query, $opts) = @_;
156         my $ret;
157         for (1..10) {
158                 eval { $ret = _enquire_once($self, $query, $opts) };
159                 return $ret unless $@;
160                 # Exception: The revision being read has been discarded -
161                 # you should call Xapian::Database::reopen()
162                 if (index($@, 'Xapian::Database::reopen') >= 0) {
163                         reopen($self);
164                 } else {
165                         die $@;
166                 }
167         }
168 }
169
170 sub _enquire_once {
171         my ($self, $query, $opts) = @_;
172         my $enquire = $self->enquire;
173         if (defined $query) {
174                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
175         } else {
176                 $query = $mail_query;
177         }
178         $enquire->set_query($query);
179         $opts ||= {};
180         my $desc = !$opts->{asc};
181         if ($opts->{relevance}) {
182                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
183         } elsif ($opts->{num}) {
184                 $enquire->set_sort_by_value(NUM, 0);
185         } else {
186                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
187         }
188         my $offset = $opts->{offset} || 0;
189         my $limit = $opts->{limit} || 50;
190         my $mset = $enquire->get_mset($offset, $limit);
191         return $mset if $opts->{mset};
192         my @msgs = map {
193                 PublicInbox::SearchMsg->load_doc($_->get_document);
194         } $mset->items;
195
196         { total => $mset->get_matches_estimated, msgs => \@msgs }
197 }
198
199 # read-write
200 sub stemmer { Search::Xapian::Stem->new($LANG) }
201
202 # read-only
203 sub qp {
204         my ($self) = @_;
205
206         my $qp = $self->{query_parser};
207         return $qp if $qp;
208
209         # new parser
210         $qp = Search::Xapian::QueryParser->new;
211         $qp->set_default_op(OP_AND);
212         $qp->set_database($self->{xdb});
213         $qp->set_stemmer($self->stemmer);
214         $qp->set_stemming_strategy(STEM_SOME);
215         $qp->add_valuerangeprocessor(
216                 Search::Xapian::StringValueRangeProcessor->new(YYYYMMDD, 'd:'));
217
218         while (my ($name, $prefix) = each %bool_pfx_external) {
219                 $qp->add_boolean_prefix($name, $prefix);
220         }
221
222         # we do not actually create AltId objects,
223         # just parse the spec to avoid the extra DB handles for now.
224         if (my $altid = $self->{altid}) {
225                 my $user_pfx = $self->{-user_pfx} ||= [];
226                 for (@$altid) {
227                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
228                         /\Aserial:(\w+):/ or next;
229                         my $pfx = $1;
230                         push @$user_pfx, "$pfx:", <<EOF;
231 alternate serial number  e.g. $pfx:12345
232 EOF
233                         # gmane => XGMANE
234                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
235                 }
236         }
237
238         while (my ($name, $prefix) = each %prob_prefix) {
239                 $qp->add_prefix($name, $prefix);
240         }
241
242         $self->{query_parser} = $qp;
243 }
244
245 sub num_range_processor {
246         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
247 }
248
249 # only used for NNTP server
250 sub query_xover {
251         my ($self, $beg, $end, $offset) = @_;
252         my $qp = Search::Xapian::QueryParser->new;
253         $qp->set_database($self->{xdb});
254         $qp->add_valuerangeprocessor($self->num_range_processor);
255         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
256
257         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
258 }
259
260 sub lookup_message {
261         my ($self, $mid) = @_;
262         $mid = mid_clean($mid);
263
264         my $doc_id = $self->find_unique_doc_id('mid', $mid);
265         my $smsg;
266         if (defined $doc_id) {
267                 # raises on error:
268                 my $doc = $self->{xdb}->get_document($doc_id);
269                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
270                 $smsg->doc_id($doc_id);
271         }
272         $smsg;
273 }
274
275 sub lookup_mail { # no ghosts!
276         my ($self, $mid) = @_;
277         my $smsg = lookup_message($self, $mid) or return;
278         PublicInbox::SearchMsg->load_doc($smsg->{doc});
279 }
280
281 sub find_unique_doc_id {
282         my ($self, $term, $value) = @_;
283
284         my ($begin, $end) = $self->find_doc_ids($term, $value);
285
286         return undef if $begin->equal($end); # not found
287
288         my $rv = $begin->get_docid;
289
290         # sanity check
291         $begin->inc;
292         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
293         $rv;
294 }
295
296 # returns begin and end PostingIterator
297 sub find_doc_ids {
298         my ($self, $term, $value) = @_;
299
300         $self->find_doc_ids_for_term(xpfx($term) . $value);
301 }
302
303 # returns begin and end PostingIterator
304 sub find_doc_ids_for_term {
305         my ($self, $term) = @_;
306         my $db = $self->{xdb};
307
308         ($db->postlist_begin($term), $db->postlist_end($term));
309 }
310
311 # normalize subjects so they are suitable as pathnames for URLs
312 sub subject_path {
313         my $subj = pop;
314         $subj = subject_normalized($subj);
315         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
316         lc($subj);
317 }
318
319 sub subject_normalized {
320         my $subj = pop;
321         $subj =~ s/\A\s+//s; # no leading space
322         $subj =~ s/\s+\z//s; # no trailing space
323         $subj =~ s/\s+/ /gs; # no redundant spaces
324         $subj =~ s/\.+\z//; # no trailing '.'
325         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
326         $subj;
327 }
328
329 # for doc data
330 sub subject_summary {
331         my $subj = pop;
332         my $max = 68;
333         if (length($subj) > $max) {
334                 my @subj = split(/\s+/, $subj);
335                 $subj = '';
336                 my $l;
337
338                 while ($l = shift @subj) {
339                         my $new = $subj . $l . ' ';
340                         last if length($new) >= $max;
341                         $subj = $new;
342                 }
343                 if ($subj ne '') {
344                         my $r = scalar @subj ? ' ...' : '';
345                         $subj =~ s/ \z/$r/s;
346                 } else {
347                         # subject has one REALLY long word, and NOT spam? wtf
348                         @subj = ($l =~ /\A(.{1,72})/);
349                         $subj = $subj[0] . ' ...';
350                 }
351         }
352         $subj;
353 }
354
355 sub enquire {
356         my ($self) = @_;
357         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
358 }
359
360 sub help {
361         my ($self) = @_;
362         $self->qp; # parse altids
363         my @ret = @HELP;
364         if (my $user_pfx = $self->{-user_pfx}) {
365                 push @ret, @$user_pfx;
366         }
367         \@ret;
368 }
369
370 1;