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