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