Add test for old versions of git that don't support --cleanup=verbatim, and munge...
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX;
11 use Storable;
12 use open qw{:utf8 :std};
13
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %renderedfiles %oldrenderedfiles %pagesources
16             %destsources %depends %hooks %forcerebuild $gettext_obj};
17
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20                  bestlink htmllink readfile writefile pagetype srcfile pagename
21                  displaytime will_render gettext urlto targetpage
22                  add_underlay
23                  %config %links %pagestate %renderedfiles
24                  %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28
29 # Optimisation.
30 use Memoize;
31 memoize("abs2rel");
32 memoize("pagespec_translate");
33 memoize("file_pruned");
34
35 sub defaultconfig () { #{{{
36         return
37         wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
38                 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
39                 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
40                 qr/(^|\/)_MTN\//,
41                 qr/\.dpkg-tmp$/],
42         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
43         web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
44         verbose => 0,
45         syslog => 0,
46         wikiname => "wiki",
47         default_pageext => "mdwn",
48         htmlext => "html",
49         cgi => 0,
50         post_commit => 0,
51         rcs => '',
52         url => '',
53         cgiurl => '',
54         historyurl => '',
55         diffurl => '',
56         rss => 0,
57         atom => 0,
58         allowrss => 0,
59         allowatom => 0,
60         discussion => 1,
61         rebuild => 0,
62         refresh => 0,
63         getctime => 0,
64         w3mmode => 0,
65         wrapper => undef,
66         wrappermode => undef,
67         svnpath => "trunk",
68         gitorigin_branch => "origin",
69         gitmaster_branch => "master",
70         srcdir => undef,
71         destdir => undef,
72         pingurl => [],
73         templatedir => "$installdir/share/ikiwiki/templates",
74         underlaydir => "$installdir/share/ikiwiki/basewiki",
75         underlaydirs => [],
76         setup => undef,
77         adminuser => undef,
78         adminemail => undef,
79         plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
80                         signinedit lockedit conditional recentchanges
81                         parentlinks}],
82         libdir => undef,
83         timeformat => '%c',
84         locale => undef,
85         sslcookie => 0,
86         httpauth => 0,
87         userdir => "",
88         usedirs => 1,
89         numbacklinks => 10,
90         account_creation_password => "",
91         prefix_directives => 0,
92         hardlink => 0,
93         cgi_disable_uploads => 1,
94 } #}}}
95
96 sub checkconfig () { #{{{
97         # locale stuff; avoid LC_ALL since it overrides everything
98         if (defined $ENV{LC_ALL}) {
99                 $ENV{LANG} = $ENV{LC_ALL};
100                 delete $ENV{LC_ALL};
101         }
102         if (defined $config{locale}) {
103                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
104                         $ENV{LANG}=$config{locale};
105                         $gettext_obj=undef;
106                 }
107         }
108
109         if (ref $config{ENV} eq 'HASH') {
110                 foreach my $val (keys %{$config{ENV}}) {
111                         $ENV{$val}=$config{ENV}{$val};
112                 }
113         }
114
115         if ($config{w3mmode}) {
116                 eval q{use Cwd q{abs_path}};
117                 error($@) if $@;
118                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
119                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
120                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
121                         unless $config{cgiurl} =~ m!file:///!;
122                 $config{url}="file://".$config{destdir};
123         }
124
125         if ($config{cgi} && ! length $config{url}) {
126                 error(gettext("Must specify url to wiki with --url when using --cgi"));
127         }
128         
129         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
130                 unless exists $config{wikistatedir};
131         
132         if ($config{rcs}) {
133                 eval qq{use IkiWiki::Rcs::$config{rcs}};
134                 if ($@) {
135                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
136                 }
137         }
138         else {
139                 require IkiWiki::Rcs::Stub;
140         }
141
142         if (exists $config{umask}) {
143                 umask(possibly_foolish_untaint($config{umask}));
144         }
145
146         run_hooks(checkconfig => sub { shift->() });
147
148         return 1;
149 } #}}}
150
151 sub loadplugins () { #{{{
152         if (defined $config{libdir}) {
153                 unshift @INC, possibly_foolish_untaint($config{libdir});
154         }
155
156         loadplugin($_) foreach @{$config{plugin}};
157
158         run_hooks(getopt => sub { shift->() });
159         if (grep /^-/, @ARGV) {
160                 print STDERR "Unknown option: $_\n"
161                         foreach grep /^-/, @ARGV;
162                 usage();
163         }
164
165         return 1;
166 } #}}}
167
168 sub loadplugin ($) { #{{{
169         my $plugin=shift;
170
171         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
172
173         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
174                          "$installdir/lib/ikiwiki") {
175                 if (defined $dir && -x "$dir/plugins/$plugin") {
176                         require IkiWiki::Plugin::external;
177                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
178                         return 1;
179                 }
180         }
181
182         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
183         eval qq{use $mod};
184         if ($@) {
185                 error("Failed to load plugin $mod: $@");
186         }
187         return 1;
188 } #}}}
189
190 sub error ($;$) { #{{{
191         my $message=shift;
192         my $cleaner=shift;
193         log_message('err' => $message) if $config{syslog};
194         if (defined $cleaner) {
195                 $cleaner->();
196         }
197         die $message."\n";
198 } #}}}
199
200 sub debug ($) { #{{{
201         return unless $config{verbose};
202         return log_message(debug => @_);
203 } #}}}
204
205 my $log_open=0;
206 sub log_message ($$) { #{{{
207         my $type=shift;
208
209         if ($config{syslog}) {
210                 require Sys::Syslog;
211                 if (! $log_open) {
212                         Sys::Syslog::setlogsock('unix');
213                         Sys::Syslog::openlog('ikiwiki', '', 'user');
214                         $log_open=1;
215                 }
216                 return eval {
217                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
218                 };
219         }
220         elsif (! $config{cgi}) {
221                 return print "@_\n";
222         }
223         else {
224                 return print STDERR "@_\n";
225         }
226 } #}}}
227
228 sub possibly_foolish_untaint ($) { #{{{
229         my $tainted=shift;
230         my ($untainted)=$tainted=~/(.*)/s;
231         return $untainted;
232 } #}}}
233
234 sub basename ($) { #{{{
235         my $file=shift;
236
237         $file=~s!.*/+!!;
238         return $file;
239 } #}}}
240
241 sub dirname ($) { #{{{
242         my $file=shift;
243
244         $file=~s!/*[^/]+$!!;
245         return $file;
246 } #}}}
247
248 sub pagetype ($) { #{{{
249         my $page=shift;
250         
251         if ($page =~ /\.([^.]+)$/) {
252                 return $1 if exists $hooks{htmlize}{$1};
253         }
254         return;
255 } #}}}
256
257 sub isinternal ($) { #{{{
258         my $page=shift;
259         return exists $pagesources{$page} &&
260                 $pagesources{$page} =~ /\._([^.]+)$/;
261 } #}}}
262
263 sub pagename ($) { #{{{
264         my $file=shift;
265
266         my $type=pagetype($file);
267         my $page=$file;
268         $page=~s/\Q.$type\E*$// if defined $type;
269         return $page;
270 } #}}}
271
272 sub targetpage ($$) { #{{{
273         my $page=shift;
274         my $ext=shift;
275         
276         if (! $config{usedirs} || $page =~ /^index$/ ) {
277                 return $page.".".$ext;
278         } else {
279                 return $page."/index.".$ext;
280         }
281 } #}}}
282
283 sub htmlpage ($) { #{{{
284         my $page=shift;
285         
286         return targetpage($page, $config{htmlext});
287 } #}}}
288
289 sub srcfile_stat { #{{{
290         my $file=shift;
291         my $nothrow=shift;
292
293         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
294         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
295                 return "$dir/$file", stat(_) if -e "$dir/$file";
296         }
297         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
298         return;
299 } #}}}
300
301 sub srcfile ($;$) { #{{{
302         return (srcfile_stat(@_))[0];
303 } #}}}
304
305 sub add_underlay ($) { #{{{
306         my $dir=shift;
307
308         if ($dir=~/^\//) {
309                 unshift @{$config{underlaydirs}}, $dir;
310         }
311         else {
312                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
313         }
314
315         return 1;
316 } #}}}
317
318 sub readfile ($;$$) { #{{{
319         my $file=shift;
320         my $binary=shift;
321         my $wantfd=shift;
322
323         if (-l $file) {
324                 error("cannot read a symlink ($file)");
325         }
326         
327         local $/=undef;
328         open (my $in, "<", $file) || error("failed to read $file: $!");
329         binmode($in) if ($binary);
330         return \*$in if $wantfd;
331         my $ret=<$in>;
332         close $in || error("failed to read $file: $!");
333         return $ret;
334 } #}}}
335
336 sub prep_writefile ($$) { #{{{
337         my $file=shift;
338         my $destdir=shift;
339         
340         my $test=$file;
341         while (length $test) {
342                 if (-l "$destdir/$test") {
343                         error("cannot write to a symlink ($test)");
344                 }
345                 $test=dirname($test);
346         }
347
348         my $dir=dirname("$destdir/$file");
349         if (! -d $dir) {
350                 my $d="";
351                 foreach my $s (split(m!/+!, $dir)) {
352                         $d.="$s/";
353                         if (! -d $d) {
354                                 mkdir($d) || error("failed to create directory $d: $!");
355                         }
356                 }
357         }
358
359         return 1;
360 } #}}}
361
362 sub writefile ($$$;$$) { #{{{
363         my $file=shift; # can include subdirs
364         my $destdir=shift; # directory to put file in
365         my $content=shift;
366         my $binary=shift;
367         my $writer=shift;
368         
369         prep_writefile($file, $destdir);
370         
371         my $newfile="$destdir/$file.ikiwiki-new";
372         if (-l $newfile) {
373                 error("cannot write to a symlink ($newfile)");
374         }
375         
376         my $cleanup = sub { unlink($newfile) };
377         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
378         binmode($out) if ($binary);
379         if ($writer) {
380                 $writer->(\*$out, $cleanup);
381         }
382         else {
383                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
384         }
385         close $out || error("failed saving $newfile: $!", $cleanup);
386         rename($newfile, "$destdir/$file") || 
387                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
388
389         return 1;
390 } #}}}
391
392 my %cleared;
393 sub will_render ($$;$) { #{{{
394         my $page=shift;
395         my $dest=shift;
396         my $clear=shift;
397
398         # Important security check.
399         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
400             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
401                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
402         }
403
404         if (! $clear || $cleared{$page}) {
405                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
406         }
407         else {
408                 foreach my $old (@{$renderedfiles{$page}}) {
409                         delete $destsources{$old};
410                 }
411                 $renderedfiles{$page}=[$dest];
412                 $cleared{$page}=1;
413         }
414         $destsources{$dest}=$page;
415
416         return 1;
417 } #}}}
418
419 sub bestlink ($$) { #{{{
420         my $page=shift;
421         my $link=shift;
422         
423         my $cwd=$page;
424         if ($link=~s/^\/+//) {
425                 # absolute links
426                 $cwd="";
427         }
428         $link=~s/\/$//;
429
430         do {
431                 my $l=$cwd;
432                 $l.="/" if length $l;
433                 $l.=$link;
434
435                 if (exists $links{$l}) {
436                         return $l;
437                 }
438                 elsif (exists $pagecase{lc $l}) {
439                         return $pagecase{lc $l};
440                 }
441         } while $cwd=~s!/?[^/]+$!!;
442
443         if (length $config{userdir}) {
444                 my $l = "$config{userdir}/".lc($link);
445                 if (exists $links{$l}) {
446                         return $l;
447                 }
448                 elsif (exists $pagecase{lc $l}) {
449                         return $pagecase{lc $l};
450                 }
451         }
452
453         #print STDERR "warning: page $page, broken link: $link\n";
454         return "";
455 } #}}}
456
457 sub isinlinableimage ($) { #{{{
458         my $file=shift;
459         
460         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
461 } #}}}
462
463 sub pagetitle ($;$) { #{{{
464         my $page=shift;
465         my $unescaped=shift;
466
467         if ($unescaped) {
468                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
469         }
470         else {
471                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
472         }
473
474         return $page;
475 } #}}}
476
477 sub titlepage ($) { #{{{
478         my $title=shift;
479         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
480         return $title;
481 } #}}}
482
483 sub linkpage ($) { #{{{
484         my $link=shift;
485         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
486         return $link;
487 } #}}}
488
489 sub cgiurl (@) { #{{{
490         my %params=@_;
491
492         return $config{cgiurl}."?".
493                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
494 } #}}}
495
496 sub baseurl (;$) { #{{{
497         my $page=shift;
498
499         return "$config{url}/" if ! defined $page;
500         
501         $page=htmlpage($page);
502         $page=~s/[^\/]+$//;
503         $page=~s/[^\/]+\//..\//g;
504         return $page;
505 } #}}}
506
507 sub abs2rel ($$) { #{{{
508         # Work around very innefficient behavior in File::Spec if abs2rel
509         # is passed two relative paths. It's much faster if paths are
510         # absolute! (Debian bug #376658; fixed in debian unstable now)
511         my $path="/".shift;
512         my $base="/".shift;
513
514         require File::Spec;
515         my $ret=File::Spec->abs2rel($path, $base);
516         $ret=~s/^// if defined $ret;
517         return $ret;
518 } #}}}
519
520 sub displaytime ($;$) { #{{{
521         my $time=shift;
522         my $format=shift;
523         if (! defined $format) {
524                 $format=$config{timeformat};
525         }
526
527         # strftime doesn't know about encodings, so make sure
528         # its output is properly treated as utf8
529         return decode_utf8(POSIX::strftime($format, localtime($time)));
530 } #}}}
531
532 sub beautify_urlpath ($) { #{{{
533         my $url=shift;
534
535         if ($config{usedirs}) {
536                 $url =~ s!/index.$config{htmlext}$!/!;
537         }
538
539         # Ensure url is not an empty link, and
540         # if it's relative, make that explicit to avoid colon confusion.
541         if ($url !~ /^\//) {
542                 $url="./$url";
543         }
544
545         return $url;
546 } #}}}
547
548 sub urlto ($$;$) { #{{{
549         my $to=shift;
550         my $from=shift;
551         my $absolute=shift;
552         
553         if (! length $to) {
554                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
555         }
556
557         if (! $destsources{$to}) {
558                 $to=htmlpage($to);
559         }
560
561         if ($absolute) {
562                 return $config{url}.beautify_urlpath("/".$to);
563         }
564
565         my $link = abs2rel($to, dirname(htmlpage($from)));
566
567         return beautify_urlpath($link);
568 } #}}}
569
570 sub htmllink ($$$;@) { #{{{
571         my $lpage=shift; # the page doing the linking
572         my $page=shift; # the page that will contain the link (different for inline)
573         my $link=shift;
574         my %opts=@_;
575
576         $link=~s/\/$//;
577
578         my $bestlink;
579         if (! $opts{forcesubpage}) {
580                 $bestlink=bestlink($lpage, $link);
581         }
582         else {
583                 $bestlink="$lpage/".lc($link);
584         }
585
586         my $linktext;
587         if (defined $opts{linktext}) {
588                 $linktext=$opts{linktext};
589         }
590         else {
591                 $linktext=pagetitle(basename($link));
592         }
593         
594         return "<span class=\"selflink\">$linktext</span>"
595                 if length $bestlink && $page eq $bestlink &&
596                    ! defined $opts{anchor};
597         
598         if (! $destsources{$bestlink}) {
599                 $bestlink=htmlpage($bestlink);
600
601                 if (! $destsources{$bestlink}) {
602                         return $linktext unless length $config{cgiurl};
603                         return "<span class=\"createlink\"><a href=\"".
604                                 cgiurl(
605                                         do => "create",
606                                         page => lc($link),
607                                         from => $lpage
608                                 ).
609                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
610                 }
611         }
612         
613         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
614         $bestlink=beautify_urlpath($bestlink);
615         
616         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
617                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
618         }
619
620         if (defined $opts{anchor}) {
621                 $bestlink.="#".$opts{anchor};
622         }
623
624         my @attrs;
625         if (defined $opts{rel}) {
626                 push @attrs, ' rel="'.$opts{rel}.'"';
627         }
628         if (defined $opts{class}) {
629                 push @attrs, ' class="'.$opts{class}.'"';
630         }
631
632         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
633 } #}}}
634
635 sub userlink ($) { #{{{
636         my $user=shift;
637
638         my $oiduser=eval { openiduser($user) };
639         if (defined $oiduser) {
640                 return "<a href=\"$user\">$oiduser</a>";
641         }
642         else {
643                 eval q{use CGI 'escapeHTML'};
644                 error($@) if $@;
645
646                 return htmllink("", "", escapeHTML(
647                         length $config{userdir} ? $config{userdir}."/".$user : $user
648                 ), noimageinline => 1);
649         }
650 } #}}}
651
652 sub htmlize ($$$$) { #{{{
653         my $page=shift;
654         my $destpage=shift;
655         my $type=shift;
656         my $content=shift;
657         
658         my $oneline = $content !~ /\n/;
659
660         if (exists $hooks{htmlize}{$type}) {
661                 $content=$hooks{htmlize}{$type}{call}->(
662                         page => $page,
663                         content => $content,
664                 );
665         }
666         else {
667                 error("htmlization of $type not supported");
668         }
669
670         run_hooks(sanitize => sub {
671                 $content=shift->(
672                         page => $page,
673                         destpage => $destpage,
674                         content => $content,
675                 );
676         });
677         
678         if ($oneline) {
679                 # hack to get rid of enclosing junk added by markdown
680                 # and other htmlizers
681                 $content=~s/^<p>//i;
682                 $content=~s/<\/p>$//i;
683                 chomp $content;
684         }
685
686         return $content;
687 } #}}}
688
689 sub linkify ($$$) { #{{{
690         my $page=shift;
691         my $destpage=shift;
692         my $content=shift;
693
694         run_hooks(linkify => sub {
695                 $content=shift->(
696                         page => $page,
697                         destpage => $destpage,
698                         content => $content,
699                 );
700         });
701         
702         return $content;
703 } #}}}
704
705 our %preprocessing;
706 our $preprocess_preview=0;
707 sub preprocess ($$$;$$) { #{{{
708         my $page=shift; # the page the data comes from
709         my $destpage=shift; # the page the data will appear in (different for inline)
710         my $content=shift;
711         my $scan=shift;
712         my $preview=shift;
713
714         # Using local because it needs to be set within any nested calls
715         # of this function.
716         local $preprocess_preview=$preview if defined $preview;
717
718         my $handle=sub {
719                 my $escape=shift;
720                 my $prefix=shift;
721                 my $command=shift;
722                 my $params=shift;
723                 if (length $escape) {
724                         return "[[$prefix$command $params]]";
725                 }
726                 elsif (exists $hooks{preprocess}{$command}) {
727                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
728                         # Note: preserve order of params, some plugins may
729                         # consider it significant.
730                         my @params;
731                         while ($params =~ m{
732                                 (?:([-\w]+)=)?          # 1: named parameter key?
733                                 (?:
734                                         """(.*?)"""     # 2: triple-quoted value
735                                 |
736                                         "([^"]+)"       # 3: single-quoted value
737                                 |
738                                         (\S+)           # 4: unquoted value
739                                 )
740                                 (?:\s+|$)               # delimiter to next param
741                         }sgx) {
742                                 my $key=$1;
743                                 my $val;
744                                 if (defined $2) {
745                                         $val=$2;
746                                         $val=~s/\r\n/\n/mg;
747                                         $val=~s/^\n+//g;
748                                         $val=~s/\n+$//g;
749                                 }
750                                 elsif (defined $3) {
751                                         $val=$3;
752                                 }
753                                 elsif (defined $4) {
754                                         $val=$4;
755                                 }
756
757                                 if (defined $key) {
758                                         push @params, $key, $val;
759                                 }
760                                 else {
761                                         push @params, $val, '';
762                                 }
763                         }
764                         if ($preprocessing{$page}++ > 3) {
765                                 # Avoid loops of preprocessed pages preprocessing
766                                 # other pages that preprocess them, etc.
767                                 return "[[!$command <span class=\"error\">".
768                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
769                                                 $page, $preprocessing{$page}).
770                                         "</span>]]";
771                         }
772                         my $ret;
773                         if (! $scan) {
774                                 $ret=eval {
775                                         $hooks{preprocess}{$command}{call}->(
776                                                 @params,
777                                                 page => $page,
778                                                 destpage => $destpage,
779                                                 preview => $preprocess_preview,
780                                         );
781                                 };
782                                 if ($@) {
783                                         chomp $@;
784                                         $ret="[[!$command <span class=\"error\">".
785                                                 gettext("Error").": $@"."</span>]]";
786                                 }
787                         }
788                         else {
789                                 # use void context during scan pass
790                                 eval {
791                                         $hooks{preprocess}{$command}{call}->(
792                                                 @params,
793                                                 page => $page,
794                                                 destpage => $destpage,
795                                                 preview => $preprocess_preview,
796                                         );
797                                 };
798                                 $ret="";
799                         }
800                         $preprocessing{$page}--;
801                         return $ret;
802                 }
803                 else {
804                         return "[[$prefix$command $params]]";
805                 }
806         };
807         
808         my $regex;
809         if ($config{prefix_directives}) {
810                 $regex = qr{
811                         (\\?)           # 1: escape?
812                         \[\[(!)         # directive open; 2: prefix
813                         ([-\w]+)        # 3: command
814                         (               # 4: the parameters..
815                                 \s+     # Must have space if parameters present
816                                 (?:
817                                         (?:[-\w]+=)?            # named parameter key?
818                                         (?:
819                                                 """.*?"""       # triple-quoted value
820                                                 |
821                                                 "[^"]+"         # single-quoted value
822                                                 |
823                                                 [^\s\]]+        # unquoted value
824                                         )
825                                         \s*                     # whitespace or end
826                                                                 # of directive
827                                 )
828                         *)?             # 0 or more parameters
829                         \]\]            # directive closed
830                 }sx;
831         }
832         else {
833                 $regex = qr{
834                         (\\?)           # 1: escape?
835                         \[\[(!?)        # directive open; 2: optional prefix
836                         ([-\w]+)        # 3: command
837                         \s+
838                         (               # 4: the parameters..
839                                 (?:
840                                         (?:[-\w]+=)?            # named parameter key?
841                                         (?:
842                                                 """.*?"""       # triple-quoted value
843                                                 |
844                                                 "[^"]+"         # single-quoted value
845                                                 |
846                                                 [^\s\]]+        # unquoted value
847                                         )
848                                         \s*                     # whitespace or end
849                                                                 # of directive
850                                 )
851                         *)              # 0 or more parameters
852                         \]\]            # directive closed
853                 }sx;
854         }
855
856         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
857         return $content;
858 } #}}}
859
860 sub filter ($$$) { #{{{
861         my $page=shift;
862         my $destpage=shift;
863         my $content=shift;
864
865         run_hooks(filter => sub {
866                 $content=shift->(page => $page, destpage => $destpage, 
867                         content => $content);
868         });
869
870         return $content;
871 } #}}}
872
873 sub indexlink () { #{{{
874         return "<a href=\"$config{url}\">$config{wikiname}</a>";
875 } #}}}
876
877 my $wikilock;
878
879 sub lockwiki (;$) { #{{{
880         my $wait=@_ ? shift : 1;
881         # Take an exclusive lock on the wiki to prevent multiple concurrent
882         # run issues. The lock will be dropped on program exit.
883         if (! -d $config{wikistatedir}) {
884                 mkdir($config{wikistatedir});
885         }
886         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
887                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
888         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
889                 if ($wait) {
890                         debug("wiki seems to be locked, waiting for lock");
891                         my $wait=600; # arbitrary, but don't hang forever to 
892                                       # prevent process pileup
893                         for (1..$wait) {
894                                 return if flock($wikilock, 2 | 4);
895                                 sleep 1;
896                         }
897                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
898                 }
899                 else {
900                         return 0;
901                 }
902         }
903         return 1;
904 } #}}}
905
906 sub unlockwiki () { #{{{
907         return close($wikilock) if $wikilock;
908         return;
909 } #}}}
910
911 my $commitlock;
912
913 sub commit_hook_enabled () { #{{{
914         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
915                 error("cannot write to $config{wikistatedir}/commitlock: $!");
916         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
917                 close($commitlock) || error("failed closing commitlock: $!");
918                 return 0;
919         }
920         close($commitlock) || error("failed closing commitlock: $!");
921         return 1;
922 } #}}}
923
924 sub disable_commit_hook () { #{{{
925         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
926                 error("cannot write to $config{wikistatedir}/commitlock: $!");
927         if (! flock($commitlock, 2)) { # LOCK_EX
928                 error("failed to get commit lock");
929         }
930         return 1;
931 } #}}}
932
933 sub enable_commit_hook () { #{{{
934         return close($commitlock) if $commitlock;
935         return;
936 } #}}}
937
938 sub loadindex () { #{{{
939         %oldrenderedfiles=%pagectime=();
940         if (! $config{rebuild}) {
941                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
942                 %destsources=%renderedfiles=%pagecase=%pagestate=();
943         }
944         my $in;
945         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
946                 if (-e "$config{wikistatedir}/index") {
947                         system("ikiwiki-transition", "indexdb", $config{srcdir});
948                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
949                 }
950                 else {
951                         return;
952                 }
953         }
954         my $ret=Storable::fd_retrieve($in);
955         if (! defined $ret) {
956                 return 0;
957         }
958         my %index=%$ret;
959         foreach my $src (keys %index) {
960                 my %d=%{$index{$src}};
961                 my $page=pagename($src);
962                 $pagectime{$page}=$d{ctime};
963                 if (! $config{rebuild}) {
964                         $pagesources{$page}=$src;
965                         $pagemtime{$page}=$d{mtime};
966                         $renderedfiles{$page}=$d{dest};
967                         if (exists $d{links} && ref $d{links}) {
968                                 $links{$page}=$d{links};
969                                 $oldlinks{$page}=[@{$d{links}}];
970                         }
971                         if (exists $d{depends}) {
972                                 $depends{$page}=$d{depends};
973                         }
974                         if (exists $d{state}) {
975                                 $pagestate{$page}=$d{state};
976                         }
977                 }
978                 $oldrenderedfiles{$page}=[@{$d{dest}}];
979         }
980         foreach my $page (keys %pagesources) {
981                 $pagecase{lc $page}=$page;
982         }
983         foreach my $page (keys %renderedfiles) {
984                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
985         }
986         return close($in);
987 } #}}}
988
989 sub saveindex () { #{{{
990         run_hooks(savestate => sub { shift->() });
991
992         my %hookids;
993         foreach my $type (keys %hooks) {
994                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
995         }
996         my @hookids=keys %hookids;
997
998         if (! -d $config{wikistatedir}) {
999                 mkdir($config{wikistatedir});
1000         }
1001         my $newfile="$config{wikistatedir}/indexdb.new";
1002         my $cleanup = sub { unlink($newfile) };
1003         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1004         my %index;
1005         foreach my $page (keys %pagemtime) {
1006                 next unless $pagemtime{$page};
1007                 my $src=$pagesources{$page};
1008
1009                 $index{$src}={
1010                         ctime => $pagectime{$page},
1011                         mtime => $pagemtime{$page},
1012                         dest => $renderedfiles{$page},
1013                         links => $links{$page},
1014                 };
1015
1016                 if (exists $depends{$page}) {
1017                         $index{$src}{depends} = $depends{$page};
1018                 }
1019
1020                 if (exists $pagestate{$page}) {
1021                         foreach my $id (@hookids) {
1022                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1023                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1024                                 }
1025                         }
1026                 }
1027         }
1028         my $ret=Storable::nstore_fd(\%index, $out);
1029         return if ! defined $ret || ! $ret;
1030         close $out || error("failed saving to $newfile: $!", $cleanup);
1031         rename($newfile, "$config{wikistatedir}/indexdb") ||
1032                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1033         
1034         return 1;
1035 } #}}}
1036
1037 sub template_file ($) { #{{{
1038         my $template=shift;
1039
1040         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1041                 return "$dir/$template" if -e "$dir/$template";
1042         }
1043         return;
1044 } #}}}
1045
1046 sub template_params (@) { #{{{
1047         my $filename=template_file(shift);
1048
1049         if (! defined $filename) {
1050                 return if wantarray;
1051                 return "";
1052         }
1053
1054         my @ret=(
1055                 filter => sub {
1056                         my $text_ref = shift;
1057                         ${$text_ref} = decode_utf8(${$text_ref});
1058                 },
1059                 filename => $filename,
1060                 loop_context_vars => 1,
1061                 die_on_bad_params => 0,
1062                 @_
1063         );
1064         return wantarray ? @ret : {@ret};
1065 } #}}}
1066
1067 sub template ($;@) { #{{{
1068         require HTML::Template;
1069         return HTML::Template->new(template_params(@_));
1070 } #}}}
1071
1072 sub misctemplate ($$;@) { #{{{
1073         my $title=shift;
1074         my $pagebody=shift;
1075         
1076         my $template=template("misc.tmpl");
1077         $template->param(
1078                 title => $title,
1079                 indexlink => indexlink(),
1080                 wikiname => $config{wikiname},
1081                 pagebody => $pagebody,
1082                 baseurl => baseurl(),
1083                 @_,
1084         );
1085         run_hooks(pagetemplate => sub {
1086                 shift->(page => "", destpage => "", template => $template);
1087         });
1088         return $template->output;
1089 }#}}}
1090
1091 sub hook (@) { # {{{
1092         my %param=@_;
1093         
1094         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1095                 error 'hook requires type, call, and id parameters';
1096         }
1097
1098         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1099         
1100         $hooks{$param{type}}{$param{id}}=\%param;
1101         return 1;
1102 } # }}}
1103
1104 sub run_hooks ($$) { # {{{
1105         # Calls the given sub for each hook of the given type,
1106         # passing it the hook function to call.
1107         my $type=shift;
1108         my $sub=shift;
1109
1110         if (exists $hooks{$type}) {
1111                 my @deferred;
1112                 foreach my $id (keys %{$hooks{$type}}) {
1113                         if ($hooks{$type}{$id}{last}) {
1114                                 push @deferred, $id;
1115                                 next;
1116                         }
1117                         $sub->($hooks{$type}{$id}{call});
1118                 }
1119                 foreach my $id (@deferred) {
1120                         $sub->($hooks{$type}{$id}{call});
1121                 }
1122         }
1123
1124         return 1;
1125 } #}}}
1126
1127 sub globlist_to_pagespec ($) { #{{{
1128         my @globlist=split(' ', shift);
1129
1130         my (@spec, @skip);
1131         foreach my $glob (@globlist) {
1132                 if ($glob=~/^!(.*)/) {
1133                         push @skip, $glob;
1134                 }
1135                 else {
1136                         push @spec, $glob;
1137                 }
1138         }
1139
1140         my $spec=join(' or ', @spec);
1141         if (@skip) {
1142                 my $skip=join(' and ', @skip);
1143                 if (length $spec) {
1144                         $spec="$skip and ($spec)";
1145                 }
1146                 else {
1147                         $spec=$skip;
1148                 }
1149         }
1150         return $spec;
1151 } #}}}
1152
1153 sub is_globlist ($) { #{{{
1154         my $s=shift;
1155         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1156 } #}}}
1157
1158 sub safequote ($) { #{{{
1159         my $s=shift;
1160         $s=~s/[{}]//g;
1161         return "q{$s}";
1162 } #}}}
1163
1164 sub add_depends ($$) { #{{{
1165         my $page=shift;
1166         my $pagespec=shift;
1167         
1168         return unless pagespec_valid($pagespec);
1169
1170         if (! exists $depends{$page}) {
1171                 $depends{$page}=$pagespec;
1172         }
1173         else {
1174                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1175         }
1176
1177         return 1;
1178 } # }}}
1179
1180 sub file_pruned ($$) { #{{{
1181         require File::Spec;
1182         my $file=File::Spec->canonpath(shift);
1183         my $base=File::Spec->canonpath(shift);
1184         $file =~ s#^\Q$base\E/+##;
1185
1186         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1187         return $file =~ m/$regexp/ && $file ne $base;
1188 } #}}}
1189
1190 sub gettext { #{{{
1191         # Only use gettext in the rare cases it's needed.
1192         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1193             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1194             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1195                 if (! $gettext_obj) {
1196                         $gettext_obj=eval q{
1197                                 use Locale::gettext q{textdomain};
1198                                 Locale::gettext->domain('ikiwiki')
1199                         };
1200                         if ($@) {
1201                                 print STDERR "$@";
1202                                 $gettext_obj=undef;
1203                                 return shift;
1204                         }
1205                 }
1206                 return $gettext_obj->get(shift);
1207         }
1208         else {
1209                 return shift;
1210         }
1211 } #}}}
1212
1213 sub yesno ($) { #{{{
1214         my $val=shift;
1215
1216         return (defined $val && lc($val) eq gettext("yes"));
1217 } #}}}
1218
1219 sub pagespec_merge ($$) { #{{{
1220         my $a=shift;
1221         my $b=shift;
1222
1223         return $a if $a eq $b;
1224
1225         # Support for old-style GlobLists.
1226         if (is_globlist($a)) {
1227                 $a=globlist_to_pagespec($a);
1228         }
1229         if (is_globlist($b)) {
1230                 $b=globlist_to_pagespec($b);
1231         }
1232
1233         return "($a) or ($b)";
1234 } #}}}
1235
1236 sub pagespec_translate ($) { #{{{
1237         my $spec=shift;
1238
1239         # Support for old-style GlobLists.
1240         if (is_globlist($spec)) {
1241                 $spec=globlist_to_pagespec($spec);
1242         }
1243
1244         # Convert spec to perl code.
1245         my $code="";
1246         while ($spec=~m{
1247                 \s*             # ignore whitespace
1248                 (               # 1: match a single word
1249                         \!              # !
1250                 |
1251                         \(              # (
1252                 |
1253                         \)              # )
1254                 |
1255                         \w+\([^\)]*\)   # command(params)
1256                 |
1257                         [^\s()]+        # any other text
1258                 )
1259                 \s*             # ignore whitespace
1260         }igx) {
1261                 my $word=$1;
1262                 if (lc $word eq 'and') {
1263                         $code.=' &&';
1264                 }
1265                 elsif (lc $word eq 'or') {
1266                         $code.=' ||';
1267                 }
1268                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1269                         $code.=' '.$word;
1270                 }
1271                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1272                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1273                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1274                         }
1275                         else {
1276                                 $code.=' 0';
1277                         }
1278                 }
1279                 else {
1280                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1281                 }
1282         }
1283
1284         if (! length $code) {
1285                 $code=0;
1286         }
1287
1288         no warnings;
1289         return eval 'sub { my $page=shift; '.$code.' }';
1290 } #}}}
1291
1292 sub pagespec_match ($$;@) { #{{{
1293         my $page=shift;
1294         my $spec=shift;
1295         my @params=@_;
1296
1297         # Backwards compatability with old calling convention.
1298         if (@params == 1) {
1299                 unshift @params, 'location';
1300         }
1301
1302         my $sub=pagespec_translate($spec);
1303         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1304         return $sub->($page, @params);
1305 } #}}}
1306
1307 sub pagespec_valid ($) { #{{{
1308         my $spec=shift;
1309
1310         my $sub=pagespec_translate($spec);
1311         return ! $@;
1312 } #}}}
1313         
1314 sub glob2re ($) { #{{{
1315         my $re=quotemeta(shift);
1316         $re=~s/\\\*/.*/g;
1317         $re=~s/\\\?/./g;
1318         return $re;
1319 } #}}}
1320
1321 package IkiWiki::FailReason;
1322
1323 use overload ( #{{{
1324         '""'    => sub { ${$_[0]} },
1325         '0+'    => sub { 0 },
1326         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1327         fallback => 1,
1328 ); #}}}
1329
1330 sub new { #{{{
1331         my $class = shift;
1332         my $value = shift;
1333         return bless \$value, $class;
1334 } #}}}
1335
1336 package IkiWiki::SuccessReason;
1337
1338 use overload ( #{{{
1339         '""'    => sub { ${$_[0]} },
1340         '0+'    => sub { 1 },
1341         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1342         fallback => 1,
1343 ); #}}}
1344
1345 sub new { #{{{
1346         my $class = shift;
1347         my $value = shift;
1348         return bless \$value, $class;
1349 }; #}}}
1350
1351 package IkiWiki::PageSpec;
1352
1353 sub match_glob ($$;@) { #{{{
1354         my $page=shift;
1355         my $glob=shift;
1356         my %params=@_;
1357         
1358         my $from=exists $params{location} ? $params{location} : '';
1359         
1360         # relative matching
1361         if ($glob =~ m!^\./!) {
1362                 $from=~s#/?[^/]+$##;
1363                 $glob=~s#^\./##;
1364                 $glob="$from/$glob" if length $from;
1365         }
1366
1367         my $regexp=IkiWiki::glob2re($glob);
1368         if ($page=~/^$regexp$/i) {
1369                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1370                         return IkiWiki::SuccessReason->new("$glob matches $page");
1371                 }
1372                 else {
1373                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1374                 }
1375         }
1376         else {
1377                 return IkiWiki::FailReason->new("$glob does not match $page");
1378         }
1379 } #}}}
1380
1381 sub match_internal ($$;@) { #{{{
1382         return match_glob($_[0], $_[1], @_, internal => 1)
1383 } #}}}
1384
1385 sub match_link ($$;@) { #{{{
1386         my $page=shift;
1387         my $link=lc(shift);
1388         my %params=@_;
1389
1390         my $from=exists $params{location} ? $params{location} : '';
1391
1392         # relative matching
1393         if ($link =~ m!^\.! && defined $from) {
1394                 $from=~s#/?[^/]+$##;
1395                 $link=~s#^\./##;
1396                 $link="$from/$link" if length $from;
1397         }
1398
1399         my $links = $IkiWiki::links{$page};
1400         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1401         my $bestlink = IkiWiki::bestlink($from, $link);
1402         foreach my $p (@{$links}) {
1403                 if (length $bestlink) {
1404                         return IkiWiki::SuccessReason->new("$page links to $link")
1405                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1406                 }
1407                 else {
1408                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1409                                 if match_glob($p, $link, %params);
1410                 }
1411         }
1412         return IkiWiki::FailReason->new("$page does not link to $link");
1413 } #}}}
1414
1415 sub match_backlink ($$;@) { #{{{
1416         return match_link($_[1], $_[0], @_);
1417 } #}}}
1418
1419 sub match_created_before ($$;@) { #{{{
1420         my $page=shift;
1421         my $testpage=shift;
1422
1423         if (exists $IkiWiki::pagectime{$testpage}) {
1424                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1425                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1426                 }
1427                 else {
1428                         return IkiWiki::FailReason->new("$page not created before $testpage");
1429                 }
1430         }
1431         else {
1432                 return IkiWiki::FailReason->new("$testpage has no ctime");
1433         }
1434 } #}}}
1435
1436 sub match_created_after ($$;@) { #{{{
1437         my $page=shift;
1438         my $testpage=shift;
1439
1440         if (exists $IkiWiki::pagectime{$testpage}) {
1441                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1442                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1443                 }
1444                 else {
1445                         return IkiWiki::FailReason->new("$page not created after $testpage");
1446                 }
1447         }
1448         else {
1449                 return IkiWiki::FailReason->new("$testpage has no ctime");
1450         }
1451 } #}}}
1452
1453 sub match_creation_day ($$;@) { #{{{
1454         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1455                 return IkiWiki::SuccessReason->new('creation_day matched');
1456         }
1457         else {
1458                 return IkiWiki::FailReason->new('creation_day did not match');
1459         }
1460 } #}}}
1461
1462 sub match_creation_month ($$;@) { #{{{
1463         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1464                 return IkiWiki::SuccessReason->new('creation_month matched');
1465         }
1466         else {
1467                 return IkiWiki::FailReason->new('creation_month did not match');
1468         }
1469 } #}}}
1470
1471 sub match_creation_year ($$;@) { #{{{
1472         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1473                 return IkiWiki::SuccessReason->new('creation_year matched');
1474         }
1475         else {
1476                 return IkiWiki::FailReason->new('creation_year did not match');
1477         }
1478 } #}}}
1479
1480 1