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