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;
9 use constant TS => 0; # timestamp
10 use constant NUM => 1; # NNTP article number
11 use constant BYTES => 2; # :bytes as defined in RFC 3977
12 use constant LINES => 3; # :lines as defined in RFC 3977
14 use Search::Xapian qw/:standard/;
15 use PublicInbox::SearchMsg;
17 use PublicInbox::MID qw/mid_clean mid_compress/;
19 # This is English-only, everything else is non-standard and may be confused as
20 # a prefix common in patch emails
21 our $REPLY_RE = qr/^re:\s+/i;
22 our $LANG = 'english';
25 # SCHEMA_VERSION history
27 # 1 - subject_path is lower-cased
28 # 2 - subject_path is mid_compress in the index, only
29 # 3 - message-ID is compressed if it includes '%' (hack!)
30 # 4 - change "Re: " normalization, avoid circular Reference ghosts
31 # 5 - subject_path drops trailing '.'
32 # 6 - preserve References: order in document data
33 # 7 - remove references and inreplyto terms
34 # 8 - remove redundant/unneeded document data
35 # 9 - disable Message-ID compression (SHA-1)
36 # 10 - optimize doc for NNTP overviews
39 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
40 # as it could become a denial-of-service vector
41 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
45 my %bool_pfx_internal = (
46 type => 'T', # "mail" or "ghost"
47 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
50 my %bool_pfx_external = (
52 mid => 'Q', # uniQue id (Message-ID)
57 s => 'S', # for mairix compatibility
58 m => 'Q', # 'mid' is exact, 'm' can do partial
61 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
63 sub xpfx { $all_pfx{$_[0]} }
66 my %meta_pfx = (mid => 1, thread => 1, path => 1);
67 while (my ($k, $v) = each %all_pfx) {
68 $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
71 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
74 my (undef, $git_dir) = @_;
75 "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
79 my ($class, $git_dir) = @_;
80 my $dir = $class->xdir($git_dir);
81 my $db = Search::Xapian::Database->new($dir);
82 bless { xdb => $db, git_dir => $git_dir }, $class;
85 sub reopen { $_[0]->{xdb}->reopen }
89 my ($self, $query_string, $opts) = @_;
93 unless ($query_string eq '') {
94 $query = $self->qp->parse_query($query_string, QP_FLAGS);
95 $opts->{relevance} = 1 unless exists $opts->{relevance};
98 $self->do_enquire($query, $opts);
102 my ($self, $mid, $opts) = @_;
103 my $smsg = eval { $self->lookup_message($mid) };
105 return { total => 0, msgs => [] } unless $smsg;
106 my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
107 my $path = mid_compress($smsg->path);
108 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
109 my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
110 $self->do_enquire($query, $opts);
114 my ($self, $query, $opts) = @_;
115 my $enquire = $self->enquire;
116 if (defined $query) {
117 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
119 $query = $mail_query;
121 $enquire->set_query($query);
123 my $desc = !$opts->{asc};
124 if ($opts->{relevance}) {
125 $enquire->set_sort_by_relevance_then_value(TS, $desc);
127 $enquire->set_sort_by_value_then_relevance(TS, $desc);
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};
134 PublicInbox::SearchMsg->load_doc($_->get_document);
137 { total => $mset->get_matches_estimated, msgs => \@msgs }
141 sub stemmer { Search::Xapian::Stem->new($LANG) }
147 my $qp = $self->{query_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);
159 while (my ($name, $prefix) = each %bool_pfx_external) {
160 $qp->add_boolean_prefix($name, $prefix);
163 while (my ($name, $prefix) = each %prob_prefix) {
164 $qp->add_prefix($name, $prefix);
167 $self->{query_parser} = $qp;
170 sub ts_range_processor {
171 $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
174 sub date_range_processor {
175 $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
178 sub num_range_processor {
179 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
182 # only used for NNTP server
184 my ($self, $beg, $end, $offset) = @_;
185 my $enquire = $self->enquire;
186 my $qp = Search::Xapian::QueryParser->new;
187 $qp->set_database($self->{xdb});
188 $qp->add_valuerangeprocessor($self->num_range_processor);
189 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
190 $query = Search::Xapian::Query->new(OP_AND, $mail_query, $query);
191 $enquire->set_query($query);
192 $enquire->set_sort_by_value(NUM, 0);
194 my $mset = $enquire->get_mset($offset, $limit);
196 PublicInbox::SearchMsg->load_doc($_->get_document);
199 { total => $mset->get_matches_estimated, msgs => \@msgs }
203 my ($self, $mid) = @_;
204 $mid = mid_clean($mid);
206 my $doc_id = $self->find_unique_doc_id('mid', $mid);
208 if (defined $doc_id) {
210 my $doc = $self->{xdb}->get_document($doc_id);
211 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
212 $smsg->doc_id($doc_id);
217 sub find_unique_doc_id {
218 my ($self, $term, $value) = @_;
220 my ($begin, $end) = $self->find_doc_ids($term, $value);
222 return undef if $begin->equal($end); # not found
224 my $rv = $begin->get_docid;
228 $begin->equal($end) or die "Term '$term:$value' is not unique\n";
232 # returns begin and end PostingIterator
234 my ($self, $term, $value) = @_;
236 $self->find_doc_ids_for_term(xpfx($term) . $value);
239 # returns begin and end PostingIterator
240 sub find_doc_ids_for_term {
241 my ($self, $term) = @_;
242 my $db = $self->{xdb};
244 ($db->postlist_begin($term), $db->postlist_end($term));
247 # normalize subjects so they are suitable as pathnames for URLs
250 $subj = subject_normalized($subj);
251 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
255 sub subject_normalized {
257 $subj =~ s/\A\s+//s; # no leading space
258 $subj =~ s/\s+\z//s; # no trailing space
259 $subj =~ s/\s+/ /gs; # no redundant spaces
260 $subj =~ s/\.+\z//; # no trailing '.'
261 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
266 sub subject_summary {
269 if (length($subj) > $max) {
270 my @subj = split(/\s+/, $subj);
274 while ($l = shift @subj) {
275 my $new = $subj . $l . ' ';
276 last if length($new) >= $max;
280 my $r = scalar @subj ? ' ...' : '';
283 # subject has one REALLY long word, and NOT spam? wtf
284 @subj = ($l =~ /\A(.{1,72})/);
285 $subj = $subj[0] . ' ...';
293 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});