* Support pages with utf8 filenames. Patch by Faidon Liambotis.
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4 use warnings;
5 use strict;
6 use encoding "utf8";
7
8 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
9             %renderedfiles %pagesources %depends %hooks};
10
11 sub defaultconfig () { #{{{
12         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
13         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
14         wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
15         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
16         verbose => 0,
17         wikiname => "wiki",
18         default_pageext => ".mdwn",
19         cgi => 0,
20         rcs => 'svn',
21         notify => 0,
22         url => '',
23         cgiurl => '',
24         historyurl => '',
25         diffurl => '',
26         anonok => 0,
27         rss => 0,
28         discussion => 1,
29         rebuild => 0,
30         refresh => 0,
31         getctime => 0,
32         wrapper => undef,
33         wrappermode => undef,
34         svnrepo => undef,
35         svnpath => "trunk",
36         srcdir => undef,
37         destdir => undef,
38         pingurl => [],
39         templatedir => "/usr/share/ikiwiki/templates",
40         underlaydir => "/usr/share/ikiwiki/basewiki",
41         setup => undef,
42         adminuser => undef,
43         adminemail => undef,
44         plugin => [qw{inline htmlscrubber}],
45         timeformat => '%c',
46 } #}}}
47             
48 sub checkconfig () { #{{{
49         if ($config{cgi} && ! length $config{url}) {
50                 error("Must specify url to wiki with --url when using --cgi\n");
51         }
52         if ($config{rss} && ! length $config{url}) {
53                 error("Must specify url to wiki with --url when using --rss\n");
54         }
55         
56         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
57                 unless exists $config{wikistatedir};
58         
59         if ($config{rcs}) {
60                 eval qq{require IkiWiki::Rcs::$config{rcs}};
61                 if ($@) {
62                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
63                 }
64         }
65         else {
66                 require IkiWiki::Rcs::Stub;
67         }
68
69         foreach my $plugin (@{$config{plugin}}) {
70                 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
71                 eval qq{use $mod};
72                 if ($@) {
73                         error("Failed to load plugin $mod: $@");
74                 }
75         }
76
77         if (exists $hooks{checkconfig}) {
78                 foreach my $id (keys %{$hooks{checkconfig}}) {
79                         $hooks{checkconfig}{$id}{call}->();
80                 }
81         }
82 } #}}}
83
84 sub error ($) { #{{{
85         if ($config{cgi}) {
86                 print "Content-type: text/html\n\n";
87                 print misctemplate("Error", "<p>Error: @_</p>");
88         }
89         die @_;
90 } #}}}
91
92 sub debug ($) { #{{{
93         return unless $config{verbose};
94         if (! $config{cgi}) {
95                 print "@_\n";
96         }
97         else {
98                 print STDERR "@_\n";
99         }
100 } #}}}
101
102 sub possibly_foolish_untaint ($) { #{{{
103         my $tainted=shift;
104         my ($untainted)=$tainted=~/(.*)/;
105         return $untainted;
106 } #}}}
107
108 sub basename ($) { #{{{
109         my $file=shift;
110
111         $file=~s!.*/+!!;
112         return $file;
113 } #}}}
114
115 sub dirname ($) { #{{{
116         my $file=shift;
117
118         $file=~s!/*[^/]+$!!;
119         return $file;
120 } #}}}
121
122 sub pagetype ($) { #{{{
123         my $page=shift;
124         
125         if ($page =~ /\.mdwn$/) {
126                 return ".mdwn";
127         }
128         else {
129                 return "unknown";
130         }
131 } #}}}
132
133 sub pagename ($) { #{{{
134         my $file=shift;
135
136         my $type=pagetype($file);
137         my $page=$file;
138         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
139         return $page;
140 } #}}}
141
142 sub htmlpage ($) { #{{{
143         my $page=shift;
144
145         return $page.".html";
146 } #}}}
147
148 sub srcfile ($) { #{{{
149         my $file=shift;
150
151         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
152         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
153         error("internal error: $file cannot be found");
154 } #}}}
155
156 sub readfile ($;$) { #{{{
157         my $file=shift;
158         my $binary=shift;
159
160         if (-l $file) {
161                 error("cannot read a symlink ($file)");
162         }
163         
164         local $/=undef;
165         open (IN, $file) || error("failed to read $file: $!");
166         if (! $binary) {
167                 binmode(IN, ":utf8");
168         }
169         else {
170                 binmode(IN);
171         }
172         my $ret=<IN>;
173         close IN;
174         return $ret;
175 } #}}}
176
177 sub writefile ($$$;$) { #{{{
178         my $file=shift; # can include subdirs
179         my $destdir=shift; # directory to put file in
180         my $content=shift;
181         my $binary=shift;
182         
183         my $test=$file;
184         while (length $test) {
185                 if (-l "$destdir/$test") {
186                         error("cannot write to a symlink ($test)");
187                 }
188                 $test=dirname($test);
189         }
190
191         my $dir=dirname("$destdir/$file");
192         if (! -d $dir) {
193                 my $d="";
194                 foreach my $s (split(m!/+!, $dir)) {
195                         $d.="$s/";
196                         if (! -d $d) {
197                                 mkdir($d) || error("failed to create directory $d: $!");
198                         }
199                 }
200         }
201         
202         open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
203         if (! $binary) {
204                 binmode(OUT, ":utf8");
205         }
206         else {
207                 binmode(OUT);
208         }
209         print OUT $content;
210         close OUT;
211 } #}}}
212
213 sub bestlink ($$) { #{{{
214         # Given a page and the text of a link on the page, determine which
215         # existing page that link best points to. Prefers pages under a
216         # subdirectory with the same name as the source page, failing that
217         # goes down the directory tree to the base looking for matching
218         # pages.
219         my $page=shift;
220         my $link=lc(shift);
221         
222         my $cwd=$page;
223         do {
224                 my $l=$cwd;
225                 $l.="/" if length $l;
226                 $l.=$link;
227
228                 if (exists $links{$l}) {
229                         #debug("for $page, \"$link\", use $l");
230                         return $l;
231                 }
232         } while $cwd=~s!/?[^/]+$!!;
233
234         #print STDERR "warning: page $page, broken link: $link\n";
235         return "";
236 } #}}}
237
238 sub isinlinableimage ($) { #{{{
239         my $file=shift;
240         
241         $file=~/\.(png|gif|jpg|jpeg)$/i;
242 } #}}}
243
244 sub pagetitle ($) { #{{{
245         my $page=shift;
246         $page=~s/__(\d+)__/&#$1;/g;
247         $page=~y/_/ /;
248         return $page;
249 } #}}}
250
251 sub titlepage ($) { #{{{
252         my $title=shift;
253         $title=~y/ /_/;
254         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
255         return $title;
256 } #}}}
257
258 sub cgiurl (@) { #{{{
259         my %params=@_;
260
261         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
262 } #}}}
263
264 sub styleurl (;$) { #{{{
265         my $page=shift;
266
267         return "$config{url}/style.css" if ! defined $page;
268         
269         $page=~s/[^\/]+$//;
270         $page=~s/[^\/]+\//..\//g;
271         return $page."style.css";
272 } #}}}
273
274 sub htmllink ($$$;$$$) { #{{{
275         my $lpage=shift; # the page doing the linking
276         my $page=shift; # the page that will contain the link (different for inline)
277         my $link=shift;
278         my $noimageinline=shift; # don't turn links into inline html images
279         my $forcesubpage=shift; # force a link to a subpage
280         my $linktext=shift; # set to force the link text to something
281
282         my $bestlink;
283         if (! $forcesubpage) {
284                 $bestlink=bestlink($lpage, $link);
285         }
286         else {
287                 $bestlink="$lpage/".lc($link);
288         }
289
290         $linktext=pagetitle(basename($link)) unless defined $linktext;
291         
292         return $linktext if length $bestlink && $page eq $bestlink;
293         
294         # TODO BUG: %renderedfiles may not have it, if the linked to page
295         # was also added and isn't yet rendered! Note that this bug is
296         # masked by the bug that makes all new files be rendered twice.
297         if (! grep { $_ eq $bestlink } values %renderedfiles) {
298                 $bestlink=htmlpage($bestlink);
299         }
300         if (! grep { $_ eq $bestlink } values %renderedfiles) {
301                 return "<span><a href=\"".
302                         cgiurl(do => "create", page => $link, from => $page).
303                         "\">?</a>$linktext</span>"
304         }
305         
306         require File::Spec;
307         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
308         
309         if (! $noimageinline && isinlinableimage($bestlink)) {
310                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
311         }
312         return "<a href=\"$bestlink\">$linktext</a>";
313 } #}}}
314
315 sub indexlink () { #{{{
316         return "<a href=\"$config{url}\">$config{wikiname}</a>";
317 } #}}}
318
319 sub lockwiki () { #{{{
320         # Take an exclusive lock on the wiki to prevent multiple concurrent
321         # run issues. The lock will be dropped on program exit.
322         if (! -d $config{wikistatedir}) {
323                 mkdir($config{wikistatedir});
324         }
325         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
326                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
327         if (! flock(WIKILOCK, 2 | 4)) {
328                 debug("wiki seems to be locked, waiting for lock");
329                 my $wait=600; # arbitrary, but don't hang forever to 
330                               # prevent process pileup
331                 for (1..600) {
332                         return if flock(WIKILOCK, 2 | 4);
333                         sleep 1;
334                 }
335                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
336         }
337 } #}}}
338
339 sub unlockwiki () { #{{{
340         close WIKILOCK;
341 } #}}}
342
343 sub loadindex () { #{{{
344         open (IN, "<:utf8", "$config{wikistatedir}/index") || return;
345         while (<IN>) {
346                 $_=possibly_foolish_untaint($_);
347                 chomp;
348                 my %items;
349                 $items{link}=[];
350                 foreach my $i (split(/ /, $_)) {
351                         my ($item, $val)=split(/=/, $i, 2);
352                         push @{$items{$item}}, $val;
353                 }
354
355                 next unless exists $items{src}; # skip bad lines for now
356
357                 my $page=pagename($items{src}[0]);
358                 if (! $config{rebuild}) {
359                         $pagesources{$page}=$items{src}[0];
360                         $oldpagemtime{$page}=$items{mtime}[0];
361                         $oldlinks{$page}=[@{$items{link}}];
362                         $links{$page}=[@{$items{link}}];
363                         $depends{$page}=join(" ", @{$items{depends}})
364                                 if exists $items{depends};
365                         $renderedfiles{$page}=$items{dest}[0];
366                 }
367                 $pagectime{$page}=$items{ctime}[0];
368         }
369         close IN;
370 } #}}}
371
372 sub saveindex () { #{{{
373         if (! -d $config{wikistatedir}) {
374                 mkdir($config{wikistatedir});
375         }
376         open (OUT, ">:utf8", "$config{wikistatedir}/index") || 
377                 error("cannot write to $config{wikistatedir}/index: $!");
378         foreach my $page (keys %oldpagemtime) {
379                 next unless $oldpagemtime{$page};
380                 my $line="mtime=$oldpagemtime{$page} ".
381                         "ctime=$pagectime{$page} ".
382                         "src=$pagesources{$page} ".
383                         "dest=$renderedfiles{$page}";
384                 $line.=" link=$_" foreach @{$links{$page}};
385                 if (exists $depends{$page}) {
386                         $line.=" depends=$_" foreach split " ", $depends{$page};
387                 }
388                 print OUT $line."\n";
389         }
390         close OUT;
391 } #}}}
392
393 sub template_params (@) { #{{{
394         my $filename=shift;
395         
396         require Encode;
397         require HTML::Template;
398         return filter => sub {
399                         my $text_ref = shift;
400                         $$text_ref=&Encode::decode_utf8($$text_ref);
401                 },
402                 filename => "$config{templatedir}/$filename", @_;
403 } #}}}
404
405 sub template ($;@) { #{{{
406         HTML::Template->new(template_params(@_));
407 } #}}}
408
409 sub misctemplate ($$) { #{{{
410         my $title=shift;
411         my $pagebody=shift;
412         
413         my $template=template("misc.tmpl");
414         $template->param(
415                 title => $title,
416                 indexlink => indexlink(),
417                 wikiname => $config{wikiname},
418                 pagebody => $pagebody,
419                 styleurl => styleurl(),
420                 baseurl => "$config{url}/",
421         );
422         return $template->output;
423 }#}}}
424
425 sub glob_match ($$) { #{{{
426         my $page=shift;
427         my $glob=shift;
428
429         if ($glob =~ /^link\((.+)\)$/) {
430                 my $rev = $links{$page} or return undef;
431                 foreach my $p (@$rev) {
432                         return 1 if lc $p eq $1;
433                 }
434                 return 0;
435         } elsif ($glob =~ /^backlink\((.+)\)$/) {
436                 my $rev = $links{$1} or return undef;
437                 foreach my $p (@$rev) {
438                         return 1 if lc $p eq $page;
439                 }
440                 return 0;
441         } else {
442                 # turn glob into safe regexp
443                 $glob=quotemeta($glob);
444                 $glob=~s/\\\*/.*/g;
445                 $glob=~s/\\\?/./g;
446                 $glob=~s!\\/!/!g;
447                 
448                 return $page=~/^$glob$/i;
449         }
450 } #}}}
451
452 sub globlist_match ($$) { #{{{
453         my $page=shift;
454         my @globlist=split(" ", shift);
455
456         # check any negated globs first
457         foreach my $glob (@globlist) {
458                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
459         }
460
461         foreach my $glob (@globlist) {
462                 return 1 if glob_match($page, $glob);
463         }
464         
465         return 0;
466 } #}}}
467
468 sub hook (@) { # {{{
469         my %param=@_;
470         
471         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
472                 error "hook requires type, call, and id parameters";
473         }
474         
475         $hooks{$param{type}}{$param{id}}=\%param;
476 } # }}}
477
478 1