Merge remote branch 'davrieb/autotag' into autotag
[ikiwiki] / IkiWiki / Plugin / search.pm
1 #!/usr/bin/perl
2 # xapian-omega search engine plugin
3 package IkiWiki::Plugin::search;
4
5 use warnings;
6 use strict;
7 use IkiWiki 3.00;
8
9 sub import {
10         hook(type => "getsetup", id => "search", call => \&getsetup);
11         hook(type => "checkconfig", id => "search", call => \&checkconfig);
12         hook(type => "pagetemplate", id => "search", call => \&pagetemplate);
13         hook(type => "postscan", id => "search", call => \&index);
14         hook(type => "delete", id => "search", call => \&delete);
15         hook(type => "cgi", id => "search", call => \&cgi);
16 }
17
18 sub getsetup () {
19         return
20                 plugin => {
21                         safe => 1,
22                         rebuild => 1,
23                         section => "web",
24                 },
25                 omega_cgi => {
26                         type => "string",
27                         example => "/usr/lib/cgi-bin/omega/omega",
28                         description => "path to the omega cgi program",
29                         safe => 0, # external program
30                         rebuild => 0,
31                 },
32 }
33
34 sub checkconfig () {
35         foreach my $required (qw(url cgiurl)) {
36                 if (! length $config{$required}) {
37                         error(sprintf(gettext("Must specify %s when using the %s plugin"), $required, 'search'));
38                 }
39         }
40         
41         if (! defined $config{omega_cgi}) {
42                 $config{omega_cgi}="/usr/lib/cgi-bin/omega/omega";
43         }
44 }
45
46 my $form;
47 sub pagetemplate (@) {
48         my %params=@_;
49         my $page=$params{page};
50         my $template=$params{template};
51
52         # Add search box to page header.
53         if ($template->query(name => "searchform")) {
54                 if (! defined $form) {
55                         my $searchform = template("searchform.tmpl", blind_cache => 1);
56                         $searchform->param(searchaction => $config{cgiurl});
57                         $form=$searchform->output;
58                 }
59
60                 $template->param(searchform => $form);
61         }
62 }
63
64 my $scrubber;
65 my $stemmer;
66 sub index (@) {
67         my %params=@_;
68
69         setupfiles();
70
71         # A unique pageterm is used to identify the document for a page.
72         my $pageterm=pageterm($params{page});
73         return $params{content} unless defined $pageterm;
74         
75         my $db=xapiandb();
76         my $doc=Search::Xapian::Document->new();
77         my $caption=pagetitle($params{page});
78         my $title;
79         if (exists $pagestate{$params{page}}{meta} &&
80                 exists $pagestate{$params{page}}{meta}{title}) {
81                 $title=$pagestate{$params{page}}{meta}{title};
82         }
83         else {
84                 $title=$caption;
85         }
86
87         # Remove html from text to be indexed.
88         if (! defined $scrubber) {
89                 eval q{use HTML::Scrubber};
90                 if (! $@) {
91                         $scrubber=HTML::Scrubber->new(allow => []);
92                 }
93         }
94         my $toindex = defined $scrubber ? $scrubber->scrub($params{content}) : $params{content};
95         
96         # Take 512 characters for a sample, then extend it out
97         # if it stopped in the middle of a word.
98         my $size=512;
99         my ($sample)=substr($toindex, 0, $size);
100         if (length($sample) == $size) {
101                 my $max=length($toindex);
102                 my $next;
103                 while ($size < $max &&
104                        ($next=substr($toindex, $size++, 1)) !~ /\s/) {
105                         $sample.=$next;
106                 }
107         }
108         $sample=~s/\n/ /g;
109         
110         # data used by omega
111         # Decode html entities in it, since omega re-encodes them.
112         eval q{use HTML::Entities};
113         error $@ if $@;
114         $doc->set_data(
115                 "url=".urlto($params{page}, "")."\n".
116                 "sample=".decode_entities($sample)."\n".
117                 "caption=".decode_entities($caption)."\n".
118                 "modtime=$IkiWiki::pagemtime{$params{page}}\n".
119                 "size=".length($params{content})."\n"
120         );
121
122         # Index document and add terms for other metadata.
123         my $tg = Search::Xapian::TermGenerator->new();
124         if (! $stemmer) {
125                 my $langcode=$ENV{LANG} || "en";
126                 $langcode=~s/_.*//;
127
128                 # This whitelist is here to work around a xapian bug (#486138)
129                 my @whitelist=qw{da de en es fi fr hu it no pt ru ro sv tr};
130
131                 if (grep { $_ eq $langcode } @whitelist) {
132                         $stemmer=Search::Xapian::Stem->new($langcode);
133                 }
134                 else {
135                         $stemmer=Search::Xapian::Stem->new("english");
136                 }
137         }
138         $tg->set_stemmer($stemmer);
139         $tg->set_document($doc);
140         $tg->index_text($params{page}, 2);
141         $tg->index_text($caption, 2);
142         $tg->index_text($title, 2) if $title ne $caption;
143         $tg->index_text($toindex);
144         $tg->index_text(lc($title), 1, "S"); # for title:foo
145         foreach my $link (@{$links{$params{page}}}) {
146                 $tg->index_text(lc($link), 1, "XLINK"); # for link:bar
147         }
148
149         $doc->add_term($pageterm);
150         $db->replace_document_by_term($pageterm, $doc);
151 }
152
153 sub delete (@) {
154         my $db=xapiandb();
155         foreach my $page (@_) {
156                 my $pageterm=pageterm(pagename($page));
157                 $db->delete_document_by_term($pageterm) if defined $pageterm;
158         }
159 }
160
161 sub cgi ($) {
162         my $cgi=shift;
163
164         if (defined $cgi->param('P')) {
165                 # only works for GET requests
166                 chdir("$config{wikistatedir}/xapian") || error("chdir: $!");
167                 $ENV{OMEGA_CONFIG_FILE}="./omega.conf";
168                 $ENV{CGIURL}=$config{cgiurl},
169                 IkiWiki::loadindex();
170                 $ENV{HELPLINK}=htmllink("", "", "ikiwiki/searching",
171                         noimageinline => 1, linktext => "Help");
172                 exec($config{omega_cgi}) || error("$config{omega_cgi} failed: $!");
173         }
174 }
175
176 sub pageterm ($) {
177         my $page=shift;
178
179         # 240 is the number used by omindex to decide when to hash an
180         # overlong term. This does not use a compatible hash method though.
181         if (length $page > 240) {
182                 eval q{use Digest::SHA1};
183                 if ($@) {
184                         debug("search: ".sprintf(gettext("need Digest::SHA1 to index %s"), $page)) if $@;
185                         return undef;
186                 }
187
188                 # Note no colon, therefore it's guaranteed to not overlap
189                 # with a page with the same name as the hash..
190                 return "U".lc(Digest::SHA1::sha1_hex($page));
191         }
192         else {
193                 return "U:".$page;
194         }
195 }
196
197 my $db;
198 sub xapiandb () {
199         if (! defined $db) {
200                 eval q{
201                         use Search::Xapian;
202                         use Search::Xapian::WritableDatabase;
203                 };
204                 error($@) if $@;
205                 $db=Search::Xapian::WritableDatabase->new($config{wikistatedir}."/xapian/default",
206                         Search::Xapian::DB_CREATE_OR_OPEN());
207         }
208         return $db;
209 }
210
211 {
212 my $setup=0;
213 sub setupfiles () {
214         if (! $setup and (! -e $config{wikistatedir}."/xapian" || $config{rebuild})) {
215                 writefile("omega.conf", $config{wikistatedir}."/xapian",
216                         "database_dir .\n".
217                         "template_dir ./templates\n");
218                 
219                 # Avoid omega interpreting anything in the misctemplate
220                 # as an omegascript command.
221                 my $misctemplate=IkiWiki::misctemplate(gettext("search"), "\0");
222                 eval q{use HTML::Entities};
223                 error $@ if $@;
224                 $misctemplate=encode_entities($misctemplate, '\$');
225
226                 my $querytemplate=readfile(IkiWiki::template_file("searchquery.tmpl"));
227                 $misctemplate=~s/\0/$querytemplate/;
228
229                 writefile("query", $config{wikistatedir}."/xapian/templates",
230                         $misctemplate);
231                 $setup=1;
232         }
233 }
234 }
235
236 1