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