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
16 use Search::Xapian qw/:standard/;
17 use PublicInbox::SearchMsg;
19 use PublicInbox::MID qw/mid_clean id_compress/;
21 # This is English-only, everything else is non-standard and may be confused as
22 # a prefix common in patch emails
23 our $REPLY_RE = qr/^re:\s+/i;
24 our $LANG = 'english';
27 # SCHEMA_VERSION history
29 # 1 - subject_path is lower-cased
30 # 2 - subject_path is id_compress in the index, only
31 # 3 - message-ID is compressed if it includes '%' (hack!)
32 # 4 - change "Re: " normalization, avoid circular Reference ghosts
33 # 5 - subject_path drops trailing '.'
34 # 6 - preserve References: order in document data
35 # 7 - remove references and inreplyto terms
36 # 8 - remove redundant/unneeded document data
37 # 9 - disable Message-ID compression (SHA-1)
38 # 10 - optimize doc for NNTP overviews
41 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
42 # as it could become a denial-of-service vector
43 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
47 my %bool_pfx_internal = (
48 type => 'T', # "mail" or "ghost"
49 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
52 my %bool_pfx_external = (
54 mid => 'Q', # uniQue id (Message-ID)
59 s => 'S', # for mairix compatibility
60 m => 'Q', # 'mid' is exact, 'm' can do partial
63 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
65 sub xpfx { $all_pfx{$_[0]} }
68 my %meta_pfx = (mid => 1, thread => 1, path => 1);
69 while (my ($k, $v) = each %all_pfx) {
70 $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
73 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
76 my (undef, $git_dir) = @_;
77 "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
81 my ($class, $git_dir) = @_;
82 my $dir = $class->xdir($git_dir);
83 my $db = Search::Xapian::Database->new($dir);
84 bless { xdb => $db, git_dir => $git_dir }, $class;
87 sub reopen { $_[0]->{xdb}->reopen }
91 my ($self, $query_string, $opts) = @_;
95 unless ($query_string eq '') {
96 $query = $self->qp->parse_query($query_string, QP_FLAGS);
97 $opts->{relevance} = 1 unless exists $opts->{relevance};
100 $self->do_enquire($query, $opts);
104 my ($self, $mid, $opts) = @_;
105 my $smsg = eval { $self->lookup_message($mid) };
107 return { total => 0, msgs => [] } unless $smsg;
108 my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
109 my $path = id_compress($smsg->path);
110 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
111 my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
112 $self->do_enquire($query, $opts);
116 my ($self, $query, $opts) = @_;
117 my $enquire = $self->enquire;
118 if (defined $query) {
119 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
121 $query = $mail_query;
123 $enquire->set_query($query);
125 my $desc = !$opts->{asc};
126 if ($opts->{relevance}) {
127 $enquire->set_sort_by_relevance_then_value(TS, $desc);
129 $enquire->set_sort_by_value_then_relevance(TS, $desc);
131 my $offset = $opts->{offset} || 0;
132 my $limit = $opts->{limit} || 50;
133 my $mset = $enquire->get_mset($offset, $limit);
134 return $mset if $opts->{mset};
136 PublicInbox::SearchMsg->load_doc($_->get_document);
139 { total => $mset->get_matches_estimated, msgs => \@msgs }
143 sub stemmer { Search::Xapian::Stem->new($LANG) }
149 my $qp = $self->{query_parser};
153 $qp = Search::Xapian::QueryParser->new;
154 $qp->set_default_op(OP_AND);
155 $qp->set_database($self->{xdb});
156 $qp->set_stemmer($self->stemmer);
157 $qp->set_stemming_strategy(STEM_SOME);
158 $qp->add_valuerangeprocessor($self->ts_range_processor);
159 $qp->add_valuerangeprocessor($self->date_range_processor);
161 while (my ($name, $prefix) = each %bool_pfx_external) {
162 $qp->add_boolean_prefix($name, $prefix);
165 while (my ($name, $prefix) = each %prob_prefix) {
166 $qp->add_prefix($name, $prefix);
169 $self->{query_parser} = $qp;
172 sub ts_range_processor {
173 $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
176 sub date_range_processor {
177 $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
180 sub num_range_processor {
181 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
184 # only used for NNTP server
186 my ($self, $beg, $end, $offset) = @_;
187 my $enquire = $self->enquire;
188 my $qp = Search::Xapian::QueryParser->new;
189 $qp->set_database($self->{xdb});
190 $qp->add_valuerangeprocessor($self->num_range_processor);
191 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
192 $query = Search::Xapian::Query->new(OP_AND, $mail_query, $query);
193 $enquire->set_query($query);
194 $enquire->set_sort_by_value(NUM, 0);
196 my $mset = $enquire->get_mset($offset, $limit);
198 PublicInbox::SearchMsg->load_doc($_->get_document);
201 { total => $mset->get_matches_estimated, msgs => \@msgs }
205 my ($self, $mid) = @_;
206 $mid = mid_clean($mid);
208 my $doc_id = $self->find_unique_doc_id('mid', $mid);
210 if (defined $doc_id) {
212 my $doc = $self->{xdb}->get_document($doc_id);
213 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
214 $smsg->doc_id($doc_id);
219 sub find_unique_doc_id {
220 my ($self, $term, $value) = @_;
222 my ($begin, $end) = $self->find_doc_ids($term, $value);
224 return undef if $begin->equal($end); # not found
226 my $rv = $begin->get_docid;
230 $begin->equal($end) or die "Term '$term:$value' is not unique\n";
234 # returns begin and end PostingIterator
236 my ($self, $term, $value) = @_;
238 $self->find_doc_ids_for_term(xpfx($term) . $value);
241 # returns begin and end PostingIterator
242 sub find_doc_ids_for_term {
243 my ($self, $term) = @_;
244 my $db = $self->{xdb};
246 ($db->postlist_begin($term), $db->postlist_end($term));
249 # normalize subjects so they are suitable as pathnames for URLs
252 $subj = subject_normalized($subj);
253 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
257 sub subject_normalized {
259 $subj =~ s/\A\s+//s; # no leading space
260 $subj =~ s/\s+\z//s; # no trailing space
261 $subj =~ s/\s+/ /gs; # no redundant spaces
262 $subj =~ s/\.+\z//; # no trailing '.'
263 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
268 sub subject_summary {
271 if (length($subj) > $max) {
272 my @subj = split(/\s+/, $subj);
276 while ($l = shift @subj) {
277 my $new = $subj . $l . ' ';
278 last if length($new) >= $max;
282 my $r = scalar @subj ? ' ...' : '';
285 # subject has one REALLY long word, and NOT spam? wtf
286 @subj = ($l =~ /\A(.{1,72})/);
287 $subj = $subj[0] . ' ...';
295 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});