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