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