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