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