]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
update copyright headers and email addresses
[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 package PublicInbox::Search;
5 use strict;
6 use warnings;
7 use constant TS => 0;
8 use Search::Xapian qw/:standard/;
9 use PublicInbox::SearchMsg;
10 use Email::MIME;
11 use PublicInbox::MID qw/mid_clean mid_compress/;
12
13 # This is English-only, everything else is non-standard and may be confused as
14 # a prefix common in patch emails
15 our $REPLY_RE = qr/^re:\s+/i;
16 our $LANG = 'english';
17
18 use constant {
19         # SCHEMA_VERSION history
20         # 0 - initial
21         # 1 - subject_path is lower-cased
22         # 2 - subject_path is mid_compress in the index, only
23         # 3 - message-ID is compressed if it includes '%' (hack!)
24         # 4 - change "Re: " normalization, avoid circular Reference ghosts
25         # 5 - subject_path drops trailing '.'
26         # 6 - preserve References: order in document data
27         # 7 - remove references and inreplyto terms
28         # 8 - remove redundant/unneeded document data
29         # 9 - disable Message-ID compression
30         SCHEMA_VERSION => 9,
31
32         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
33         # as it could become a denial-of-service vector
34         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
35 };
36
37 # setup prefixes
38 my %bool_pfx_internal = (
39         type => 'T', # "mail" or "ghost"
40         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
41 );
42
43 my %bool_pfx_external = (
44         path => 'XPATH',
45         mid => 'Q', # uniQue id (Message-ID)
46 );
47
48 my %prob_prefix = (
49         subject => 'S',
50         s => 'S', # for mairix compatibility
51         m => 'Q', # 'mid' is exact, 'm' can do partial
52 );
53
54 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
55
56 sub xpfx { $all_pfx{$_[0]} }
57
58 our %PFX2TERM_RMAP;
59 my %meta_pfx = (mid => 1, thread => 1, path => 1);
60 while (my ($k, $v) = each %all_pfx) {
61         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
62 }
63
64 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
65
66 sub xdir {
67         my (undef, $git_dir) = @_;
68         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
69 }
70
71 sub new {
72         my ($class, $git_dir) = @_;
73         my $dir = $class->xdir($git_dir);
74         my $db = Search::Xapian::Database->new($dir);
75         bless { xdb => $db, git_dir => $git_dir }, $class;
76 }
77
78 sub reopen { $_[0]->{xdb}->reopen }
79
80 # read-only
81 sub query {
82         my ($self, $query_string, $opts) = @_;
83         my $query;
84
85         $opts ||= {};
86         unless ($query_string eq '') {
87                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
88                 $opts->{relevance} = 1 unless exists $opts->{relevance};
89         }
90
91         $self->do_enquire($query, $opts);
92 }
93
94 sub get_subject_path {
95         my ($self, $path, $opts) = @_;
96         my $q = Search::Xapian::Query->new(xpfx("path").mid_compress($path));
97         $self->do_enquire($q, $opts);
98 }
99
100 sub get_thread {
101         my ($self, $mid, $opts) = @_;
102         my $smsg = eval { $self->lookup_message($mid) };
103
104         return { total => 0, msgs => [] } unless $smsg;
105         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
106         my $path = mid_compress($smsg->path);
107         my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
108         my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
109         $self->do_enquire($query, $opts);
110 }
111
112 # private subs below
113
114 sub do_enquire {
115         my ($self, $query, $opts) = @_;
116         my $enquire = $self->enquire;
117         if (defined $query) {
118                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
119         } else {
120                 $query = $mail_query;
121         }
122         $enquire->set_query($query);
123         if ($opts->{relevance}) {
124                 $enquire->set_sort_by_relevance_then_value(TS, 1);
125         } else {
126                 $enquire->set_sort_by_value_then_relevance(TS, 1);
127         }
128         $opts ||= {};
129         my $offset = $opts->{offset} || 0;
130         my $limit = $opts->{limit} || 50;
131         my $mset = $enquire->get_mset($offset, $limit);
132         return $mset if $opts->{mset};
133         my @msgs = map {
134                 PublicInbox::SearchMsg->load_doc($_->get_document);
135         } $mset->items;
136
137         { total => $mset->get_matches_estimated, msgs => \@msgs }
138 }
139
140 # read-write
141 sub stemmer { Search::Xapian::Stem->new($LANG) }
142
143 # read-only
144 sub qp {
145         my ($self) = @_;
146
147         my $qp = $self->{query_parser};
148         return $qp if $qp;
149
150         # new parser
151         $qp = Search::Xapian::QueryParser->new;
152         $qp->set_default_op(OP_AND);
153         $qp->set_database($self->{xdb});
154         $qp->set_stemmer($self->stemmer);
155         $qp->set_stemming_strategy(STEM_SOME);
156         $qp->add_valuerangeprocessor($self->ts_range_processor);
157         $qp->add_valuerangeprocessor($self->date_range_processor);
158
159         while (my ($name, $prefix) = each %bool_pfx_external) {
160                 $qp->add_boolean_prefix($name, $prefix);
161         }
162
163         while (my ($name, $prefix) = each %prob_prefix) {
164                 $qp->add_prefix($name, $prefix);
165         }
166
167         $self->{query_parser} = $qp;
168 }
169
170 sub ts_range_processor {
171         $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
172 }
173
174 sub date_range_processor {
175         $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
176 }
177
178 sub lookup_message {
179         my ($self, $mid) = @_;
180         $mid = mid_clean($mid);
181
182         my $doc_id = $self->find_unique_doc_id('mid', $mid);
183         my $smsg;
184         if (defined $doc_id) {
185                 # raises on error:
186                 my $doc = $self->{xdb}->get_document($doc_id);
187                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
188                 $smsg->doc_id($doc_id);
189         }
190         $smsg;
191 }
192
193 sub find_unique_doc_id {
194         my ($self, $term, $value) = @_;
195
196         my ($begin, $end) = $self->find_doc_ids($term, $value);
197
198         return undef if $begin->equal($end); # not found
199
200         my $rv = $begin->get_docid;
201
202         # sanity check
203         $begin->inc;
204         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
205         $rv;
206 }
207
208 # returns begin and end PostingIterator
209 sub find_doc_ids {
210         my ($self, $term, $value) = @_;
211
212         $self->find_doc_ids_for_term(xpfx($term) . $value);
213 }
214
215 # returns begin and end PostingIterator
216 sub find_doc_ids_for_term {
217         my ($self, $term) = @_;
218         my $db = $self->{xdb};
219
220         ($db->postlist_begin($term), $db->postlist_end($term));
221 }
222
223 # normalize subjects so they are suitable as pathnames for URLs
224 sub subject_path {
225         my $subj = pop;
226         $subj = subject_normalized($subj);
227         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
228         lc($subj);
229 }
230
231 sub subject_normalized {
232         my $subj = pop;
233         $subj =~ s/\A\s+//s; # no leading space
234         $subj =~ s/\s+\z//s; # no trailing space
235         $subj =~ s/\s+/ /gs; # no redundant spaces
236         $subj =~ s/\.+\z//; # no trailing '.'
237         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
238         $subj;
239 }
240
241 # for doc data
242 sub subject_summary {
243         my $subj = pop;
244         my $max = 68;
245         if (length($subj) > $max) {
246                 my @subj = split(/\s+/, $subj);
247                 $subj = '';
248                 my $l;
249
250                 while ($l = shift @subj) {
251                         my $new = $subj . $l . ' ';
252                         last if length($new) >= $max;
253                         $subj = $new;
254                 }
255                 if ($subj ne '') {
256                         my $r = scalar @subj ? ' ...' : '';
257                         $subj =~ s/ \z/$r/s;
258                 } else {
259                         # subject has one REALLY long word, and NOT spam? wtf
260                         @subj = ($l =~ /\A(.{1,72})/);
261                         $subj = $subj[0] . ' ...';
262                 }
263         }
264         $subj;
265 }
266
267 sub enquire {
268         my ($self) = @_;
269         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
270 }
271
272 sub mid_prefix {
273         my ($self, $mpfx) = @_;
274         my $query = eval { $self->qp->parse_query("m:$mpfx", FLAG_PARTIAL) };
275         return if $@;
276         my $res = $self->do_enquire($query, { relevance => 1 });
277         return unless $res->{total};
278         [ map { $_->mid } @{$res->{msgs}} ];
279 }
280
281 1;