Instructions to allow .cgi files to execute from anywhere using boa webserver
[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 %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %hooks %forcerebuild
17             $gettext_obj %loaded_plugins};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21                  pagespec_match_list bestlink htmllink readfile writefile
22                  pagetype srcfile pagename displaytime will_render gettext urlto
23                  targetpage add_underlay pagetitle titlepage linkpage
24                  newpagefile inject add_link
25                  %config %links %pagestate %wikistate %renderedfiles
26                  %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30
31 # Optimisation.
32 use Memoize;
33 memoize("abs2rel");
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36
37 sub getsetup () {
38         wikiname => {
39                 type => "string",
40                 default => "wiki",
41                 description => "name of the wiki",
42                 safe => 1,
43                 rebuild => 1,
44         },
45         adminemail => {
46                 type => "string",
47                 default => undef,
48                 example => 'me@example.com',
49                 description => "contact email for wiki",
50                 safe => 1,
51                 rebuild => 0,
52         },
53         adminuser => {
54                 type => "string",
55                 default => [],
56                 description => "users who are wiki admins",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         banned_users => {
61                 type => "string",
62                 default => [],
63                 description => "users who are banned from the wiki",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         srcdir => {
68                 type => "string",
69                 default => undef,
70                 example => "$ENV{HOME}/wiki",
71                 description => "where the source of the wiki is located",
72                 safe => 0, # path
73                 rebuild => 1,
74         },
75         destdir => {
76                 type => "string",
77                 default => undef,
78                 example => "/var/www/wiki",
79                 description => "where to build the wiki",
80                 safe => 0, # path
81                 rebuild => 1,
82         },
83         url => {
84                 type => "string",
85                 default => '',
86                 example => "http://example.com/wiki",
87                 description => "base url to the wiki",
88                 safe => 1,
89                 rebuild => 1,
90         },
91         cgiurl => {
92                 type => "string",
93                 default => '',
94                 example => "http://example.com/wiki/ikiwiki.cgi",
95                 description => "url to the ikiwiki.cgi",
96                 safe => 1,
97                 rebuild => 1,
98         },
99         cgi_wrapper => {
100                 type => "string",
101                 default => '',
102                 example => "/var/www/wiki/ikiwiki.cgi",
103                 description => "filename of cgi wrapper to generate",
104                 safe => 0, # file
105                 rebuild => 0,
106         },
107         cgi_wrappermode => {
108                 type => "string",
109                 default => '06755',
110                 description => "mode for cgi_wrapper (can safely be made suid)",
111                 safe => 0,
112                 rebuild => 0,
113         },
114         rcs => {
115                 type => "string",
116                 default => '',
117                 description => "rcs backend to use",
118                 safe => 0, # don't allow overriding
119                 rebuild => 0,
120         },
121         default_plugins => {
122                 type => "internal",
123                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124                                 openid signinedit lockedit conditional
125                                 recentchanges parentlinks editpage}],
126                 description => "plugins to enable by default",
127                 safe => 0,
128                 rebuild => 1,
129         },
130         add_plugins => {
131                 type => "string",
132                 default => [],
133                 description => "plugins to add to the default configuration",
134                 safe => 1,
135                 rebuild => 1,
136         },
137         disable_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to disable",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         templatedir => {
145                 type => "string",
146                 default => "$installdir/share/ikiwiki/templates",
147                 description => "location of template files",
148                 advanced => 1,
149                 safe => 0, # path
150                 rebuild => 1,
151         },
152         underlaydir => {
153                 type => "string",
154                 default => "$installdir/share/ikiwiki/basewiki",
155                 description => "base wiki source location",
156                 advanced => 1,
157                 safe => 0, # path
158                 rebuild => 0,
159         },
160         underlaydirbase => {
161                 type => "internal",
162                 default => "$installdir/share/ikiwiki",
163                 description => "parent directory containing additional underlays",
164                 safe => 0,
165                 rebuild => 0,
166         },
167         wrappers => {
168                 type => "internal",
169                 default => [],
170                 description => "wrappers to generate",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         underlaydirs => {
175                 type => "internal",
176                 default => [],
177                 description => "additional underlays to use",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         verbose => {
182                 type => "boolean",
183                 example => 1,
184                 description => "display verbose messages?",
185                 safe => 1,
186                 rebuild => 0,
187         },
188         syslog => {
189                 type => "boolean",
190                 example => 1,
191                 description => "log to syslog?",
192                 safe => 1,
193                 rebuild => 0,
194         },
195         usedirs => {
196                 type => "boolean",
197                 default => 1,
198                 description => "create output files named page/index.html?",
199                 safe => 0, # changing requires manual transition
200                 rebuild => 1,
201         },
202         prefix_directives => {
203                 type => "boolean",
204                 default => 1,
205                 description => "use '!'-prefixed preprocessor directives?",
206                 safe => 0, # changing requires manual transition
207                 rebuild => 1,
208         },
209         indexpages => {
210                 type => "boolean",
211                 default => 0,
212                 description => "use page/index.mdwn source files",
213                 safe => 1,
214                 rebuild => 1,
215         },
216         discussion => {
217                 type => "boolean",
218                 default => 1,
219                 description => "enable Discussion pages?",
220                 safe => 1,
221                 rebuild => 1,
222         },
223         sslcookie => {
224                 type => "boolean",
225                 default => 0,
226                 description => "only send cookies over SSL connections?",
227                 advanced => 1,
228                 safe => 1,
229                 rebuild => 0,
230         },
231         default_pageext => {
232                 type => "string",
233                 default => "mdwn",
234                 description => "extension to use for new pages",
235                 safe => 0, # not sanitized
236                 rebuild => 0,
237         },
238         htmlext => {
239                 type => "string",
240                 default => "html",
241                 description => "extension to use for html files",
242                 safe => 0, # not sanitized
243                 rebuild => 1,
244         },
245         timeformat => {
246                 type => "string",
247                 default => '%c',
248                 description => "strftime format string to display date",
249                 advanced => 1,
250                 safe => 1,
251                 rebuild => 1,
252         },
253         locale => {
254                 type => "string",
255                 default => undef,
256                 example => "en_US.UTF-8",
257                 description => "UTF-8 locale to use",
258                 advanced => 1,
259                 safe => 0,
260                 rebuild => 1,
261         },
262         userdir => {
263                 type => "string",
264                 default => "",
265                 example => "users",
266                 description => "put user pages below specified page",
267                 safe => 1,
268                 rebuild => 1,
269         },
270         numbacklinks => {
271                 type => "integer",
272                 default => 10,
273                 description => "how many backlinks to show before hiding excess (0 to show all)",
274                 safe => 1,
275                 rebuild => 1,
276         },
277         hardlink => {
278                 type => "boolean",
279                 default => 0,
280                 description => "attempt to hardlink source files? (optimisation for large files)",
281                 advanced => 1,
282                 safe => 0, # paranoia
283                 rebuild => 0,
284         },
285         umask => {
286                 type => "integer",
287                 example => "022",
288                 description => "force ikiwiki to use a particular umask",
289                 advanced => 1,
290                 safe => 0, # paranoia
291                 rebuild => 0,
292         },
293         wrappergroup => {
294                 type => "string",
295                 example => "ikiwiki",
296                 description => "group for wrappers to run in",
297                 advanced => 1,
298                 safe => 0, # paranoia
299                 rebuild => 0,
300         },
301         libdir => {
302                 type => "string",
303                 default => "",
304                 example => "$ENV{HOME}/.ikiwiki/",
305                 description => "extra library and plugin directory",
306                 advanced => 1,
307                 safe => 0, # directory
308                 rebuild => 0,
309         },
310         ENV => {
311                 type => "string", 
312                 default => {},
313                 description => "environment variables",
314                 safe => 0, # paranoia
315                 rebuild => 0,
316         },
317         exclude => {
318                 type => "string",
319                 default => undef,
320                 example => '\.wav$',
321                 description => "regexp of source files to ignore",
322                 advanced => 1,
323                 safe => 0, # regexp
324                 rebuild => 1,
325         },
326         wiki_file_prune_regexps => {
327                 type => "internal",
328                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
332                         qr/\.dpkg-tmp$/],
333                 description => "regexps of source files to ignore",
334                 safe => 0,
335                 rebuild => 1,
336         },
337         wiki_file_chars => {
338                 type => "string",
339                 description => "specifies the characters that are allowed in source filenames",
340                 default => "-[:alnum:]+/.:_",
341                 safe => 0,
342                 rebuild => 1,
343         },
344         wiki_file_regexp => {
345                 type => "internal",
346                 description => "regexp of legal source files",
347                 safe => 0,
348                 rebuild => 1,
349         },
350         web_commit_regexp => {
351                 type => "internal",
352                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353                 description => "regexp to parse web commits from logs",
354                 safe => 0,
355                 rebuild => 0,
356         },
357         cgi => {
358                 type => "internal",
359                 default => 0,
360                 description => "run as a cgi",
361                 safe => 0,
362                 rebuild => 0,
363         },
364         cgi_disable_uploads => {
365                 type => "internal",
366                 default => 1,
367                 description => "whether CGI should accept file uploads",
368                 safe => 0,
369                 rebuild => 0,
370         },
371         post_commit => {
372                 type => "internal",
373                 default => 0,
374                 description => "run as a post-commit hook",
375                 safe => 0,
376                 rebuild => 0,
377         },
378         rebuild => {
379                 type => "internal",
380                 default => 0,
381                 description => "running in rebuild mode",
382                 safe => 0,
383                 rebuild => 0,
384         },
385         setup => {
386                 type => "internal",
387                 default => undef,
388                 description => "running in setup mode",
389                 safe => 0,
390                 rebuild => 0,
391         },
392         refresh => {
393                 type => "internal",
394                 default => 0,
395                 description => "running in refresh mode",
396                 safe => 0,
397                 rebuild => 0,
398         },
399         test_receive => {
400                 type => "internal",
401                 default => 0,
402                 description => "running in receive test mode",
403                 safe => 0,
404                 rebuild => 0,
405         },
406         getctime => {
407                 type => "internal",
408                 default => 0,
409                 description => "running in getctime mode",
410                 safe => 0,
411                 rebuild => 0,
412         },
413         w3mmode => {
414                 type => "internal",
415                 default => 0,
416                 description => "running in w3mmode",
417                 safe => 0,
418                 rebuild => 0,
419         },
420         wikistatedir => {
421                 type => "internal",
422                 default => undef,
423                 description => "path to the .ikiwiki directory holding ikiwiki state",
424                 safe => 0,
425                 rebuild => 0,
426         },
427         setupfile => {
428                 type => "internal",
429                 default => undef,
430                 description => "path to setup file",
431                 safe => 0,
432                 rebuild => 0,
433         },
434         allow_symlinks_before_srcdir => {
435                 type => "boolean",
436                 default => 0,
437                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
438                 safe => 0,
439                 rebuild => 0,
440         },
441 }
442
443 sub defaultconfig () {
444         my %s=getsetup();
445         my @ret;
446         foreach my $key (keys %s) {
447                 push @ret, $key, $s{$key}->{default};
448         }
449         use Data::Dumper;
450         return @ret;
451 }
452
453 sub checkconfig () {
454         # locale stuff; avoid LC_ALL since it overrides everything
455         if (defined $ENV{LC_ALL}) {
456                 $ENV{LANG} = $ENV{LC_ALL};
457                 delete $ENV{LC_ALL};
458         }
459         if (defined $config{locale}) {
460                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461                         $ENV{LANG}=$config{locale};
462                         $gettext_obj=undef;
463                 }
464         }
465                 
466         if (! defined $config{wiki_file_regexp}) {
467                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
468         }
469
470         if (ref $config{ENV} eq 'HASH') {
471                 foreach my $val (keys %{$config{ENV}}) {
472                         $ENV{$val}=$config{ENV}{$val};
473                 }
474         }
475
476         if ($config{w3mmode}) {
477                 eval q{use Cwd q{abs_path}};
478                 error($@) if $@;
479                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482                         unless $config{cgiurl} =~ m!file:///!;
483                 $config{url}="file://".$config{destdir};
484         }
485
486         if ($config{cgi} && ! length $config{url}) {
487                 error(gettext("Must specify url to wiki with --url when using --cgi"));
488         }
489         
490         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
492
493         if (defined $config{umask}) {
494                 umask(possibly_foolish_untaint($config{umask}));
495         }
496
497         run_hooks(checkconfig => sub { shift->() });
498
499         return 1;
500 }
501
502 sub listplugins () {
503         my %ret;
504
505         foreach my $dir (@INC, $config{libdir}) {
506                 next unless defined $dir && length $dir;
507                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
509                         $ret{$plugin}=1;
510                 }
511         }
512         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513                 next unless defined $dir && length $dir;
514                 foreach my $file (glob("$dir/plugins/*")) {
515                         $ret{basename($file)}=1 if -x $file;
516                 }
517         }
518
519         return keys %ret;
520 }
521
522 sub loadplugins () {
523         if (defined $config{libdir} && length $config{libdir}) {
524                 unshift @INC, possibly_foolish_untaint($config{libdir});
525         }
526
527         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
528                 loadplugin($plugin);
529         }
530         
531         if ($config{rcs}) {
532                 if (exists $IkiWiki::hooks{rcs}) {
533                         error(gettext("cannot use multiple rcs plugins"));
534                 }
535                 loadplugin($config{rcs});
536         }
537         if (! exists $IkiWiki::hooks{rcs}) {
538                 loadplugin("norcs");
539         }
540
541         run_hooks(getopt => sub { shift->() });
542         if (grep /^-/, @ARGV) {
543                 print STDERR "Unknown option (or missing parameter): $_\n"
544                         foreach grep /^-/, @ARGV;
545                 usage();
546         }
547
548         return 1;
549 }
550
551 sub loadplugin ($) {
552         my $plugin=shift;
553
554         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
555
556         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557                          "$installdir/lib/ikiwiki") {
558                 if (defined $dir && -x "$dir/plugins/$plugin") {
559                         eval { require IkiWiki::Plugin::external };
560                         if ($@) {
561                                 my $reason=$@;
562                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
563                         }
564                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565                         $loaded_plugins{$plugin}=1;
566                         return 1;
567                 }
568         }
569
570         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
571         eval qq{use $mod};
572         if ($@) {
573                 error("Failed to load plugin $mod: $@");
574         }
575         $loaded_plugins{$plugin}=1;
576         return 1;
577 }
578
579 sub error ($;$) {
580         my $message=shift;
581         my $cleaner=shift;
582         log_message('err' => $message) if $config{syslog};
583         if (defined $cleaner) {
584                 $cleaner->();
585         }
586         die $message."\n";
587 }
588
589 sub debug ($) {
590         return unless $config{verbose};
591         return log_message(debug => @_);
592 }
593
594 my $log_open=0;
595 sub log_message ($$) {
596         my $type=shift;
597
598         if ($config{syslog}) {
599                 require Sys::Syslog;
600                 if (! $log_open) {
601                         Sys::Syslog::setlogsock('unix');
602                         Sys::Syslog::openlog('ikiwiki', '', 'user');
603                         $log_open=1;
604                 }
605                 return eval {
606                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
607                 };
608         }
609         elsif (! $config{cgi}) {
610                 return print "@_\n";
611         }
612         else {
613                 return print STDERR "@_\n";
614         }
615 }
616
617 sub possibly_foolish_untaint ($) {
618         my $tainted=shift;
619         my ($untainted)=$tainted=~/(.*)/s;
620         return $untainted;
621 }
622
623 sub basename ($) {
624         my $file=shift;
625
626         $file=~s!.*/+!!;
627         return $file;
628 }
629
630 sub dirname ($) {
631         my $file=shift;
632
633         $file=~s!/*[^/]+$!!;
634         return $file;
635 }
636
637 sub isinternal ($) {
638         my $page=shift;
639         return exists $pagesources{$page} &&
640                 $pagesources{$page} =~ /\._([^.]+)$/;
641 }
642
643 sub pagetype ($) {
644         my $file=shift;
645         
646         if ($file =~ /\.([^.]+)$/) {
647                 return $1 if exists $hooks{htmlize}{$1};
648         }
649         my $base=basename($file);
650         if (exists $hooks{htmlize}{$base} &&
651             $hooks{htmlize}{$base}{noextension}) {
652                 return $base;
653         }
654         return;
655 }
656
657 sub pagename ($) {
658         my $file=shift;
659
660         my $type=pagetype($file);
661         my $page=$file;
662         $page=~s/\Q.$type\E*$//
663                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664                         && !$hooks{htmlize}{$type}{noextension};
665         if ($config{indexpages} && $page=~/(.*)\/index$/) {
666                 $page=$1;
667         }
668         return $page;
669 }
670
671 sub newpagefile ($$) {
672         my $page=shift;
673         my $type=shift;
674
675         if (! $config{indexpages} || $page eq 'index') {
676                 return $page.".".$type;
677         }
678         else {
679                 return $page."/index.".$type;
680         }
681 }
682
683 sub targetpage ($$;$) {
684         my $page=shift;
685         my $ext=shift;
686         my $filename=shift;
687         
688         if (defined $filename) {
689                 return $page."/".$filename.".".$ext;
690         }
691         elsif (! $config{usedirs} || $page eq 'index') {
692                 return $page.".".$ext;
693         }
694         else {
695                 return $page."/index.".$ext;
696         }
697 }
698
699 sub htmlpage ($) {
700         my $page=shift;
701         
702         return targetpage($page, $config{htmlext});
703 }
704
705 sub srcfile_stat {
706         my $file=shift;
707         my $nothrow=shift;
708
709         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711                 return "$dir/$file", stat(_) if -e "$dir/$file";
712         }
713         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
714         return;
715 }
716
717 sub srcfile ($;$) {
718         return (srcfile_stat(@_))[0];
719 }
720
721 sub add_underlay ($) {
722         my $dir=shift;
723
724         if ($dir !~ /^\//) {
725                 $dir="$config{underlaydirbase}/$dir";
726         }
727
728         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729                 unshift @{$config{underlaydirs}}, $dir;
730         }
731
732         return 1;
733 }
734
735 sub readfile ($;$$) {
736         my $file=shift;
737         my $binary=shift;
738         my $wantfd=shift;
739
740         if (-l $file) {
741                 error("cannot read a symlink ($file)");
742         }
743         
744         local $/=undef;
745         open (my $in, "<", $file) || error("failed to read $file: $!");
746         binmode($in) if ($binary);
747         return \*$in if $wantfd;
748         my $ret=<$in>;
749         # check for invalid utf-8, and toss it back to avoid crashes
750         if (! utf8::valid($ret)) {
751                 $ret=encode_utf8($ret);
752         }
753         close $in || error("failed to read $file: $!");
754         return $ret;
755 }
756
757 sub prep_writefile ($$) {
758         my $file=shift;
759         my $destdir=shift;
760         
761         my $test=$file;
762         while (length $test) {
763                 if (-l "$destdir/$test") {
764                         error("cannot write to a symlink ($test)");
765                 }
766                 $test=dirname($test);
767         }
768
769         my $dir=dirname("$destdir/$file");
770         if (! -d $dir) {
771                 my $d="";
772                 foreach my $s (split(m!/+!, $dir)) {
773                         $d.="$s/";
774                         if (! -d $d) {
775                                 mkdir($d) || error("failed to create directory $d: $!");
776                         }
777                 }
778         }
779
780         return 1;
781 }
782
783 sub writefile ($$$;$$) {
784         my $file=shift; # can include subdirs
785         my $destdir=shift; # directory to put file in
786         my $content=shift;
787         my $binary=shift;
788         my $writer=shift;
789         
790         prep_writefile($file, $destdir);
791         
792         my $newfile="$destdir/$file.ikiwiki-new";
793         if (-l $newfile) {
794                 error("cannot write to a symlink ($newfile)");
795         }
796         
797         my $cleanup = sub { unlink($newfile) };
798         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799         binmode($out) if ($binary);
800         if ($writer) {
801                 $writer->(\*$out, $cleanup);
802         }
803         else {
804                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
805         }
806         close $out || error("failed saving $newfile: $!", $cleanup);
807         rename($newfile, "$destdir/$file") || 
808                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
809
810         return 1;
811 }
812
813 my %cleared;
814 sub will_render ($$;$) {
815         my $page=shift;
816         my $dest=shift;
817         my $clear=shift;
818
819         # Important security check.
820         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
823         }
824
825         if (! $clear || $cleared{$page}) {
826                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
827         }
828         else {
829                 foreach my $old (@{$renderedfiles{$page}}) {
830                         delete $destsources{$old};
831                 }
832                 $renderedfiles{$page}=[$dest];
833                 $cleared{$page}=1;
834         }
835         $destsources{$dest}=$page;
836
837         return 1;
838 }
839
840 sub bestlink ($$) {
841         my $page=shift;
842         my $link=shift;
843         
844         my $cwd=$page;
845         if ($link=~s/^\/+//) {
846                 # absolute links
847                 $cwd="";
848         }
849         $link=~s/\/$//;
850
851         do {
852                 my $l=$cwd;
853                 $l.="/" if length $l;
854                 $l.=$link;
855
856                 if (exists $links{$l}) {
857                         return $l;
858                 }
859                 elsif (exists $pagecase{lc $l}) {
860                         return $pagecase{lc $l};
861                 }
862         } while $cwd=~s{/?[^/]+$}{};
863
864         if (length $config{userdir}) {
865                 my $l = "$config{userdir}/".lc($link);
866                 if (exists $links{$l}) {
867                         return $l;
868                 }
869                 elsif (exists $pagecase{lc $l}) {
870                         return $pagecase{lc $l};
871                 }
872         }
873
874         #print STDERR "warning: page $page, broken link: $link\n";
875         return "";
876 }
877
878 sub isinlinableimage ($) {
879         my $file=shift;
880         
881         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
882 }
883
884 sub pagetitle ($;$) {
885         my $page=shift;
886         my $unescaped=shift;
887
888         if ($unescaped) {
889                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
890         }
891         else {
892                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
893         }
894
895         return $page;
896 }
897
898 sub titlepage ($) {
899         my $title=shift;
900         # support use w/o %config set
901         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
903         return $title;
904 }
905
906 sub linkpage ($) {
907         my $link=shift;
908         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
910         return $link;
911 }
912
913 sub cgiurl (@) {
914         my %params=@_;
915
916         return $config{cgiurl}."?".
917                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
918 }
919
920 sub baseurl (;$) {
921         my $page=shift;
922
923         return "$config{url}/" if ! defined $page;
924         
925         $page=htmlpage($page);
926         $page=~s/[^\/]+$//;
927         $page=~s/[^\/]+\//..\//g;
928         return $page;
929 }
930
931 sub abs2rel ($$) {
932         # Work around very innefficient behavior in File::Spec if abs2rel
933         # is passed two relative paths. It's much faster if paths are
934         # absolute! (Debian bug #376658; fixed in debian unstable now)
935         my $path="/".shift;
936         my $base="/".shift;
937
938         require File::Spec;
939         my $ret=File::Spec->abs2rel($path, $base);
940         $ret=~s/^// if defined $ret;
941         return $ret;
942 }
943
944 sub displaytime ($;$) {
945         # Plugins can override this function to mark up the time to
946         # display.
947         return '<span class="date">'.formattime(@_).'</span>';
948 }
949
950 sub formattime ($;$) {
951         # Plugins can override this function to format the time.
952         my $time=shift;
953         my $format=shift;
954         if (! defined $format) {
955                 $format=$config{timeformat};
956         }
957
958         # strftime doesn't know about encodings, so make sure
959         # its output is properly treated as utf8
960         return decode_utf8(POSIX::strftime($format, localtime($time)));
961 }
962
963 sub beautify_urlpath ($) {
964         my $url=shift;
965
966         # Ensure url is not an empty link, and if necessary,
967         # add ./ to avoid colon confusion.
968         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
969                 $url="./$url";
970         }
971
972         if ($config{usedirs}) {
973                 $url =~ s!/index.$config{htmlext}$!/!;
974         }
975
976         return $url;
977 }
978
979 sub urlto ($$;$) {
980         my $to=shift;
981         my $from=shift;
982         my $absolute=shift;
983         
984         if (! length $to) {
985                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
986         }
987
988         if (! $destsources{$to}) {
989                 $to=htmlpage($to);
990         }
991
992         if ($absolute) {
993                 return $config{url}.beautify_urlpath("/".$to);
994         }
995
996         my $link = abs2rel($to, dirname(htmlpage($from)));
997
998         return beautify_urlpath($link);
999 }
1000
1001 sub htmllink ($$$;@) {
1002         my $lpage=shift; # the page doing the linking
1003         my $page=shift; # the page that will contain the link (different for inline)
1004         my $link=shift;
1005         my %opts=@_;
1006
1007         $link=~s/\/$//;
1008
1009         my $bestlink;
1010         if (! $opts{forcesubpage}) {
1011                 $bestlink=bestlink($lpage, $link);
1012         }
1013         else {
1014                 $bestlink="$lpage/".lc($link);
1015         }
1016
1017         my $linktext;
1018         if (defined $opts{linktext}) {
1019                 $linktext=$opts{linktext};
1020         }
1021         else {
1022                 $linktext=pagetitle(basename($link));
1023         }
1024         
1025         return "<span class=\"selflink\">$linktext</span>"
1026                 if length $bestlink && $page eq $bestlink &&
1027                    ! defined $opts{anchor};
1028         
1029         if (! $destsources{$bestlink}) {
1030                 $bestlink=htmlpage($bestlink);
1031
1032                 if (! $destsources{$bestlink}) {
1033                         return $linktext unless length $config{cgiurl};
1034                         return "<span class=\"createlink\"><a href=\"".
1035                                 cgiurl(
1036                                         do => "create",
1037                                         page => lc($link),
1038                                         from => $lpage
1039                                 ).
1040                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1041                 }
1042         }
1043         
1044         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045         $bestlink=beautify_urlpath($bestlink);
1046         
1047         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1049         }
1050
1051         if (defined $opts{anchor}) {
1052                 $bestlink.="#".$opts{anchor};
1053         }
1054
1055         my @attrs;
1056         if (defined $opts{rel}) {
1057                 push @attrs, ' rel="'.$opts{rel}.'"';
1058         }
1059         if (defined $opts{class}) {
1060                 push @attrs, ' class="'.$opts{class}.'"';
1061         }
1062
1063         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1064 }
1065
1066 sub userlink ($) {
1067         my $user=shift;
1068
1069         my $oiduser=eval { openiduser($user) };
1070         if (defined $oiduser) {
1071                 return "<a href=\"$user\">$oiduser</a>";
1072         }
1073         else {
1074                 eval q{use CGI 'escapeHTML'};
1075                 error($@) if $@;
1076
1077                 return htmllink("", "", escapeHTML(
1078                         length $config{userdir} ? $config{userdir}."/".$user : $user
1079                 ), noimageinline => 1);
1080         }
1081 }
1082
1083 sub htmlize ($$$$) {
1084         my $page=shift;
1085         my $destpage=shift;
1086         my $type=shift;
1087         my $content=shift;
1088         
1089         my $oneline = $content !~ /\n/;
1090
1091         if (exists $hooks{htmlize}{$type}) {
1092                 $content=$hooks{htmlize}{$type}{call}->(
1093                         page => $page,
1094                         content => $content,
1095                 );
1096         }
1097         else {
1098                 error("htmlization of $type not supported");
1099         }
1100
1101         run_hooks(sanitize => sub {
1102                 $content=shift->(
1103                         page => $page,
1104                         destpage => $destpage,
1105                         content => $content,
1106                 );
1107         });
1108         
1109         if ($oneline) {
1110                 # hack to get rid of enclosing junk added by markdown
1111                 # and other htmlizers
1112                 $content=~s/^<p>//i;
1113                 $content=~s/<\/p>$//i;
1114                 chomp $content;
1115         }
1116
1117         return $content;
1118 }
1119
1120 sub linkify ($$$) {
1121         my $page=shift;
1122         my $destpage=shift;
1123         my $content=shift;
1124
1125         run_hooks(linkify => sub {
1126                 $content=shift->(
1127                         page => $page,
1128                         destpage => $destpage,
1129                         content => $content,
1130                 );
1131         });
1132         
1133         return $content;
1134 }
1135
1136 our %preprocessing;
1137 our $preprocess_preview=0;
1138 sub preprocess ($$$;$$) {
1139         my $page=shift; # the page the data comes from
1140         my $destpage=shift; # the page the data will appear in (different for inline)
1141         my $content=shift;
1142         my $scan=shift;
1143         my $preview=shift;
1144
1145         # Using local because it needs to be set within any nested calls
1146         # of this function.
1147         local $preprocess_preview=$preview if defined $preview;
1148
1149         my $handle=sub {
1150                 my $escape=shift;
1151                 my $prefix=shift;
1152                 my $command=shift;
1153                 my $params=shift;
1154                 $params="" if ! defined $params;
1155
1156                 if (length $escape) {
1157                         return "[[$prefix$command $params]]";
1158                 }
1159                 elsif (exists $hooks{preprocess}{$command}) {
1160                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1161                         # Note: preserve order of params, some plugins may
1162                         # consider it significant.
1163                         my @params;
1164                         while ($params =~ m{
1165                                 (?:([-\w]+)=)?          # 1: named parameter key?
1166                                 (?:
1167                                         """(.*?)"""     # 2: triple-quoted value
1168                                 |
1169                                         "([^"]+)"       # 3: single-quoted value
1170                                 |
1171                                         (\S+)           # 4: unquoted value
1172                                 )
1173                                 (?:\s+|$)               # delimiter to next param
1174                         }sgx) {
1175                                 my $key=$1;
1176                                 my $val;
1177                                 if (defined $2) {
1178                                         $val=$2;
1179                                         $val=~s/\r\n/\n/mg;
1180                                         $val=~s/^\n+//g;
1181                                         $val=~s/\n+$//g;
1182                                 }
1183                                 elsif (defined $3) {
1184                                         $val=$3;
1185                                 }
1186                                 elsif (defined $4) {
1187                                         $val=$4;
1188                                 }
1189
1190                                 if (defined $key) {
1191                                         push @params, $key, $val;
1192                                 }
1193                                 else {
1194                                         push @params, $val, '';
1195                                 }
1196                         }
1197                         if ($preprocessing{$page}++ > 3) {
1198                                 # Avoid loops of preprocessed pages preprocessing
1199                                 # other pages that preprocess them, etc.
1200                                 return "[[!$command <span class=\"error\">".
1201                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1202                                                 $page, $preprocessing{$page}).
1203                                         "</span>]]";
1204                         }
1205                         my $ret;
1206                         if (! $scan) {
1207                                 $ret=eval {
1208                                         $hooks{preprocess}{$command}{call}->(
1209                                                 @params,
1210                                                 page => $page,
1211                                                 destpage => $destpage,
1212                                                 preview => $preprocess_preview,
1213                                         );
1214                                 };
1215                                 if ($@) {
1216                                         chomp $@;
1217                                         $ret="[[!$command <span class=\"error\">".
1218                                                 gettext("Error").": $@"."</span>]]";
1219                                 }
1220                         }
1221                         else {
1222                                 # use void context during scan pass
1223                                 eval {
1224                                         $hooks{preprocess}{$command}{call}->(
1225                                                 @params,
1226                                                 page => $page,
1227                                                 destpage => $destpage,
1228                                                 preview => $preprocess_preview,
1229                                         );
1230                                 };
1231                                 $ret="";
1232                         }
1233                         $preprocessing{$page}--;
1234                         return $ret;
1235                 }
1236                 else {
1237                         return "[[$prefix$command $params]]";
1238                 }
1239         };
1240         
1241         my $regex;
1242         if ($config{prefix_directives}) {
1243                 $regex = qr{
1244                         (\\?)           # 1: escape?
1245                         \[\[(!)         # directive open; 2: prefix
1246                         ([-\w]+)        # 3: command
1247                         (               # 4: the parameters..
1248                                 \s+     # Must have space if parameters present
1249                                 (?:
1250                                         (?:[-\w]+=)?            # named parameter key?
1251                                         (?:
1252                                                 """.*?"""       # triple-quoted value
1253                                                 |
1254                                                 "[^"]+"         # single-quoted value
1255                                                 |
1256                                                 [^"\s\]]+       # unquoted value
1257                                         )
1258                                         \s*                     # whitespace or end
1259                                                                 # of directive
1260                                 )
1261                         *)?             # 0 or more parameters
1262                         \]\]            # directive closed
1263                 }sx;
1264         }
1265         else {
1266                 $regex = qr{
1267                         (\\?)           # 1: escape?
1268                         \[\[(!?)        # directive open; 2: optional prefix
1269                         ([-\w]+)        # 3: command
1270                         \s+
1271                         (               # 4: the parameters..
1272                                 (?:
1273                                         (?:[-\w]+=)?            # named parameter key?
1274                                         (?:
1275                                                 """.*?"""       # triple-quoted value
1276                                                 |
1277                                                 "[^"]+"         # single-quoted value
1278                                                 |
1279                                                 [^"\s\]]+       # unquoted value
1280                                         )
1281                                         \s*                     # whitespace or end
1282                                                                 # of directive
1283                                 )
1284                         *)              # 0 or more parameters
1285                         \]\]            # directive closed
1286                 }sx;
1287         }
1288
1289         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1290         return $content;
1291 }
1292
1293 sub filter ($$$) {
1294         my $page=shift;
1295         my $destpage=shift;
1296         my $content=shift;
1297
1298         run_hooks(filter => sub {
1299                 $content=shift->(page => $page, destpage => $destpage, 
1300                         content => $content);
1301         });
1302
1303         return $content;
1304 }
1305
1306 sub indexlink () {
1307         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1308 }
1309
1310 sub check_canedit ($$$;$) {
1311         my $page=shift;
1312         my $q=shift;
1313         my $session=shift;
1314         my $nonfatal=shift;
1315         
1316         my $canedit;
1317         run_hooks(canedit => sub {
1318                 return if defined $canedit;
1319                 my $ret=shift->($page, $q, $session);
1320                 if (defined $ret) {
1321                         if ($ret eq "") {
1322                                 $canedit=1;
1323                         }
1324                         elsif (ref $ret eq 'CODE') {
1325                                 $ret->() unless $nonfatal;
1326                                 $canedit=0;
1327                         }
1328                         elsif (defined $ret) {
1329                                 error($ret) unless $nonfatal;
1330                                 $canedit=0;
1331                         }
1332                 }
1333         });
1334         return defined $canedit ? $canedit : 1;
1335 }
1336
1337 sub check_content (@) {
1338         my %params=@_;
1339         
1340         return 1 if ! exists $hooks{checkcontent}; # optimisation
1341
1342         if (exists $pagesources{$params{page}}) {
1343                 my @diff;
1344                 my %old=map { $_ => 1 }
1345                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1346                 foreach my $line (split("\n", $params{content})) {
1347                         push @diff, $line if ! exists $old{$_};
1348                 }
1349                 $params{content}=join("\n", @diff);
1350         }
1351
1352         my $ok;
1353         run_hooks(checkcontent => sub {
1354                 return if defined $ok;
1355                 my $ret=shift->(%params);
1356                 if (defined $ret) {
1357                         if ($ret eq "") {
1358                                 $ok=1;
1359                         }
1360                         elsif (ref $ret eq 'CODE') {
1361                                 $ret->() unless $params{nonfatal};
1362                                 $ok=0;
1363                         }
1364                         elsif (defined $ret) {
1365                                 error($ret) unless $params{nonfatal};
1366                                 $ok=0;
1367                         }
1368                 }
1369
1370         });
1371         return defined $ok ? $ok : 1;
1372 }
1373
1374 my $wikilock;
1375
1376 sub lockwiki () {
1377         # Take an exclusive lock on the wiki to prevent multiple concurrent
1378         # run issues. The lock will be dropped on program exit.
1379         if (! -d $config{wikistatedir}) {
1380                 mkdir($config{wikistatedir});
1381         }
1382         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1383                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1384         if (! flock($wikilock, 2)) { # LOCK_EX
1385                 error("failed to get lock");
1386         }
1387         return 1;
1388 }
1389
1390 sub unlockwiki () {
1391         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1392         return close($wikilock) if $wikilock;
1393         return;
1394 }
1395
1396 my $commitlock;
1397
1398 sub commit_hook_enabled () {
1399         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1400                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1401         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1402                 close($commitlock) || error("failed closing commitlock: $!");
1403                 return 0;
1404         }
1405         close($commitlock) || error("failed closing commitlock: $!");
1406         return 1;
1407 }
1408
1409 sub disable_commit_hook () {
1410         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1411                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1412         if (! flock($commitlock, 2)) { # LOCK_EX
1413                 error("failed to get commit lock");
1414         }
1415         return 1;
1416 }
1417
1418 sub enable_commit_hook () {
1419         return close($commitlock) if $commitlock;
1420         return;
1421 }
1422
1423 sub loadindex () {
1424         %oldrenderedfiles=%pagectime=();
1425         if (! $config{rebuild}) {
1426                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1427                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1428         }
1429         my $in;
1430         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1431                 if (-e "$config{wikistatedir}/index") {
1432                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1433                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1434                 }
1435                 else {
1436                         return;
1437                 }
1438         }
1439
1440         my $index=Storable::fd_retrieve($in);
1441         if (! defined $index) {
1442                 return 0;
1443         }
1444
1445         my $pages;
1446         if (exists $index->{version} && ! ref $index->{version}) {
1447                 $pages=$index->{page};
1448                 %wikistate=%{$index->{state}};
1449         }
1450         else {
1451                 $pages=$index;
1452                 %wikistate=();
1453         }
1454
1455         foreach my $src (keys %$pages) {
1456                 my $d=$pages->{$src};
1457                 my $page=pagename($src);
1458                 $pagectime{$page}=$d->{ctime};
1459                 if (! $config{rebuild}) {
1460                         $pagesources{$page}=$src;
1461                         $pagemtime{$page}=$d->{mtime};
1462                         $renderedfiles{$page}=$d->{dest};
1463                         if (exists $d->{links} && ref $d->{links}) {
1464                                 $links{$page}=$d->{links};
1465                                 $oldlinks{$page}=[@{$d->{links}}];
1466                         }
1467                         if (exists $d->{depends}) {
1468                                 $depends{$page}=$d->{depends};
1469                         }
1470                         if (exists $d->{state}) {
1471                                 $pagestate{$page}=$d->{state};
1472                         }
1473                 }
1474                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1475         }
1476         foreach my $page (keys %pagesources) {
1477                 $pagecase{lc $page}=$page;
1478         }
1479         foreach my $page (keys %renderedfiles) {
1480                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1481         }
1482         return close($in);
1483 }
1484
1485 sub saveindex () {
1486         run_hooks(savestate => sub { shift->() });
1487
1488         my %hookids;
1489         foreach my $type (keys %hooks) {
1490                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1491         }
1492         my @hookids=keys %hookids;
1493
1494         if (! -d $config{wikistatedir}) {
1495                 mkdir($config{wikistatedir});
1496         }
1497         my $newfile="$config{wikistatedir}/indexdb.new";
1498         my $cleanup = sub { unlink($newfile) };
1499         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1500
1501         my %index;
1502         foreach my $page (keys %pagemtime) {
1503                 next unless $pagemtime{$page};
1504                 my $src=$pagesources{$page};
1505
1506                 $index{page}{$src}={
1507                         ctime => $pagectime{$page},
1508                         mtime => $pagemtime{$page},
1509                         dest => $renderedfiles{$page},
1510                         links => $links{$page},
1511                 };
1512
1513                 if (exists $depends{$page}) {
1514                         $index{page}{$src}{depends} = $depends{$page};
1515                 }
1516
1517                 if (exists $pagestate{$page}) {
1518                         foreach my $id (@hookids) {
1519                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1520                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1521                                 }
1522                         }
1523                 }
1524         }
1525
1526         $index{state}={};
1527         foreach my $id (@hookids) {
1528                 foreach my $key (keys %{$wikistate{$id}}) {
1529                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1530                 }
1531         }
1532         
1533         $index{version}="3";
1534         my $ret=Storable::nstore_fd(\%index, $out);
1535         return if ! defined $ret || ! $ret;
1536         close $out || error("failed saving to $newfile: $!", $cleanup);
1537         rename($newfile, "$config{wikistatedir}/indexdb") ||
1538                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1539         
1540         return 1;
1541 }
1542
1543 sub template_file ($) {
1544         my $template=shift;
1545
1546         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1547                 return "$dir/$template" if -e "$dir/$template";
1548         }
1549         return;
1550 }
1551
1552 sub template_params (@) {
1553         my $filename=template_file(shift);
1554
1555         if (! defined $filename) {
1556                 return if wantarray;
1557                 return "";
1558         }
1559
1560         my @ret=(
1561                 filter => sub {
1562                         my $text_ref = shift;
1563                         ${$text_ref} = decode_utf8(${$text_ref});
1564                 },
1565                 filename => $filename,
1566                 loop_context_vars => 1,
1567                 die_on_bad_params => 0,
1568                 @_
1569         );
1570         return wantarray ? @ret : {@ret};
1571 }
1572
1573 sub template ($;@) {
1574         require HTML::Template;
1575         return HTML::Template->new(template_params(@_));
1576 }
1577
1578 sub misctemplate ($$;@) {
1579         my $title=shift;
1580         my $pagebody=shift;
1581         
1582         my $template=template("misc.tmpl");
1583         $template->param(
1584                 title => $title,
1585                 indexlink => indexlink(),
1586                 wikiname => $config{wikiname},
1587                 pagebody => $pagebody,
1588                 baseurl => baseurl(),
1589                 @_,
1590         );
1591         run_hooks(pagetemplate => sub {
1592                 shift->(page => "", destpage => "", template => $template);
1593         });
1594         return $template->output;
1595 }
1596
1597 sub hook (@) {
1598         my %param=@_;
1599         
1600         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1601                 error 'hook requires type, call, and id parameters';
1602         }
1603
1604         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1605         
1606         $hooks{$param{type}}{$param{id}}=\%param;
1607         return 1;
1608 }
1609
1610 sub run_hooks ($$) {
1611         # Calls the given sub for each hook of the given type,
1612         # passing it the hook function to call.
1613         my $type=shift;
1614         my $sub=shift;
1615
1616         if (exists $hooks{$type}) {
1617                 my (@first, @middle, @last);
1618                 foreach my $id (keys %{$hooks{$type}}) {
1619                         if ($hooks{$type}{$id}{first}) {
1620                                 push @first, $id;
1621                         }
1622                         elsif ($hooks{$type}{$id}{last}) {
1623                                 push @last, $id;
1624                         }
1625                         else {
1626                                 push @middle, $id;
1627                         }
1628                 }
1629                 foreach my $id (@first, @middle, @last) {
1630                         $sub->($hooks{$type}{$id}{call});
1631                 }
1632         }
1633
1634         return 1;
1635 }
1636
1637 sub rcs_update () {
1638         $hooks{rcs}{rcs_update}{call}->(@_);
1639 }
1640
1641 sub rcs_prepedit ($) {
1642         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1643 }
1644
1645 sub rcs_commit ($$$;$$) {
1646         $hooks{rcs}{rcs_commit}{call}->(@_);
1647 }
1648
1649 sub rcs_commit_staged ($$$) {
1650         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1651 }
1652
1653 sub rcs_add ($) {
1654         $hooks{rcs}{rcs_add}{call}->(@_);
1655 }
1656
1657 sub rcs_remove ($) {
1658         $hooks{rcs}{rcs_remove}{call}->(@_);
1659 }
1660
1661 sub rcs_rename ($$) {
1662         $hooks{rcs}{rcs_rename}{call}->(@_);
1663 }
1664
1665 sub rcs_recentchanges ($) {
1666         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1667 }
1668
1669 sub rcs_diff ($) {
1670         $hooks{rcs}{rcs_diff}{call}->(@_);
1671 }
1672
1673 sub rcs_getctime ($) {
1674         $hooks{rcs}{rcs_getctime}{call}->(@_);
1675 }
1676
1677 sub rcs_receive () {
1678         $hooks{rcs}{rcs_receive}{call}->();
1679 }
1680
1681 sub add_depends ($$) {
1682         my $page=shift;
1683         my $pagespec=shift;
1684         
1685         return unless pagespec_valid($pagespec);
1686
1687         if (! exists $depends{$page}) {
1688                 $depends{$page}=$pagespec;
1689         }
1690         else {
1691                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1692         }
1693
1694         return 1;
1695 }
1696
1697 sub file_pruned ($$) {
1698         require File::Spec;
1699         my $file=File::Spec->canonpath(shift);
1700         my $base=File::Spec->canonpath(shift);
1701         $file =~ s#^\Q$base\E/+##;
1702
1703         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1704         return $file =~ m/$regexp/ && $file ne $base;
1705 }
1706
1707 sub gettext {
1708         # Only use gettext in the rare cases it's needed.
1709         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1710             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1711             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1712                 if (! $gettext_obj) {
1713                         $gettext_obj=eval q{
1714                                 use Locale::gettext q{textdomain};
1715                                 Locale::gettext->domain('ikiwiki')
1716                         };
1717                         if ($@) {
1718                                 print STDERR "$@";
1719                                 $gettext_obj=undef;
1720                                 return shift;
1721                         }
1722                 }
1723                 return $gettext_obj->get(shift);
1724         }
1725         else {
1726                 return shift;
1727         }
1728 }
1729
1730 sub yesno ($) {
1731         my $val=shift;
1732
1733         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1734 }
1735
1736 sub inject {
1737         # Injects a new function into the symbol table to replace an
1738         # exported function.
1739         my %params=@_;
1740
1741         # This is deep ugly perl foo, beware.
1742         no strict;
1743         no warnings;
1744         if (! defined $params{parent}) {
1745                 $params{parent}='::';
1746                 $params{old}=\&{$params{name}};
1747                 $params{name}=~s/.*:://;
1748         }
1749         my $parent=$params{parent};
1750         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1751                 $ns = $params{parent} . $ns;
1752                 inject(%params, parent => $ns) unless $ns eq '::main::';
1753                 *{$ns . $params{name}} = $params{call}
1754                         if exists ${$ns}{$params{name}} &&
1755                            \&{${$ns}{$params{name}}} == $params{old};
1756         }
1757         use strict;
1758         use warnings;
1759 }
1760
1761 sub add_link ($$) {
1762         my $page=shift;
1763         my $link=shift;
1764
1765         push @{$links{$page}}, $link
1766                 unless grep { $_ eq $link } @{$links{$page}};
1767 }
1768
1769 sub pagespec_merge ($$) {
1770         my $a=shift;
1771         my $b=shift;
1772
1773         return $a if $a eq $b;
1774         return "($a) or ($b)";
1775 }
1776
1777 sub pagespec_translate ($) {
1778         my $spec=shift;
1779
1780         # Convert spec to perl code.
1781         my $code="";
1782         my @data;
1783         while ($spec=~m{
1784                 \s*             # ignore whitespace
1785                 (               # 1: match a single word
1786                         \!              # !
1787                 |
1788                         \(              # (
1789                 |
1790                         \)              # )
1791                 |
1792                         \w+\([^\)]*\)   # command(params)
1793                 |
1794                         [^\s()]+        # any other text
1795                 )
1796                 \s*             # ignore whitespace
1797         }igx) {
1798                 my $word=$1;
1799                 if (lc $word eq 'and') {
1800                         $code.=' &&';
1801                 }
1802                 elsif (lc $word eq 'or') {
1803                         $code.=' ||';
1804                 }
1805                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1806                         $code.=' '.$word;
1807                 }
1808                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1809                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1810                                 push @data, $2;
1811                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1812                         }
1813                         else {
1814                                 push @data, qq{unknown function in pagespec "$word"};
1815                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1816                         }
1817                 }
1818                 else {
1819                         push @data, $word;
1820                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1821                 }
1822         }
1823
1824         if (! length $code) {
1825                 $code="IkiWiki::FailReason->new('empty pagespec')";
1826         }
1827
1828         no warnings;
1829         return eval 'sub { my $page=shift; '.$code.' }';
1830 }
1831
1832 sub pagespec_match ($$;@) {
1833         my $page=shift;
1834         my $spec=shift;
1835         my @params=@_;
1836
1837         # Backwards compatability with old calling convention.
1838         if (@params == 1) {
1839                 unshift @params, 'location';
1840         }
1841
1842         my $sub=pagespec_translate($spec);
1843         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1844                 if $@ || ! defined $sub;
1845         return $sub->($page, @params);
1846 }
1847
1848 sub pagespec_match_list ($$;@) {
1849         my $pages=shift;
1850         my $spec=shift;
1851         my @params=@_;
1852
1853         my $sub=pagespec_translate($spec);
1854         error "syntax error in pagespec \"$spec\""
1855                 if $@ || ! defined $sub;
1856         
1857         my @ret;
1858         my $r;
1859         foreach my $page (@$pages) {
1860                 $r=$sub->($page, @params);
1861                 push @ret, $page if $r;
1862         }
1863
1864         if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1865                 error(sprintf(gettext("cannot match pages: %s"), $r));
1866         }
1867         else {
1868                 return @ret;
1869         }
1870 }
1871
1872 sub pagespec_valid ($) {
1873         my $spec=shift;
1874
1875         my $sub=pagespec_translate($spec);
1876         return ! $@;
1877 }
1878
1879 sub glob2re ($) {
1880         my $re=quotemeta(shift);
1881         $re=~s/\\\*/.*/g;
1882         $re=~s/\\\?/./g;
1883         return $re;
1884 }
1885
1886 package IkiWiki::FailReason;
1887
1888 use overload (
1889         '""'    => sub { ${$_[0]} },
1890         '0+'    => sub { 0 },
1891         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1892         fallback => 1,
1893 );
1894
1895 sub new {
1896         my $class = shift;
1897         my $value = shift;
1898         return bless \$value, $class;
1899 }
1900
1901 package IkiWiki::ErrorReason;
1902
1903 our @ISA = 'IkiWiki::FailReason';
1904
1905 package IkiWiki::SuccessReason;
1906
1907 use overload (
1908         '""'    => sub { ${$_[0]} },
1909         '0+'    => sub { 1 },
1910         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1911         fallback => 1,
1912 );
1913
1914 sub new {
1915         my $class = shift;
1916         my $value = shift;
1917         return bless \$value, $class;
1918 };
1919
1920 package IkiWiki::PageSpec;
1921
1922 sub derel ($$) {
1923         my $path=shift;
1924         my $from=shift;
1925
1926         if ($path =~ m!^\./!) {
1927                 $from=~s#/?[^/]+$## if defined $from;
1928                 $path=~s#^\./##;
1929                 $path="$from/$path" if length $from;
1930         }
1931
1932         return $path;
1933 }
1934
1935 sub match_glob ($$;@) {
1936         my $page=shift;
1937         my $glob=shift;
1938         my %params=@_;
1939         
1940         $glob=derel($glob, $params{location});
1941
1942         my $regexp=IkiWiki::glob2re($glob);
1943         if ($page=~/^$regexp$/i) {
1944                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1945                         return IkiWiki::SuccessReason->new("$glob matches $page");
1946                 }
1947                 else {
1948                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1949                 }
1950         }
1951         else {
1952                 return IkiWiki::FailReason->new("$glob does not match $page");
1953         }
1954 }
1955
1956 sub match_internal ($$;@) {
1957         return match_glob($_[0], $_[1], @_, internal => 1)
1958 }
1959
1960 sub match_link ($$;@) {
1961         my $page=shift;
1962         my $link=lc(shift);
1963         my %params=@_;
1964
1965         $link=derel($link, $params{location});
1966         my $from=exists $params{location} ? $params{location} : '';
1967
1968         my $links = $IkiWiki::links{$page};
1969         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1970         my $bestlink = IkiWiki::bestlink($from, $link);
1971         foreach my $p (@{$links}) {
1972                 if (length $bestlink) {
1973                         return IkiWiki::SuccessReason->new("$page links to $link")
1974                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1975                 }
1976                 else {
1977                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1978                                 if match_glob($p, $link, %params);
1979                         $p=~s/^\///;
1980                         $link=~s/^\///;
1981                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1982                                 if match_glob($p, $link, %params);
1983                 }
1984         }
1985         return IkiWiki::FailReason->new("$page does not link to $link");
1986 }
1987
1988 sub match_backlink ($$;@) {
1989         return match_link($_[1], $_[0], @_);
1990 }
1991
1992 sub match_created_before ($$;@) {
1993         my $page=shift;
1994         my $testpage=shift;
1995         my %params=@_;
1996         
1997         $testpage=derel($testpage, $params{location});
1998
1999         if (exists $IkiWiki::pagectime{$testpage}) {
2000                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2001                         return IkiWiki::SuccessReason->new("$page created before $testpage");
2002                 }
2003                 else {
2004                         return IkiWiki::FailReason->new("$page not created before $testpage");
2005                 }
2006         }
2007         else {
2008                 return IkiWiki::FailReason->new("$testpage has no ctime");
2009         }
2010 }
2011
2012 sub match_created_after ($$;@) {
2013         my $page=shift;
2014         my $testpage=shift;
2015         my %params=@_;
2016         
2017         $testpage=derel($testpage, $params{location});
2018
2019         if (exists $IkiWiki::pagectime{$testpage}) {
2020                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2021                         return IkiWiki::SuccessReason->new("$page created after $testpage");
2022                 }
2023                 else {
2024                         return IkiWiki::FailReason->new("$page not created after $testpage");
2025                 }
2026         }
2027         else {
2028                 return IkiWiki::FailReason->new("$testpage has no ctime");
2029         }
2030 }
2031
2032 sub match_creation_day ($$;@) {
2033         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2034                 return IkiWiki::SuccessReason->new('creation_day matched');
2035         }
2036         else {
2037                 return IkiWiki::FailReason->new('creation_day did not match');
2038         }
2039 }
2040
2041 sub match_creation_month ($$;@) {
2042         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2043                 return IkiWiki::SuccessReason->new('creation_month matched');
2044         }
2045         else {
2046                 return IkiWiki::FailReason->new('creation_month did not match');
2047         }
2048 }
2049
2050 sub match_creation_year ($$;@) {
2051         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2052                 return IkiWiki::SuccessReason->new('creation_year matched');
2053         }
2054         else {
2055                 return IkiWiki::FailReason->new('creation_year did not match');
2056         }
2057 }
2058
2059 sub match_user ($$;@) {
2060         shift;
2061         my $user=shift;
2062         my %params=@_;
2063         
2064         if (! exists $params{user}) {
2065                 return IkiWiki::ErrorReason->new("no user specified");
2066         }
2067
2068         if (defined $params{user} && lc $params{user} eq lc $user) {
2069                 return IkiWiki::SuccessReason->new("user is $user");
2070         }
2071         elsif (! defined $params{user}) {
2072                 return IkiWiki::FailReason->new("not logged in");
2073         }
2074         else {
2075                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2076         }
2077 }
2078
2079 sub match_admin ($$;@) {
2080         shift;
2081         shift;
2082         my %params=@_;
2083         
2084         if (! exists $params{user}) {
2085                 return IkiWiki::ErrorReason->new("no user specified");
2086         }
2087
2088         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2089                 return IkiWiki::SuccessReason->new("user is an admin");
2090         }
2091         elsif (! defined $params{user}) {
2092                 return IkiWiki::FailReason->new("not logged in");
2093         }
2094         else {
2095                 return IkiWiki::FailReason->new("user is not an admin");
2096         }
2097 }
2098
2099 sub match_ip ($$;@) {
2100         shift;
2101         my $ip=shift;
2102         my %params=@_;
2103         
2104         if (! exists $params{ip}) {
2105                 return IkiWiki::ErrorReason->new("no IP specified");
2106         }
2107
2108         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2109                 return IkiWiki::SuccessReason->new("IP is $ip");
2110         }
2111         else {
2112                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2113         }
2114 }
2115
2116 1